From 2efa7838df6e6e9359c20871cd3350d648de1a92 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 14:30:36 +0800 Subject: [PATCH 01/19] docs(design): target contracts for the Session scope and its host ports Define the owners behind #2025: SessionScope and the four Session host ports. Each contract follows docs/templates/owner-redesign.md. - SessionScope: one `sessionScope` face for the creation record, identity, phase, leases, fault record, content mounts and branch construction. - RequestSettings: `prepareModelHost` becomes a value. - ContextFacts: `contextModelHost` becomes four reads. - ContextProjection: `historyRenderer` becomes branch-scoped reads; the Session-level fold by branch id is removed. - SummaryStrategy: `compactionStrategyHost` becomes two operations and the model object leaves the input. Refs #2025 --- docs/design/plugins/ContextFacts.md | 228 +++++++++++++++++ docs/design/plugins/ContextProjection.md | 248 ++++++++++++++++++ docs/design/plugins/README.md | 5 + docs/design/plugins/RequestSettings.md | 135 ++++++++++ docs/design/plugins/SessionScope.md | 306 +++++++++++++++++++++++ docs/design/plugins/SummaryStrategy.md | 238 ++++++++++++++++++ 6 files changed, 1160 insertions(+) create mode 100644 docs/design/plugins/ContextFacts.md create mode 100644 docs/design/plugins/ContextProjection.md create mode 100644 docs/design/plugins/RequestSettings.md create mode 100644 docs/design/plugins/SessionScope.md create mode 100644 docs/design/plugins/SummaryStrategy.md diff --git a/docs/design/plugins/ContextFacts.md b/docs/design/plugins/ContextFacts.md new file mode 100644 index 0000000000..123b0337bb --- /dev/null +++ b/docs/design/plugins/ContextFacts.md @@ -0,0 +1,228 @@ +# Context facts + +Scope: session. Issue: #2025. + +The owner answers a model's context limits and how many tokens a request, a message or a request's fixed prefix take. Today the same need is the `contextModelHost` object: a `resolve(request)` call that returns an object whose methods the callers use one at a time. This document replaces the object with four reads. The owner has no state beyond its resolved counting rules and writes nothing. + +## Use and scope: responsibility split + +The owner answers: + +- **The model's limits.** The context window, the output allowance every request reserves, the input threshold that triggers compaction, and the counting algorithm's identity when one exists. +- **A request's count.** The tokens of one complete request as the model's counter sees them. +- **A request's components.** The fixed contribution (system and tools), one contribution per message, and the estimate of a contribution. + +Callers keep: + +- What the budget decision is: ContextPreparation's threshold rule, the retention reserve and the fallback cuts. +- Which requests are counted and when a saved count may be reused: ContextUsage's statistics and its baseline association. +- How a summary's planned size is computed: the summary owner asks for the planned message's count. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| ContextPreparation decides whether a request is over the input budget | No: the limits, the reserve rule and the counter are the owner's knowledge; composing them in the caller duplicates the model's capacity facts | `describe`, `count` | +| Loop runs a compaction step and needs the window and the request's count | Yes: `describe` and `count` | Business composition | +| ContextUsage records a request's statistics additively | No: the counter's algorithm, its fixed contribution and its per-message contribution are one counting rule; splitting them across callers breaks the equality between `count` and the sum of the components | `contributions`, `estimate` | +| The summary owner plans the replacement size | Yes: `describe` for the algorithm and `count` for the planned message | Business composition | + +## Caller example + +```rust +// ContextPreparation: one request's budget. +let facts = facts.describe(DescribeRequest { model: selection.clone() }).await?; +let counted = facts.count(CountRequest { model: selection.clone(), request: request.clone() }).await?; +let over = counted.tokens > facts.threshold_tokens; +``` + +```rust +// ContextUsage: the contributions of one request, when the model has an additive counter. +let described = facts.describe(DescribeRequest { model: selection.clone() }).await?; +let Some(algorithm) = described.algorithm else { + return Err(UsageError::NotCountable); // the caller keeps complete-request counts only +}; +let parts = facts.contributions(ContributionsRequest { + model: selection, + fixed: Some(Fixed { system, tools }), + messages, +}).await?; +let total: f64 = parts.fixed.map(|fixed| fixed.estimated).unwrap_or_default() + + parts.messages.iter().map(|message| message.estimated).sum::(); +``` + +## Own contract + +### Dependencies + +None. The capability snapshot, the config and the messages arrive in the request data; the model catalog is read by the profile that installs the owner, not while answering. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `describe` | The model's limits and counter identity | `{model}` | `{contextWindow, outputTokens, thresholdTokens, algorithm?}` | None; the owner completes the read | `not_adopted`, `closed` | +| `count` | One complete request's tokens | `{model, request}` | `{tokens}` | None | `not_adopted`, `closed` | +| `contributions` | The fixed and per-message contributions of a request | `{model, fixed?, messages}` | `{algorithm, fixed?, messages}` | None | `not_adopted`, `unsupported`, `closed` | +| `estimate` | The tokens of one contribution | `{model, algorithm, contribution}` | `{tokens}` | None | `not_adopted`, `unsupported`, `algorithm_mismatch`, `closed` | + +`model` is the Session's model selection: provider, model, adopted capability snapshot, config and metadata. `contributions` answers contributions in request order and, when `fixed` is present, the fixed contribution of the given system and tools. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `not_adopted` | all | Adopt the model again and retry: the snapshot is missing, belongs to another provider or model, or the output allowance is absent | +| `unsupported` | `contributions`, `estimate` | This model has no additive counter; keep only complete-request counts | +| `algorithm_mismatch` | `estimate` | Recompute with the algorithm `describe` and `contributions` reported; a saved contribution of another algorithm cannot be estimated | +| `closed` | all | This generation is unloading; call the replacement generation | + +`describe` and `count` do not fail for a model without an additive counter: `algorithm` is absent and `count` still answers. + +### Flows + +The four operations hold no resource and wait for nothing; their rows cover only owner close. + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `describe`, `count`, `contributions`, `estimate` | The owner resolves the model from the request data, counts and answers | A dropped call answers nothing and leaves nothing | An in-flight call ends `closed`; the generation answers no further call | The calling row drops the call; the owner closes | + +## Exceptions with reasons + +- `algorithm` is absent for a model whose count cannot be composed from contributions: reporting an algorithm it does not have would make `contributions` and `estimate` look available. +- `estimate` takes the algorithm as data: a caller that saved contributions in a Timeline fact reads them back after a restart, and the saved algorithm is the only proof that the numbers share one rule. +- `not_adopted` covers both a missing snapshot and a snapshot of another model: the caller's next step is the same, adopting the model again. + +## Verification + +- `describe` answers the window, allowance and threshold of an adopted model; a missing or foreign snapshot is `not_adopted`. +- `count` equals the fixed contribution plus the message contributions summed through `estimate`, for a model with an additive counter. +- `contributions` is `unsupported` for a model without a counter; `estimate` with another algorithm is `algorithm_mismatch`. +- A call in flight when the generation closes ends `closed`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part publishing four reads; it writes no Timeline event and folds no state. | +| §2 scopes | Session: the limits are properties of the model the Session runs, shared by its branches. | +| §3 orthogonality | No other owner's state is read; the model selection is data. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handover of an object: the reply is data. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning: the budget rule stays with ContextPreparation. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path. | +| §4 rule 7 | Callers use the reads; no caller holds a counter object. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact: counts are statistics, persisted by ContextUsage in its own record. | +| §7 values, ids and objects | Every reply is a value; the old `Arc` no longer crosses. | +| §7 one interface | One name, `contextFacts`, on the owner type. | +| §7 cross-language | Requests and replies are data. | +| ADR 002 D1 | Session: the model facts are shared by the Session's branches. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | The profile that installs the owner reads its catalog; the owner injects nothing. | +| ADR 002 D5 | Data contract; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_runtime::{ModelSelection, PublicService}; +use dim_agent_types::{Message, ModelRequest, SystemPrompt, ToolDefinition}; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DescribeRequest { + pub model: ModelSelection, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Limits { + pub context_window: f64, + pub output_tokens: f64, + pub threshold_tokens: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub algorithm: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CountRequest { + pub model: ModelSelection, + pub request: ModelRequest, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CountReply { + pub tokens: f64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Fixed { + pub system: Option, + pub tools: Option>, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ContributionsRequest { + pub model: ModelSelection, + pub fixed: Option, + pub messages: Vec, +} + +#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Contribution { + pub serialized_bytes: u64, + pub images: u64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ContributionsReply { + pub algorithm: String, + pub fixed: Option, + pub messages: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EstimateRequest { + pub model: ModelSelection, + pub algorithm: String, + pub contribution: Contribution, +} + +#[derive(Debug, thiserror::Error)] +pub enum ContextFactsError { + #[error("{0}")] + NotAdopted(String), + #[error("{0}")] + Unsupported(String), + #[error("{0}")] + AlgorithmMismatch(String), + #[error("{0}")] + Closed(String), +} + +impl PublicService for ContextFacts {} + +#[rutis::service(name = "contextFacts")] +impl ContextFacts { + pub async fn describe(&self, request: DescribeRequest) -> Result { /* ... */ } + pub async fn count(&self, request: CountRequest) -> Result { /* ... */ } + pub async fn contributions( + &self, + request: ContributionsRequest, + ) -> Result { /* ... */ } + pub async fn estimate(&self, request: EstimateRequest) -> Result { /* ... */ } +} +``` + +`ContributionsReply.fixed` and `.messages` are token counts, aligned with the request's messages; `Contribution` stays the serialized-bytes and image facts the counter works from. diff --git a/docs/design/plugins/ContextProjection.md b/docs/design/plugins/ContextProjection.md new file mode 100644 index 0000000000..5f9d5896a5 --- /dev/null +++ b/docs/design/plugins/ContextProjection.md @@ -0,0 +1,248 @@ +# Context projection + +Scope: branch. Issue: #2025. + +The owner folds its own branch's facts into the context a model request carries, renders that context to messages, and encodes or decodes the recovery snapshot that lets a later fold start after a compaction. Today the same need is the `historyRenderer` value: a table of Rust functions at Session scope, whose methods take a caller-supplied `&Timeline` or `&Session`, plus a Session-level `context_in` that folds another branch's history by id. This document replaces the value with branch-scoped operations. + +## Use and scope: responsibility split + +The owner answers: + +- **The context at a cutoff.** Which events place context, how a compaction's replacement and baseline apply, and the positions the fold covered. +- **Rendered entries.** The context and its `HistoryEntry` list at one cutoff, for callers that need both. +- **A request-local projection.** The same content as the fold's streamed form, so a long history is released page by page instead of held whole. +- **Recovery snapshots.** Encode the projection at a completed compaction's cut, validate a saved snapshot against its anchor, and decode the checkpoint it carries. + +Callers keep: + +- Which cutoff a request uses: Loop's committed position and its fixed `through`. +- Whether a saved count or projection may be reused: ContextPreparation's validation rules. +- When a snapshot is saved and which interpreter is current: ContextPreparation's compaction flow. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Loop builds a request's context at a fixed cutoff | No: which events carry context, how compaction replaces a range and how the baseline folds are the owner's knowledge; composing them from `timeline.query` puts a second projection in the caller | `renderedStream`, `renderedContext` | +| ContextPreparation checks the budget at its own cutoff and compacts | Yes: the same reads, and the projection Loop hands over | Business composition | +| A compaction saves its snapshot after the fact commits | No: encoding and the anchor check are one rule with decoding | `snapshot`, `streamCheckpoint` | +| A later preparation resumes from a saved snapshot | No: the owner validates the snapshot against its anchor before decoding | `snapshotFromCheckpoint`, `snapshot` | +| A test or an example inspects a folded context | Yes: `renderedContext` answers the context and the entries | Business | + +## Caller example + +```rust +// Loop: the request's context at the committed cutoff. +let streamed = projection + .rendered_stream(RenderedStreamRequest { through, batch: 256 }) + .await?; +let request = settings.request(streamed.history.iter().map(|entry| entry.message.clone()).collect()); +``` + +```rust +// ContextPreparation: the snapshot of a completed compaction. +let snapshot = projection + .snapshot(SnapshotRequest { context, retain_from: cut, anchor: fact.clone() }) + .await?; +``` + +```rust +// A later preparation: the checkpoint a saved snapshot carries, if the anchor matches. +let Some(checkpoint) = projection + .snapshot_from_checkpoint(SnapshotFromCheckpointRequest { checkpoint, anchor }) + .await? +else { + return Ok(None); // the snapshot does not resume here; the fold starts earlier +}; +``` + +## Own contract + +### Dependencies + +`B:Timeline` — the owner folds the branch's own facts through the branch's Timeline operations; it never asks another branch or the Session for events. The projection policy is factory configuration: the assembly installs the owner with the policy in force, and a host that needs another policy installs another part. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `renderedStream` | The context and rendered entries at a cutoff, folded page by page | `{through, batch}` | `{context, history, configuration?, prompt?}` | The caller drops the call; the fold stops at its last page | `future_sequence`, `invalid`, `storage`, `closed` | +| `renderedContext` | The context and rendered entries at a cutoff | `{through}` | `{context, history}` | The caller drops the call | `future_sequence`, `storage`, `closed` | +| `snapshot` | Encode the projection at a completed compaction's cut | `{context, retainFrom, anchor}` | `{snapshot}` | None; the owner completes the read | `invalid`, `storage`, `closed` | +| `streamCheckpoint` | The checkpoint of the fold that starts after a compaction's cut | `{through, retainFrom, batch}` | `{checkpoint}` | The caller drops the call | `future_sequence`, `invalid`, `storage`, `closed` | +| `snapshotFromCheckpoint` | A snapshot that carries an already-computed checkpoint | `{checkpoint, anchor}` | `{snapshot}` or none when the anchor does not match | None | `invalid`, `storage`, `closed` | + +`through` is a committed sequence of this branch; `batch` is the page size of the fold; `retainFrom` is the id of the compaction's cut event; `anchor` is the completed compaction fact a snapshot anchors to. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `future_sequence` | `renderedStream`, `renderedContext`, `streamCheckpoint` | Fix the cutoff: it is above the branch's committed head | +| `invalid` | all | Fix the request: a batch size of zero, a cut outside the branch chain, an anchor that is not a completed compaction, a snapshot whose interpreter is not current | +| `storage` | all | The branch's facts could not be read; the request fails for this attempt; a retry re-reads | +| `closed` | all | The branch is closing; stop preparing requests | + +`snapshotFromCheckpoint` answers none, not an error, when the snapshot cannot be used at that anchor: the caller folds from an earlier point. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `renderedStream` | The owner selects the snapshot a checkpoint validates, folds page by page from its resume position, releases each page, and answers the streamed projection | A dropped call stops the fold at its last page; no state is written | An in-flight fold ends `closed`; the generation answers no further call | The calling row drops the call; the owner holds no resource between pages | +| `renderedContext` | The owner folds the same content without the request-local form | A dropped call ends the read | `closed` | The owner | +| `snapshot` | The owner folds to the cut, builds the checkpoint and encodes it with the snapshot's digest | A dropped call answers nothing; nothing is written | `closed` | The owner | +| `streamCheckpoint` | The owner finds the cut's position, resumes from a valid snapshot and folds to the cutoff | A dropped call ends the fold | `closed` | The owner | +| `snapshotFromCheckpoint` | The owner encodes the given checkpoint at the anchor | A dropped call ends the read | `closed` | The owner | + +## Exceptions with reasons + +- `renderedStream` and `renderedContext` take a cutoff, not a branch id: the owner is a branch part and folds its own branch's facts; a Session-scoped fold by branch id returned another owner's history and is removed. +- The projection policy is factory configuration rather than a Session value: a table of Rust functions cannot cross languages, and a host that substitutes the projection installs another part, so no Rust-only value sits on the public face. +- `snapshotFromCheckpoint` answers none instead of failing when the anchor does not match: a snapshot is optional acceleration, and the caller's next step is the same fold the snapshot would have skipped. +- `streamCheckpoint` takes `batch`: a streamed fold's page size is the caller's memory decision, and the checkpoint must be built from the same fold the caller will use. + +## Verification + +- A fold at a cutoff returns the events that place context and the compaction in force, with positions that compare across the branch chain. +- `renderedStream` releases each page: a fold larger than one page keeps only the current projection. +- `snapshot` encodes the checkpoint of a completed compaction; a snapshot of another interpreter or a mismatched anchor is `invalid` or answers none. +- `context_in` no longer exists; every read is the caller's own branch. +- A call in flight when the branch closes ends `closed`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One branch part. It folds the branch's facts but writes none, so it is not a Capability; the projection policy is its factory configuration. | +| §2 scopes | Branch. The fold reads its own branch's Timeline and nothing across scopes. | +| §3 orthogonality | No other owner's state is read; the projection is a pure function of the branch's public facts. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handover of a business object; the streamed projection is a value. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | The projection policy is configuration, not a core special case. | +| §4 rule 5 | The fold reads committed facts; publishing facts is not affected. | +| §4 rule 6 | The projection renders what the branch's adopted inputs and tool results placed; it adds no context path of its own. | +| §4 rule 7 | Callers use these operations; no caller folds from `timeline.query` itself. | +| §4 rule 8 | No infrastructure change: the branch's Timeline already serves the reads. | +| §4 rule 9 | No Timeline fact; a snapshot is optional derived state. | +| §7 values, ids and objects | Every reply is a value; the caller's `&Timeline` and `&Session` no longer cross. | +| §7 no proxy lookup | The owner folds its own branch; the Session-level `context_in` is removed. | +| §7 one interface | One name, `contextProjection`, on the owner type; `historyRenderer` leaves the catalog. | +| §7 cross-language | Requests and replies are data. | +| ADR 002 D1 | Branch: the projection is derived from the branch's facts and shares their lifetime. | +| ADR 002 D2 | No wiring plugin: the part is the owner; the policy is its configuration. | +| ADR 002 D3 | Depends on the branch's Timeline, at its own scope. | +| ADR 002 D5 | Data contract; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None: the owner needs only the branch's `timeline` operations. + +## Binding appendix + +```rust +use dim_agent_runtime::{ContextHistory, PublicService}; +use dim_agent_types::{AgentEvent, HistoryEntry, ProjectionCheckpoint, RecoverySnapshot, TimelinePosition}; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RenderedStreamRequest { + pub through: u64, + pub batch: u64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StreamedContext { + pub context: ContextHistory, + pub history: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub configuration: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub prompt: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RenderedContextRequest { + pub through: u64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RenderedContextReply { + pub context: ContextHistory, + pub history: Vec, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SnapshotRequest { + pub context: ContextHistory, + pub retain_from: String, + pub anchor: AgentEvent, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SnapshotReply { + pub snapshot: RecoverySnapshot, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct StreamCheckpointRequest { + pub through: u64, + pub retain_from: String, + pub batch: u64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CheckpointReply { + pub checkpoint: ProjectionCheckpoint, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SnapshotFromCheckpointRequest { + pub checkpoint: ProjectionCheckpoint, + pub anchor: AgentEvent, +} + +#[derive(Debug, thiserror::Error)] +pub enum ProjectionError { + #[error("{0}")] + FutureSequence(String), + #[error("{0}")] + Invalid(String), + #[error("{0}")] + Storage(String), + #[error("the projection owner is unloading")] + Closed, +} + +impl PublicService for ContextProjection {} + +#[rutis::service(name = "contextProjection")] +impl ContextProjection { + pub async fn rendered_stream( + &self, + request: RenderedStreamRequest, + ) -> Result { /* ... */ } + pub async fn rendered_context( + &self, + request: RenderedContextRequest, + ) -> Result { /* ... */ } + pub async fn snapshot(&self, request: SnapshotRequest) -> Result { /* ... */ } + pub async fn stream_checkpoint( + &self, + request: StreamCheckpointRequest, + ) -> Result { /* ... */ } + pub async fn snapshot_from_checkpoint( + &self, + request: SnapshotFromCheckpointRequest, + ) -> Result, ProjectionError> { /* ... */ } +} +``` + +`ContextHistory`, `HistoryEntry`, `ProjectionCheckpoint`, `RecoverySnapshot`, `AgentEvent` and `TimelinePosition` are the types those facts already use; the reply carries no event handle beyond the events the facts are. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..fff906249a 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,11 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Plugin | Process part | Session part | Branch part | Phase / issue | | --- | --- | --- | --- | --- | +| [SessionScope](SessionScope.md) (owner contract) | — | the Session's creation record, identity, phase, leases, fault record, content mounts and branch construction behind `sessionScope` | — | [#2025](https://github.com/arcships/dim/issues/2025) | +| [Request settings](RequestSettings.md) (owner contract) | — | the default request settings value behind `requestSettings` | — | [#2025](https://github.com/arcships/dim/issues/2025) | +| [Context facts](ContextFacts.md) (owner contract) | — | the model's limits and token counting behind `contextFacts` | — | [#2025](https://github.com/arcships/dim/issues/2025) | +| [Context projection](ContextProjection.md) (owner contract) | — | — | the branch's context fold and recovery snapshots behind `contextProjection` | [#2025](https://github.com/arcships/dim/issues/2025) | +| [Summary strategy](SummaryStrategy.md) (owner contract) | — | the summary policy for compaction behind `summaryStrategy` | — | [#2025](https://github.com/arcships/dim/issues/2025) | | [Migration](Migration.md) | on-demand import tasks, source mappings, progress and retry records; unloaded after settlement | — | — | [Delivery plan](../../plan/analysis/legacy-migration.md) | | [Provider management](../appserver/provider-management.md) | existing Provider: configuration, catalogs, client preferences and management methods | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` tool, `session.question.respond`, waiters of running `ask_user` calls; no events | — | M2; #262 | diff --git a/docs/design/plugins/RequestSettings.md b/docs/design/plugins/RequestSettings.md new file mode 100644 index 0000000000..983a464efd --- /dev/null +++ b/docs/design/plugins/RequestSettings.md @@ -0,0 +1,135 @@ +# Request settings + +Scope: session. Issue: #2025. + +The owner publishes the model settings a turn starts from: the Session's model selection, its adopted capability snapshot, the config to send and the request metadata, as one value. Today the same need is the `prepareModelHost` object port; this document replaces it. The owner has no state of its own and writes nothing. + +## Use and scope: responsibility split + +The owner publishes: + +- **The default settings value.** `{providerId, modelId, capabilitySnapshot?, config?, system?, metadata?}` derived once, when the Session is assembled, from the creation record and — when the profile has one — the model catalog. +- **The allowance repair.** The adopted output allowance is bounded by the model's declared output and half the window before the value is published; callers never recompute it. + +Callers keep: + +- Which messages the request carries: Loop's history and guide. +- Which tools it declares: ToolBinding's pinned definitions for the request. +- The turn and request ids and the session id in the metadata: Loop writes them. +- The adopted configuration published during the run: Prompt adopts sources and model changes into the Timeline as `context/configured`, and Loop reads that record instead of this value. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Loop prepares the model settings of a turn that has no adopted configuration yet | No: the catalog defaults and the allowance rule are the owner's knowledge; composing them in Loop duplicates the provider profile's decision | `settings` | +| Loop requests with a configuration Prompt adopted during the run | Yes: Loop reads the adopted record from the Timeline | Business | +| A caller changes the model for the next turn | Yes: the Session's model methods write the record and Prompt adopts it | Business | + +## Caller example + +```rust +// Loop: the first request of a Session before any configuration is adopted. +let defaults = request_settings.settings()?; +let settings = ModelSettings { + provider_id: defaults.provider_id, + model_id: defaults.model_id, + capability_snapshot: defaults.capability_snapshot, + config: defaults.config, + system: Some(guide.compose_system(&branch, defaults.system)), + tools: Some(binding.definitions(&request_id)?), + metadata: defaults.metadata.map(|mut metadata| { + metadata.session_id = Some(session_id); + metadata.turn_id = Some(turn_id); + metadata + }), +}; +``` + +## Own contract + +### Dependencies + +None. The assembly provides the value; the aimux profile also reads its model catalog while building it. The owner reads no other owner's state. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `settings` | The Session's default request settings | `{}` | `{providerId, modelId, capabilitySnapshot?, config?, system?, metadata?}` | None | None | + +### Errors + +None: the value is fixed before the Session is published. A profile that cannot derive settings fails its own assembly instead of answering an error here. + +### Flows + +None: the operation holds no resource and waits for nothing. + +## Exceptions with reasons + +- `config` may already be the adopted allowance repair: the owner repairs the stored allowance against the declared limits, so a request started from this value cannot exceed the model's capacity. +- The value is fixed at creation: a model change during the run is a Timeline record (`context/configured`), and Loop reads that record; the value is never stale for its one use. +- `metadata` carries the profile's extensions (for example a request-id extension); the owner publishes them and Loop only adds the turn's ids. + +## Verification + +- `settings` answers the record's model, snapshot and config; with a catalog entry, the config is the catalog default repaired to the declared allowance. +- A Session whose configuration was adopted mid-run is requested from the adopted record, not from this value. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part that publishes a value; it writes no Timeline event and folds no state. | +| §2 scopes | Session: the value derives from the Session's record. | +| §3 orthogonality | No other owner's state is read after assembly. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handover of a business object. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning in the core: the provider profile decides the catalog defaults. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path: the value carries no messages. | +| §4 rule 7 | Loop calls the operation; no caller reads the owner's inputs. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact: settings that a later turn reads are Prompt's adopted record, not this value. | +| §7 values, ids and objects | The reply is a value; no object, id or handle crosses. | +| §7 one interface | One name, `requestSettings`, on the owner type; the old `prepareModelHost` operation and object are removed. | +| §7 cross-language | The reply is data. | +| ADR 002 D1 | Session: the settings derive from the Session's creation record. | +| ADR 002 D2 | No wiring plugin: the value is on the owner's own service and the part reads the catalog directly. | +| ADR 002 D3 | The aimux profile reads its own process service while assembling; the default profile reads nothing. | +| ADR 002 D5 | The contract is data; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_runtime::{ModelId, ModelSelection, PublicService}; +use dim_agent_types::{ModelCapabilitySnapshot, ModelConfig, RequestMetadata, SystemPrompt}; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RequestSettings { + pub provider_id: String, + pub model_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub capability_snapshot: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub system: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata: Option, +} + +impl PublicService for RequestSettings {} + +#[rutis::service(name = "requestSettings")] +impl RequestSettings { + pub fn settings(&self) -> RequestSettings { /* ... */ } +} +``` + +`ModelSelection`, `ModelId` and the reply's members are the crate's existing data; `settings` answers the value itself, as `agentConfig.get` did before this owner existed. diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md new file mode 100644 index 0000000000..f8365e42f1 --- /dev/null +++ b/docs/design/plugins/SessionScope.md @@ -0,0 +1,306 @@ +# SessionScope + +Scope: session. Issue: #2025. + +SessionScope is the runtime's Session owner: the creation record and identity, the phase, the activity leases and the failure record that accepted work and callers share, and the Session subtree's content instances. This document is the owner's target contract. The branch tree (#2024) and the Session store (#2018) are separate owners; their calls appear here only as dependencies or requirements. + +## Use and scope: responsibility split + +SessionScope owns: + +- **The creation record.** The Session's mount list, working directory, model selection, system prompt, permission preset, collaboration role, interactive flag, language seed and initial title, fixed when the Session is built. The record never changes while the Session runs. +- **Identity.** The Session id and whether the Session was restored from the store. +- **The phase.** Loading, Active, Closing, Closed, monotonic and never replaced by an earlier phase. `activated` and `closing` are the waits on the two transitions. +- **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. A lease is an id bound to the calling row: the row's unload releases every lease it still holds, and `release` ends one earlier. A lease reports nothing and cancels nothing. +- **The failure record.** The first fault that stopped the Session; a storage failure supersedes an earlier non-storage fault and the first storage failure wins. `reportFault` writes, `failure` reads, `observeFault` subscribes. +- **Content instances.** Session-owned content mounted from a definition — a Skill's content, an MCP connection — inside this Session's subtree, addressed by instance id. The owner admits only groups whose configured parent is the Session group. +- **The branch's runtime context.** One construction per branch id, handed to the branch tree, which owns and settles the context (see Exceptions with reasons). + +Callers keep as business: + +- When their background work may start and must stop: BranchLine, Skills, ShellInput and FileAccess wait on the phase. +- Which work counts as accepted and therefore holds a lease: ShellInput's command, BackgroundExec's task, Report's draft, Collaboration's member. +- What a fault means for their work; the failure record says only that the Session stopped. +- Which definitions to mount and when to retire them. +- Which branches exist, their ids and their ancestors: TimelineTree owns the branch directory (#2024). + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Read the creation record: WorkspaceTools' root and role, ToolRegistry's declaration, Permission's preset, ShellInput's cwd, PromptSources' system prompt and language seed | No: the record is the owner's state and has no other source | `config` | +| Read identity: Attachments' ownership check, Permission and tool-source attribution, the store key | No | `identity` | +| Wait for publication or for close to start: BranchLine's writer, Skills' replacement, ShellInput's refusal, FileAccess' gate | No: polling a value makes every caller write the wait | `activated`, `closing` | +| Read the phase now: Goal's state read, MCP's admission, ShellInput's refusal | No | `phase` | +| Keep accepted work from being ended by an idle release | No: the idle-release decision is the owner's, and composing it makes the caller hold a counter or a token across every error path | `hold` | +| End a lease early, after the work's last fact | No: the id is bound to the calling row and only the owner releases it | `release` | +| Record a fault: Prompt on a prompt or recovery failure | No | `reportFault` | +| Read the current fault | No | `failure` | +| Subscribe to later faults: a part in another language | No: a subscription is the owner's, not a poll loop in the caller | `observeFault` | +| Mount and retire Session content: Skills' content instances, MCP's connections | No: the Session's anchor and the group admission are the owner's knowledge | `mount`, `unmount` | +| Open a branch's runtime context: TimelineTree | No: only the runtime constructs a branch's context, in its own subtree | `openBranch` | + +An operation exists only where the row says No. + +## Caller example + +Skills replaces content after publication, and stops when the Session closes: + +```rust +if !scope.activated().await?.active { + return Ok(()); // the Session never published +} +let mounted = scope + .mount(MountDefinition { + group: CONTENT_GROUP.into(), + definition_id: skill.id.clone(), + instance_data: value, + }) + .await?; +scope.unmount(UnmountRequest { instance_id: mounted.instance_id }).await?; +``` + +ShellInput refuses after closing starts and holds the Session while a command runs: + +```rust +scope.phase()?; // closing or closed -> RpcError::closed() +let lease = scope.hold().await?.lease_id; +run_command(lease.clone(), cancel.clone()).await?; +scope.release(ReleaseRequest { lease_id: lease }).await?; +``` + +A part in another language subscribes to the fault record: + +```ts +const { leaseId } = await sessionScope.observeFault(async fault => { + if (fault?.storage) record(fault.storage) +}) +await sessionScope.release({ leaseId }) +``` + +TimelineTree opens a branch after admitting it: + +```rust +let branch = scope + .open_branch(OpenBranchRequest { branch_id: id, ancestors }, cancelled) + .await?; +// The tree owns `branch` from here: it hands it to the branch's parts and closes it +// before the Session scope unloads. +self.nodes.insert(id, branch); +``` + +## Own contract + +### Dependencies + +SessionScope injects nothing. The assembly gives the owner its creation record and the Session anchor; the trusted host installs the content definitions the Session may mount. SessionScope binds the store's `timelineStore` face at the Session instance (the operations belong to the Session store, #2018) and no longer provides the Agent's configuration, the Skills or Collaboration factory texts, or the five host ports; those names leave the catalog (delivery). + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `config` | The Session's creation record | `{}` | `SessionConfig` | None; the owner completes the read | None | +| `identity` | Who this Session is | `{}` | `{sessionId, restored}` | None | None | +| `phase` | The phase now | `{}` | `{phase}`: `loading`, `active`, `closing`, `closed` | None | None | +| `activated` | Wait until the Session is published or starts closing | `{}` | `{active}`: true only when published and not closing | The caller drops the call; the owner's close ends the wait with `active: false` | None | +| `closing` | Wait until the Session starts closing | `{}` | `{}` | The caller drops the call | None | +| `hold` | Keep an idle release from ending this Session | `{}` | `{leaseId}` | None; the call does not wait | `closed` | +| `observeFault` | Receive the current fault and later reports until released or the row unloads | `{listener}` | `{leaseId}` | None; the call does not wait | `closed` | +| `release` | End a lease or a subscription before the row unloads | `{leaseId}` | `{released}`: false when the id was already released | None | `invalid` when the id belongs to another row; `closed` | +| `reportFault` | Record the fault that stopped the Session | `{fault}` | `{}` | None | None | +| `failure` | The fault in force, if any | `{}` | `{fault?}` | None | None | +| `mount` | Create a Session-owned content instance from a definition | `{group, definitionId, instanceData}` | `{instanceId}` | The caller drops the call; an instance it no longer waits for is shut down before the reply | `invalid`, `not_ready`, `cleanup`, `closed` | +| `unmount` | Retire a content instance this Session owns | `{instanceId}` | `{}` | None; the owner completes the release | `invalid` when the id belongs to another Session; `cleanup`; `closed` | +| `openBranch` | Construct a branch's runtime context for the branch tree | `{branchId, ancestors}` | the branch's runtime context (see Exceptions) | The caller drops the call; a construction the caller abandoned is shut down before the branch becomes visible | `closed`, `build` | + +`listener` is a callback by reference: it runs outside the owner's locks and outside the Timeline's commit lock. A lease id is an owner-issued token; it carries no authority and is valid only for the calling row. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `closed` | `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | +| `invalid` | `release`, `unmount`, `mount` | Fix the id or the definition: an id of another row or Session, a group outside this Session's subtree, an unknown definition | +| `not_ready` | `mount` | Act on the reported row and state: the definition's rows did not activate; the instance was shut down and nothing is left to release | +| `cleanup` | `mount`, `unmount` | The instance is unreachable but its shutdown failed; the Session will report it as a fault; treat the content as unavailable | +| `build` | `openBranch` | The branch did not open: `cause` is why, `cleanup` is a shutdown that also failed; the tree records the branch as failed and settles it | + +`reportFault`, `failure`, `config`, `identity`, `phase`, `activated` and `closing` have no error kinds: nothing in the owner refuses them. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `hold` | The owner checks the phase, increments the hold count and registers the lease under the calling row | The row's unload releases every lease the row still holds | No new lease is issued once an idle release is decided; an existing lease never delays a close | SessionScope | +| `observeFault` | The owner registers a listener under the calling row, calls it once with the fault in force (none included), then on every later report | The row's unload stops the listener and drops the registration | The listener stays until the generation unloads; a report after close is ignored | SessionScope; the listener's work by the calling row | +| `release` | The owner removes the lease or subscription and disposes it | A dropped call leaves the lease in place; the row's unload settles it | An id of an unloaded generation is `closed` | SessionScope | +| `mount` | The owner creates the instance in the Session subtree, waits for its required rows, then answers the id | A dropped call shuts the half-made instance down; a definition that never activates is shut down and answers `not_ready` | New mounts are refused; in-flight mounts settle, and every instance is shut down when the Session scope unloads | SessionScope | +| `unmount` | The owner shuts the instance down, propagates a shutdown failure as `cleanup`, and forgets the id | A dropped call does not cancel the shutdown | The Session's unload shuts down every remaining instance | SessionScope | +| `openBranch` | The owner admits the id, waits for the branch scope and its required parts, and hands the context to the tree | A dropped call settles the half-made branch before it is visible | `closed` once the Session is closing; a Construction in flight settles or ends `closed` | SessionScope creates; TimelineTree holds and closes (Exceptions) | + +## Exceptions with reasons + +- `openBranch` hands out the branch's runtime context: an id would put branch runtime state behind a second set of operations owned by SessionScope, while ADR 002 D1 gives the branch's directory and close to TimelineTree, and the branch's whole capability machine runs behind that context. The joint design is [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md): the owner creates the context inside the Session subtree after the branch scope loads; TimelineTree holds it, hands it to the branch's parts and closes it; the Session unloads only after its branches close; a failed construction reports `cause` before `cleanup` and settles both before the branch is visible; a Session scope never reloads, so the context never outlives its generation. +- `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. +- The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. +- `identity` carries no version: the id and the restored flag are fixed at creation. +- A lease is a value, not a handle: it names nothing the caller can use except in `release`, and the owner releases every lease at the row's unload, so a caller that loses the id leaks nothing. + +## Verification + +- `hold` answers `closed` once an idle release is decided; a lease taken before it keeps the Session loaded until released, and never refuses a close. +- `observeFault` delivers the fault in force and later reports; `release` answers `released: true` then `false`; another row's id is `invalid`; the row's unload stops delivery. +- `reportFault` keeps the first fault; a storage fault after a non-storage one wins; a non-storage fault after a storage one loses. +- `mount` answers `invalid` for a group outside the Session's subtree, `not_ready` for a definition whose row failed (and leaves no instance), and shuts down an abandoned mount; `unmount` answers `cleanup` when the shutdown fails and `invalid` for another Session's id. +- `activated` answers false when the Session closes before publishing; `closing` returns when the close starts. +- `openBranch` answers `closed` during the Session's close; a failed construction settles the branch scope before the reply; the tree closes every branch before the Session scope unloads. +- `config`, `identity` and `phase` do not change while the Session runs. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part, the scope itself. It writes no Timeline event and folds no state, so it is not a Capability; it provides the Session's own state and the mounts. | +| §2 scopes | Session. Branch state and the branch directory stay with TimelineTree; the store's operations stay with the Session store. | +| §3 orthogonality | No other owner's state is read or changed. A caller that needs a new operation gets a general one here or composes it. | +| §4 rule 1 | No command event: the owner writes no Timeline fact. | +| §4 rule 2 | No handover of business objects; the phase and the fault record are the owner's own state. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | Core and assembly carry no business meaning: no content format, no prompt, no branch policy. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path: content instances are mounted for their own owners; the owner adds no model-visible text. | +| §4 rule 7 | Callers use these operations; no caller reads the hold count, the fault slot or an instance's fiber. | +| §4 rule 8 | No infrastructure change. SessionScope is the runtime's Session part and its shape is the runtime's decision; the operations above are the data face those decisions already require. | +| §4 rule 9 | No Timeline fact: the phase and the fault record are runtime state, read live and never persisted as events. | +| §7 values, ids and objects | The record, identity, phase and fault are values; leases and instance ids are ids bound to the calling row; the one object is `openBranch`, with the joint design above. | +| §7 no proxy lookup | The owner returns only its own state; the Agent's configuration and the Skills and Collaboration factory texts leave this face. | +| §7 one interface | One name, `sessionScope`, on the owner type; the Rust binding and the wire call the same methods; no facade or wrapper type. | +| §7 cross-language | Every operation is data, a callback by reference or an id; no method exists only for Rust. | +| §7 one change | The implementation task deletes the old names and migrates every caller in one change. | +| ADR 002 D1 | Session scope: the record, phase, leases, faults and mounts live and die with the Session. | +| ADR 002 D2 | No wiring plugin: the operations are on the owner type; no adapter exists beside it. | +| ADR 002 D3 | No dependency: SessionScope injects nothing. | +| ADR 002 D4 | The mount list and the record are structural; no business setting is read here. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix below. | + +## Requirements raised to mechanism owners + +- [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns `timelineStore`. SessionScope keeps binding that face at the Session instance; the store's contract must keep the binding and must not keep `createSession`, `releaseSession`, `rollbackSession` or `append` on it. The operations those four serve belong to the Agent's own path or to the owner's internal commit path. + +## Binding appendix + +The service is marked on the owner type under one name; the existing names `sessionConfig`, `sessionIdentity`, `sessionLifecycle`, `sessionLoader` and `timelineFactory` stop existing. + +```rust +use dim_agent_runtime::{PublicService, SessionConfig, SessionFault, SessionPhase}; +use rutis::Ctx; +use std::sync::Arc; + +pub type LeaseId = String; +pub type InstanceId = u64; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Identity { + pub session_id: String, + pub restored: bool, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PhaseReply { + pub phase: SessionPhase, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ActivatedReply { + pub active: bool, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LeaseRequest { + pub lease_id: LeaseId, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LeaseReply { + pub lease_id: LeaseId, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReleaseReply { + pub released: bool, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct MountDefinition { + pub group: String, + pub definition_id: String, + pub instance_data: serde_json::Value, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MountedInstance { + pub instance_id: InstanceId, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UnmountRequest { + pub instance_id: InstanceId, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OpenBranchRequest { + pub branch_id: String, + pub ancestors: Vec<(String, u64)>, +} + +pub type FaultListener = + Arc) -> rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + Send + Sync>; + +#[derive(Debug, thiserror::Error)] +pub enum SessionScopeError { + #[error("{0}")] + Closed(String), + #[error("{0}")] + Invalid(String), + #[error("{0}")] + NotReady(String), + #[error("{0}")] + Cleanup(String), + #[error("{0}")] + Build(String), +} + +impl PublicService for SessionScope {} + +#[rutis::service(name = "sessionScope")] +impl SessionScope { + pub fn config(&self) -> SessionConfig { /* ... */ } + pub fn identity(&self) -> Identity { /* ... */ } + pub fn phase(&self) -> PhaseReply { /* ... */ } + pub async fn activated(&self) -> ActivatedReply { /* ... */ } + pub async fn closing(&self) { /* ... */ } + pub async fn hold(&self) -> Result { /* ... */ } + pub async fn observe_fault(&self, listener: FaultListener) -> Result { /* ... */ } + pub async fn report_fault(&self, fault: SessionFault) { /* ... */ } + pub fn failure(&self) -> Option { /* ... */ } + pub async fn release(&self, request: LeaseRequest) -> Result { /* ... */ } + pub async fn mount(&self, definition: MountDefinition) -> Result { /* ... */ } + pub async fn unmount(&self, request: UnmountRequest) -> Result<(), SessionScopeError> { /* ... */ } + pub async fn open_branch( + &self, + caller: &Ctx, + request: OpenBranchRequest, + cancelled: dim_agent_capabilities::host::CancelledFn, + ) -> Result, SessionScopeError> { /* ... */ } +} +``` + +`caller: &Ctx` and `cancelled: CancelledFn` are the binding's caller row and cancellation argument; the dispatch fills them and no caller sends or names a row. `LeaseId`, `InstanceId` and the ancestor pairs cross as strings and numbers. diff --git a/docs/design/plugins/SummaryStrategy.md b/docs/design/plugins/SummaryStrategy.md new file mode 100644 index 0000000000..a8156fca42 --- /dev/null +++ b/docs/design/plugins/SummaryStrategy.md @@ -0,0 +1,238 @@ +# Summary strategy + +Scope: session. Issue: #2025. + +The owner replaces a range of a branch's history with a summary produced by model calls: it picks the cut the retention rule allows, summarizes the transcript in bounded chunks, and reports what it did. Today the same need is the `compactionStrategyHost` object, and `CompactionInput` carries the context model object so the owner can count. This document replaces the object with two operations and removes the object field. + +## Use and scope: responsibility split + +The owner answers: + +- **The plan.** The strategy's name and the planned token size of its replacement, so the caller can reserve the space before the strategy runs. +- **The replacement.** One compaction from a request at a cutoff: the chosen cut, the replacement messages, and the model calls, usage and duration it took. +- **The outcome as data.** `completed`, `skipped` or `failed`, each with diagnostics; a failure inside the strategy is an outcome, not an error. + +Callers keep: + +- When a compaction runs: the automatic threshold, the manual command and the recovery rule are ContextPreparation's and Loop's business. +- The legal cuts and the retention limit: the policy that computes them is the caller's. +- Publishing the compaction fact and saving a snapshot: the caller commits what the strategy reported. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Loop or ContextPreparation replaces a range of history when the budget is exceeded or the operator asks | No: the summary prompt, the chunking, the retry budget and the diagnostics are one policy; composing them in a caller duplicates the summarizer | `compact` | +| The retention rule reserves the replacement's planned size before running | No: the plan comes from the same target rule the prompt states, and only the owner knows it | `describe` | + +## Caller example + +```rust +// ContextPreparation: the planned size, then the compaction. +let plan = strategy.describe(DescribeRequest { model: selection.clone() }).await?; +let reserved = plan.replacement_size; +let outcome = strategy + .compact(CompactionRequest { + history, + checkpoint, + request: request.clone(), + retain_limit, + cuts, + trigger: CompactionTrigger::Threshold, + estimated_input_tokens, + baseline_source, + baseline_prompt_tokens, + delta_tokens, + provider_budget, + prior: None, + }, cancel.clone()) + .await?; +match outcome.outcome { + StrategyOutcome::Completed { retain_from, replacement, diagnostics } => { + write_compaction(retain_from, replacement, diagnostics).await? + } + StrategyOutcome::Skipped { reason, .. } => record_skip(reason), + StrategyOutcome::Failed { error, diagnostics } => record_failed(error, diagnostics), +} +``` + +## Own contract + +### Dependencies + +- `S:contextFacts` — the limits and the token count the plan and the chunk budget need. +- `P:modelHost` — the summarizer's model calls, under the existing failure and credential policy. +- `P:providerConnectionResolver` — the connection each summarizer request uses; the connection lives only inside the call. +- `S:summaryPromptSettingsHost` — optional: the operator's system prompt override, read once when the owner loads. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `describe` | The strategy's name and the planned size of its replacement | `{model}` | `{name, replacementSize}` | None; the owner completes the read | `not_adopted`, `closed` | +| `compact` | Replace the history before a cut with a summary | `{history, checkpoint?, request, retainLimit?, cuts, trigger, estimatedInputTokens, baselineSource, baselinePromptTokens?, deltaTokens?, providerBudget?, prior?}` | `{outcome}`: `completed`, `skipped` or `failed`, each with diagnostics | Stops the model call in flight; the compaction then answers nothing and writes nothing | `cancelled`, `closed`, `invalid` | + +`model` is a model selection; the owner asks `contextFacts` for its limits and counts. `retainLimit` is the cut the retention rule allows; `cuts` lists every legal cut in order; `request` is the request whose context is compacted. + +`completed` carries `{retainFrom, replacement, diagnostics}`; `skipped` carries `{reason, diagnostics}`; `failed` carries `{error, diagnostics}`. `diagnostics` holds the model call count, the summed usage, the strategy's own record and the duration. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `cancelled` | `compact` | The call was stopped before any model work or by the caller's cancellation; the history is unchanged | +| `closed` | both | The owner is unloading; the compaction did not run | +| `invalid` | `compact` | Fix the input: no legal cut, a cut outside the history, a request without an adopted model | +| `not_adopted` | `describe` | Adopt the model again; without it the plan cannot be computed | + +A strategy failure after model work is the `failed` outcome with its diagnostics, not an error: the caller writes the compaction fact with those diagnostics. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `describe` | The owner reads the limits and the planned size from `contextFacts` | A dropped call ends the read | `closed` | The owner | +| `compact` | The owner picks the cut, summarizes in chunks under the input budget, and answers the outcome with diagnostics | The model call in flight is stopped; the call answers nothing and the history is unchanged | An in-flight compaction ends `cancelled`; the generation answers no further call | The model call by the owner; the compaction fact by the caller | + +## Exceptions with reasons + +- `describe` and `compact` take the model selection as data and ask `contextFacts` for the limits: a model object in the input made the strategy hold another owner's counter, and a number in the input would freeze the capacity the request actually has. +- `failed` is an outcome rather than an error: the compaction fact reports the same diagnostics as a completion, and the caller writes that fact either way. +- `prior` carries the earlier pass of a re-planned compaction: the caller re-plans when the first pass does not fit, and the second pass must continue the same request budget. + +## Verification + +- A threshold compaction over the retention limit completes, skips or fails with diagnostics; a compaction with no legal cut is `invalid` and sends no model call. +- `describe` equals the target rule plus the empty wrapper's count; a caller that reserved that size keeps it. +- A cancel during the model call answers nothing and leaves the history unchanged. +- A re-planned compaction sums both passes' model calls and usage. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part publishing two operations. It writes no Timeline event and folds no state; the compaction fact is the caller's. | +| §2 scopes | Session: the summarizer's policy and its model calls are shared by the Session's branches. | +| §3 orthogonality | Reads `contextFacts` and the model services; writes nothing outside its own calls. | +| §4 rule 1 | No command event: the caller writes the compaction start and result facts. | +| §4 rule 2 | No handover of an object; the outcome is data. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | The summary prompt and the target rule are this owner's configuration, not core behavior. | +| §4 rule 5 | No batches. | +| §4 rule 6 | The replacement returns to the caller, which places it in the compaction fact; the owner adds no second path. | +| §4 rule 7 | Callers use the two operations; no caller reads the owner's prompt or chunk state. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | The compaction fact is the durable record; the strategy writes none itself. | +| §7 values, ids and objects | Requests and replies are data; the model object no longer crosses. | +| §7 one interface | One name, `summaryStrategy`, on the owner type. | +| §7 cross-language | Every request and reply is data; the cancellation is the caller's dropped call. | +| §7 one change | The implementation task removes `compactionStrategyHost` and migrates both callers in one change. | +| ADR 002 D1 | Session: the policy has no branch state and serves every branch. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | Depends on process services at an enclosing scope and on `contextFacts` at its own. | +| ADR 002 D4 | The target rule and the prompt are factory configuration; the operator's override is read at load. | +| ADR 002 D5 | Data contract; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_capabilities::host::StrategyDiagnostics; +use dim_agent_runtime::{ModelSelection, PublicService}; +use dim_agent_types::{ + AgentEvent, BaselineSource, CompactionCut, CompactionTrigger, HistoryEntry, Message, + ModelRequest, ProviderOutputBudgetFacts, +}; +use std::sync::Arc; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DescribeRequest { + pub model: ModelSelection, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Plan { + pub name: String, + pub replacement_size: f64, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CompactionCheckpoint { + pub retain_from: String, + pub replacement: Arc<[Message]>, + pub context_baseline: Arc<[dim_agent_types::ContextBaselineEntry]>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub replacement_parts: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CompactionRequest { + pub history: Vec, + pub checkpoint: Option, + pub request: ModelRequest, + pub retain_limit: Option, + pub cuts: Vec, + pub trigger: CompactionTrigger, + pub estimated_input_tokens: f64, + pub baseline_source: BaselineSource, + pub baseline_prompt_tokens: Option, + pub delta_tokens: Option, + pub provider_budget: Option, + pub prior: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", tag = "status")] +pub enum StrategyOutcome { + Completed { + retain_from: String, + replacement: Vec, + diagnostics: StrategyDiagnostics, + }, + Skipped { + reason: String, + diagnostics: StrategyDiagnostics, + }, + Failed { + error: String, + diagnostics: StrategyDiagnostics, + }, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CompactionReply { + pub outcome: StrategyOutcome, +} + +#[derive(Debug, thiserror::Error)] +pub enum StrategyError { + #[error("the compaction was cancelled")] + Cancelled, + #[error("the strategy owner is unloading")] + Closed, + #[error("{0}")] + Invalid(String), + #[error("{0}")] + NotAdopted(String), +} + +impl PublicService for SummaryStrategy {} + +#[rutis::service(name = "summaryStrategy")] +impl SummaryStrategy { + pub async fn describe(&self, request: DescribeRequest) -> Result { /* ... */ } + pub async fn compact( + &self, + request: CompactionRequest, + cancelled: dim_agent_capabilities::host::CancelledFn, + ) -> Result { /* ... */ } +} +``` + +`cancelled` is the binding's cancellation argument, not a request field. `AgentEvent` is not part of the request: the caller writes the compaction facts. From 0869dd6003c051b29006dd04d83ef09bcab47eb3 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 14:44:39 +0800 Subject: [PATCH 02/19] docs(design): hold work by callback and settle leases at the row SessionScope gains withHold for work whose extent is the call; hold stays for work that outlives it, and the owner settles every lease at the row's unload. Content instances are the Session's, not the caller's, so unmount retires content early instead of being a required release. Refs #2025 --- docs/design/plugins/SessionScope.md | 65 +++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 13 deletions(-) diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index f8365e42f1..814cdafd6a 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -11,7 +11,7 @@ SessionScope owns: - **The creation record.** The Session's mount list, working directory, model selection, system prompt, permission preset, collaboration role, interactive flag, language seed and initial title, fixed when the Session is built. The record never changes while the Session runs. - **Identity.** The Session id and whether the Session was restored from the store. - **The phase.** Loading, Active, Closing, Closed, monotonic and never replaced by an earlier phase. `activated` and `closing` are the waits on the two transitions. -- **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. A lease is an id bound to the calling row: the row's unload releases every lease it still holds, and `release` ends one earlier. A lease reports nothing and cancels nothing. +- **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. Every lease is bound to the calling row and the owner settles it at the row's unload, so no caller frees anything on an error path. `withHold` holds one for the extent of the caller's callback; `hold` answers an id for work that outlives the call. A lease reports nothing and cancels nothing. - **The failure record.** The first fault that stopped the Session; a storage failure supersedes an earlier non-storage fault and the first storage failure wins. `reportFault` writes, `failure` reads, `observeFault` subscribes. - **Content instances.** Session-owned content mounted from a definition — a Skill's content, an MCP connection — inside this Session's subtree, addressed by instance id. The owner admits only groups whose configured parent is the Session group. - **The branch's runtime context.** One construction per branch id, handed to the branch tree, which owns and settles the context (see Exceptions with reasons). @@ -19,7 +19,7 @@ SessionScope owns: Callers keep as business: - When their background work may start and must stop: BranchLine, Skills, ShellInput and FileAccess wait on the phase. -- Which work counts as accepted and therefore holds a lease: ShellInput's command, BackgroundExec's task, Report's draft, Collaboration's member. +- Which work counts as accepted: the extent of ShellInput's command, the lifetime of BackgroundExec's task, Report's draft and Collaboration's member. - What a fault means for their work; the failure record says only that the Session stopped. - Which definitions to mount and when to retire them. - Which branches exist, their ids and their ancestors: TimelineTree owns the branch directory (#2024). @@ -30,8 +30,9 @@ Callers keep as business: | Read identity: Attachments' ownership check, Permission and tool-source attribution, the store key | No | `identity` | | Wait for publication or for close to start: BranchLine's writer, Skills' replacement, ShellInput's refusal, FileAccess' gate | No: polling a value makes every caller write the wait | `activated`, `closing` | | Read the phase now: Goal's state read, MCP's admission, ShellInput's refusal | No | `phase` | -| Keep accepted work from being ended by an idle release | No: the idle-release decision is the owner's, and composing it makes the caller hold a counter or a token across every error path | `hold` | -| End a lease early, after the work's last fact | No: the id is bound to the calling row and only the owner releases it | `release` | +| Run accepted work under a hold for the extent of the call: ShellInput's command | No: the idle-release decision is the owner's, and composing it makes the caller hold a counter or a token across every error path | `withHold` | +| Hold across work that outlives the call: BackgroundExec's task, Report's draft, Collaboration's member | No: a callback would have to stay pending for the whole task, and a tool that answers a task id returns before the command ends | `hold`, settled at the row's unload | +| End a hold early, after the work's last fact, so an idle release may happen sooner | No: the id is bound to the calling row and only the owner releases it | `release` | | Record a fault: Prompt on a prompt or recovery failure | No | `reportFault` | | Read the current fault | No | `failure` | | Subscribe to later faults: a part in another language | No: a subscription is the owner's, not a poll loop in the caller | `observeFault` | @@ -55,25 +56,42 @@ let mounted = scope instance_data: value, }) .await?; +// The instance is the Session's: its close shuts the content down. Retiring it earlier +// keeps an obsolete definition from staying published. scope.unmount(UnmountRequest { instance_id: mounted.instance_id }).await?; ``` ShellInput refuses after closing starts and holds the Session while a command runs: ```rust +// ShellInput: the hold covers the command; the owner releases it when the call returns, +// and the row's unload releases it if the caller never returns. scope.phase()?; // closing or closed -> RpcError::closed() +scope + .with_hold( + WithHoldRequest { work: Arc::new(move || Box::pin(run_command(cancel.clone()))) }, + cancel.clone(), + ) + .await?; +``` + +BackgroundExec's task outlives the call, so the part takes an id; the owner settles it at +the row's unload, and the part releases it when the task ends only so an idle release may +happen sooner: + +```rust +// The id belongs to this part's row; a lost id is settled by the owner. let lease = scope.hold().await?.lease_id; -run_command(lease.clone(), cancel.clone()).await?; -scope.release(ReleaseRequest { lease_id: lease }).await?; +self.leases.lock().unwrap().insert(task_id, lease); ``` A part in another language subscribes to the fault record: ```ts +// The subscription belongs to this row: its unload releases it, and release ends it earlier. const { leaseId } = await sessionScope.observeFault(async fault => { if (fault?.storage) record(fault.storage) }) -await sessionScope.release({ leaseId }) ``` TimelineTree opens a branch after admitting it: @@ -102,7 +120,8 @@ SessionScope injects nothing. The assembly gives the owner its creation record a | `phase` | The phase now | `{}` | `{phase}`: `loading`, `active`, `closing`, `closed` | None | None | | `activated` | Wait until the Session is published or starts closing | `{}` | `{active}`: true only when published and not closing | The caller drops the call; the owner's close ends the wait with `active: false` | None | | `closing` | Wait until the Session starts closing | `{}` | `{}` | The caller drops the call | None | -| `hold` | Keep an idle release from ending this Session | `{}` | `{leaseId}` | None; the call does not wait | `closed` | +| `withHold` | Run the caller's work under a lease for the extent of the call | `{work}` | `{}` | The caller's cancel drops the work; the owner releases the lease and answers `cancelled` | `cancelled`, `closed` | +| `hold` | Keep an idle release from ending this Session for work that outlives the call | `{}` | `{leaseId}` | None; the call does not wait | `closed` | | `observeFault` | Receive the current fault and later reports until released or the row unloads | `{listener}` | `{leaseId}` | None; the call does not wait | `closed` | | `release` | End a lease or a subscription before the row unloads | `{leaseId}` | `{released}`: false when the id was already released | None | `invalid` when the id belongs to another row; `closed` | | `reportFault` | Record the fault that stopped the Session | `{fault}` | `{}` | None | None | @@ -111,13 +130,14 @@ SessionScope injects nothing. The assembly gives the owner its creation record a | `unmount` | Retire a content instance this Session owns | `{instanceId}` | `{}` | None; the owner completes the release | `invalid` when the id belongs to another Session; `cleanup`; `closed` | | `openBranch` | Construct a branch's runtime context for the branch tree | `{branchId, ancestors}` | the branch's runtime context (see Exceptions) | The caller drops the call; a construction the caller abandoned is shut down before the branch becomes visible | `closed`, `build` | -`listener` is a callback by reference: it runs outside the owner's locks and outside the Timeline's commit lock. A lease id is an owner-issued token; it carries no authority and is valid only for the calling row. +`listener` and `work` are callbacks by reference: they run outside the owner's locks and outside the Timeline's commit lock. `work` returns nothing; its failure and its cleanup stay with the caller. A lease id is an owner-issued token bound to the calling row; it carries no authority, the owner settles it at the row's unload, and a caller never has to free it on an error path. ### Errors | Kind | Operation | What the caller does next | | --- | --- | --- | -| `closed` | `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | +| `closed` | `withHold`, `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | +| `cancelled` | `withHold` | The caller's cancel stopped the work before it finished; the lease is released and nothing else changed | | `invalid` | `release`, `unmount`, `mount` | Fix the id or the definition: an id of another row or Session, a group outside this Session's subtree, an unknown definition | | `not_ready` | `mount` | Act on the reported row and state: the definition's rows did not activate; the instance was shut down and nothing is left to release | | `cleanup` | `mount`, `unmount` | The instance is unreachable but its shutdown failed; the Session will report it as a fault; treat the content as unavailable | @@ -129,6 +149,7 @@ SessionScope injects nothing. The assembly gives the owner its creation record a | Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | +| `withHold` | The owner takes a lease, calls the work, and releases the lease when the work returns | The dropped call stops the work; the owner releases the lease and answers `cancelled` | An in-flight call ends `closed`; a lease never delays a close | SessionScope; the work's own cleanup by the calling row | | `hold` | The owner checks the phase, increments the hold count and registers the lease under the calling row | The row's unload releases every lease the row still holds | No new lease is issued once an idle release is decided; an existing lease never delays a close | SessionScope | | `observeFault` | The owner registers a listener under the calling row, calls it once with the fault in force (none included), then on every later report | The row's unload stops the listener and drops the registration | The listener stays until the generation unloads; a report after close is ignored | SessionScope; the listener's work by the calling row | | `release` | The owner removes the lease or subscription and disposes it | A dropped call leaves the lease in place; the row's unload settles it | An id of an unloaded generation is `closed` | SessionScope | @@ -142,11 +163,14 @@ SessionScope injects nothing. The assembly gives the owner its creation record a - `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. - The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. - `identity` carries no version: the id and the restored flag are fixed at creation. -- A lease is a value, not a handle: it names nothing the caller can use except in `release`, and the owner releases every lease at the row's unload, so a caller that loses the id leaks nothing. +- `withHold` cannot replace `hold`: a tool that answers a task id returns before the command ends, and a member, a draft or a background task outlives many calls, so a callback kept pending for the whole work would make the tool wait for its own task. Long-running commands are fine with the callback: `withHold` awaits the work, and a client in another language passes the callback by reference while the row stays the settlement owner. +- A lease is a value, not a handle: it names nothing the caller can use except in `release`, and the owner releases every lease at the row's unload, so a caller that loses the id leaks nothing. `release` only lets an idle release happen sooner. +- Content instance ids are the Session's, not the caller's: the Session's close shuts down every instance it mounted, so a part that never unmounts leaves obsolete content published until the Session ends, without breaking the owner. ## Verification -- `hold` answers `closed` once an idle release is decided; a lease taken before it keeps the Session loaded until released, and never refuses a close. +- `withHold` releases its lease when the work returns, and answers `cancelled` with the lease released when the caller cancels; the work's error path needs no release. +- `hold` answers `closed` once an idle release is decided; a lease taken before it keeps the Session loaded until released, and never refuses a close; a lost id is settled at the row's unload. - `observeFault` delivers the fault in force and later reports; `release` answers `released: true` then `false`; another row's id is `invalid`; the row's unload stops delivery. - `reportFault` keeps the first fault; a storage fault after a non-storage one wins; a non-storage fault after a storage one loses. - `mount` answers `invalid` for a group outside the Session's subtree, `not_ready` for a definition whose row failed (and leaves no instance), and shuts down an abandoned mount; `unmount` answers `cleanup` when the shutdown fails and `invalid` for another Session's id. @@ -170,7 +194,7 @@ SessionScope injects nothing. The assembly gives the owner its creation record a | §4 rule 7 | Callers use these operations; no caller reads the hold count, the fault slot or an instance's fiber. | | §4 rule 8 | No infrastructure change. SessionScope is the runtime's Session part and its shape is the runtime's decision; the operations above are the data face those decisions already require. | | §4 rule 9 | No Timeline fact: the phase and the fault record are runtime state, read live and never persisted as events. | -| §7 values, ids and objects | The record, identity, phase and fault are values; leases and instance ids are ids bound to the calling row; the one object is `openBranch`, with the joint design above. | +| §7 values, ids and objects | The record, identity, phase and fault are values; `withHold` takes the caller's work as a callback; a lease id and a content instance id are the owner's, bound to the calling row and settled at its unload; the one object is `openBranch`, with the joint design above. | | §7 no proxy lookup | The owner returns only its own state; the Agent's configuration and the Skills and Collaboration factory texts leave this face. | | §7 one interface | One name, `sessionScope`, on the owner type; the Rust binding and the wire call the same methods; no facade or wrapper type. | | §7 cross-language | Every operation is data, a callback by reference or an id; no method exists only for Rust. | @@ -264,6 +288,16 @@ pub struct OpenBranchRequest { pub type FaultListener = Arc) -> rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + Send + Sync>; +/// The caller's accepted work; its error and cleanup stay with the caller. +pub type WorkFn = + Arc rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + Send + Sync>; + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WithHoldRequest { + pub work: WorkFn, +} + #[derive(Debug, thiserror::Error)] pub enum SessionScopeError { #[error("{0}")] @@ -287,6 +321,11 @@ impl SessionScope { pub fn phase(&self) -> PhaseReply { /* ... */ } pub async fn activated(&self) -> ActivatedReply { /* ... */ } pub async fn closing(&self) { /* ... */ } + pub async fn with_hold( + &self, + request: WithHoldRequest, + cancelled: dim_agent_capabilities::host::CancelledFn, + ) -> Result<(), SessionScopeError> { /* ... */ } pub async fn hold(&self) -> Result { /* ... */ } pub async fn observe_fault(&self, listener: FaultListener) -> Result { /* ... */ } pub async fn report_fault(&self, fault: SessionFault) { /* ... */ } From 29563dff41bd13fcda53ff8d21779f491507a7f3 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 15:17:27 +0800 Subject: [PATCH 03/19] docs(design): add line addressing, file access facts and the store spelling SessionScope answers the instance of a line by line id so Session parts reach that line's owners; the write and the read stay with those owners. File access facts become a data owner with check and workspaceRoots. The Timeline engine keeps one spelling: query and sessionConfig on store, per-line reads and completions on the Session timelineStore. Refs #2025 --- docs/design/plugins/FileAccessFacts.md | 196 +++++++++++++++++++++++++ docs/design/plugins/README.md | 1 + docs/design/plugins/SessionScope.md | 23 ++- 3 files changed, 218 insertions(+), 2 deletions(-) create mode 100644 docs/design/plugins/FileAccessFacts.md diff --git a/docs/design/plugins/FileAccessFacts.md b/docs/design/plugins/FileAccessFacts.md new file mode 100644 index 0000000000..c308dc9cb1 --- /dev/null +++ b/docs/design/plugins/FileAccessFacts.md @@ -0,0 +1,196 @@ +# File access facts + +Scope: session. Issue: #2025. + +The owner answers what one call's target path is and which file-access facts hold for it: inside the workspace, inside a system path, an owned Session file, or covered by a grant. Permission asks before approving a file call; the process preparation asks for the confirmed workspace roots before running a command. Today the same need is the `FileAccessFacts` object and its `ReadFileAccessFacts` trait; this document replaces both with two reads. + +## Use and scope: responsibility split + +The owner answers: + +- **The resolved target.** The path a call names with `~`, the working directory, `..` and links resolved, as the workspace sees it. +- **The facts.** Workspace, system, owned and grant membership under the effective access mode, plus the reason a workspace discovery failed when it did. +- **The confirmed roots.** The workspace and confirmed grant roots a command's process boundary may use. + +Callers keep: + +- What the facts mean: Permission's risk and approval decision, and which facts it shows. +- Which paths a tool is asked to read or write. +- The process boundary decision: the command preparation applies the roots it is given. + +| Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Permission resolves a file call's target and decides with the facts | No: `~`, cwd, `..` and link resolution are the workspace's knowledge, and the owned and grant facts come from two owners the caller would otherwise each hold | `check` | +| A command's preparation needs the confirmed workspace roots | No: the roots are validated against the Session's workspace and grants; a caller that composed them could start a process with an expired grant | `workspaceRoots` | + +## Caller example + +```rust +// Permission: one file call's target and facts under the requested access. +let facts = access.check(Check { access: FileAccess::Write, mode: GrantMode::Ask, path }).await?; +let inside = facts.workspace || facts.system || facts.owned || facts.grant; +``` + +```rust +// HostPlatform: the boundary a command may use. +let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; +``` + +## Own contract + +### Dependencies + +- The Session's working directory and identity: the owner's own Session part. +- `P:fileStorage` — `stat` and the path validation the workspace root uses. +- `P:sessionFiles` — whether the Session owns the target file. +- `S:sessionGrants` — the Session's file grants. +- `P:worktrees` — managed worktree roots that extend the workspace. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `check` | Resolve a call's target and answer the facts under one access mode | `{access, mode, path}` | `{target, workspace, system, owned, grant, discoveryError?}` | The caller drops the call; the reads stop | `invalid`, `unavailable`, `cancelled`, `closed` | +| `workspaceRoots` | The workspace and confirmed grant roots a command may use | `{cwd}` | `{roots}` | The caller drops the call | `invalid`, `unavailable`, `cancelled`, `closed` | + +`access` is read or write; `mode` is the grant mode the call asks for; `path` is the path the call named. `target` is the resolved path, and it is what the caller passes to the file operation. + +### Errors + +| Kind | Operation | What the caller does next | +| --- | --- | --- | +| `invalid` | both | Fix the input: an empty path, or a path the workspace cannot resolve | +| `unavailable` | both | The owned-file or grant facts could not be read; Permission denies the call, and a command is not started with an unconfirmed boundary | +| `cancelled` | both | Nothing was decided; the caller's own cancellation ended the read | +| `closed` | both | The Session is closing; the call is refused | + +`discoveryError` is a field, not an error: a failed workspace discovery answers `workspace: false` with the reason, and the caller keeps the original file approvals visible with that reason. + +### Flows + +| Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `check` | The owner resolves the target, reads the owned file and the grants, and answers the facts | A dropped call ends the reads; nothing is decided | An in-flight call ends `closed` | The calling row; the owner holds no resource | +| `workspaceRoots` | The owner resolves the cwd, returns the workspace and the confirmed grant roots | A dropped call ends the read | `closed` | The calling row | + +## Exceptions with reasons + +- No `sessionId` in the request: the owner is the Session's instance, so the Session id is the owner's own identity; a request field would let one Session ask for another's facts. +- `discoveryError` is a field: a workspace that cannot be discovered is a fact the caller shows, not a refusal; approvals the user already gave stay available. +- `workspaceRoots` fails rather than answering an empty list: a command started with an unconfirmed boundary would run outside the workspace the user approved. + +## Verification + +- `check` resolves `~`, `..` and a link before answering; the target is absolute. +- An owned Session file and a granted path each answer their fact under the requested mode; a path outside every fact answers all false. +- A failed discovery answers `workspace: false` with `discoveryError` and no error. +- `workspaceRoots` answers the workspace plus confirmed grants; `unavailable` when the grants cannot be read. +- A call in flight when the Session closes ends `closed`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One Session part publishing two reads; it writes no Timeline event and folds no state. | +| §2 scopes | Session: the facts derive from the Session's workspace, files and grants. | +| §3 orthogonality | Reads the Session's own owners and process services; changes nothing. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handover of a business object; the facts are data. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business meaning: Permission's risk rules stay with Permission. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context path. | +| §4 rule 7 | Callers use the reads; no caller holds the owner's path state. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact. | +| §7 values, ids and objects | Every reply is a value; the old `Arc` no longer crosses. | +| §7 one interface | One name, `fileAccessFacts`, on the owner type. | +| §7 cross-language | Requests and replies are data; the path is a UTF-8 string. | +| ADR 002 D1 | Session: the facts are the Session's workspace and grants. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | Reads process services at an enclosing scope and Session owners at its own. | +| ADR 002 D5 | Data contract; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_capabilities::host::CancelledFn; +use dim_agent_runtime::PublicService; + +#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Access { + Read, + Write, +} + +#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GrantMode { + Ask, + Session, + Once, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Check { + pub access: Access, + pub mode: GrantMode, + pub path: String, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Facts { + pub target: String, + pub workspace: bool, + pub system: bool, + pub owned: bool, + pub grant: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub discovery_error: Option, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WorkspaceRoots { + pub cwd: String, +} + +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Roots { + pub roots: Vec, +} + +#[derive(Debug, thiserror::Error)] +pub enum FactsError { + #[error("{0}")] + Invalid(String), + #[error("{0}")] + Unavailable(String), + #[error("the call was cancelled")] + Cancelled, + #[error("the facts owner is unloading")] + Closed, +} + +impl PublicService for FileAccessFacts {} + +#[rutis::service(name = "fileAccessFacts")] +impl FileAccessFacts { + pub async fn check(&self, request: Check, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn workspace_roots( + &self, + request: WorkspaceRoots, + cancelled: CancelledFn, + ) -> Result { /* ... */ } +} +``` + +`cancelled` is the binding's cancellation argument, not a request field. Paths cross as UTF-8 strings; a path that is not UTF-8 is `invalid`. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index fff906249a..ad598766a5 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -13,6 +13,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [Context facts](ContextFacts.md) (owner contract) | — | the model's limits and token counting behind `contextFacts` | — | [#2025](https://github.com/arcships/dim/issues/2025) | | [Context projection](ContextProjection.md) (owner contract) | — | — | the branch's context fold and recovery snapshots behind `contextProjection` | [#2025](https://github.com/arcships/dim/issues/2025) | | [Summary strategy](SummaryStrategy.md) (owner contract) | — | the summary policy for compaction behind `summaryStrategy` | — | [#2025](https://github.com/arcships/dim/issues/2025) | +| [File access facts](FileAccessFacts.md) (owner contract) | — | the Session's resolved file facts and confirmed roots behind `fileAccessFacts` | — | [#2025](https://github.com/arcships/dim/issues/2025) | | [Migration](Migration.md) | on-demand import tasks, source mappings, progress and retry records; unloaded after settlement | — | — | [Delivery plan](../../plan/analysis/legacy-migration.md) | | [Provider management](../appserver/provider-management.md) | existing Provider: configuration, catalogs, client preferences and management methods | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` tool, `session.question.respond`, waiters of running `ask_user` calls; no events | — | M2; #262 | diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index 814cdafd6a..b07db8c208 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -14,6 +14,7 @@ SessionScope owns: - **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. Every lease is bound to the calling row and the owner settles it at the row's unload, so no caller frees anything on an error path. `withHold` holds one for the extent of the caller's callback; `hold` answers an id for work that outlives the call. A lease reports nothing and cancels nothing. - **The failure record.** The first fault that stopped the Session; a storage failure supersedes an earlier non-storage fault and the first storage failure wins. `reportFault` writes, `failure` reads, `observeFault` subscribes. - **Content instances.** Session-owned content mounted from a definition — a Skill's content, an MCP connection — inside this Session's subtree, addressed by instance id. The owner admits only groups whose configured parent is the Session group. +- **Line addresses.** The instance of each line this Session opened, so a Session part reaches that line's owners by line id. The owner answers the address; the write and the read are those owners' operations. - **The branch's runtime context.** One construction per branch id, handed to the branch tree, which owns and settles the context (see Exceptions with reasons). Callers keep as business: @@ -36,6 +37,7 @@ Callers keep as business: | Record a fault: Prompt on a prompt or recovery failure | No | `reportFault` | | Read the current fault | No | `failure` | | Subscribe to later faults: a part in another language | No: a subscription is the owner's, not a poll loop in the caller | `observeFault` | +| Act on one line's owner by line id: write an input to that line (a Session method steering a member), read the value that line's owner publishes (a tool reading its own line's binding) | No: the id-to-instance step is the mechanism's; composing it makes every Session part carry the loader's instance table | `lineInstance`; the write is the line's input owner's operation, the read is the publishing owner's | | Mount and retire Session content: Skills' content instances, MCP's connections | No: the Session's anchor and the group admission are the owner's knowledge | `mount`, `unmount` | | Open a branch's runtime context: TimelineTree | No: only the runtime constructs a branch's context, in its own subtree | `openBranch` | @@ -109,7 +111,9 @@ self.nodes.insert(id, branch); ### Dependencies -SessionScope injects nothing. The assembly gives the owner its creation record and the Session anchor; the trusted host installs the content definitions the Session may mount. SessionScope binds the store's `timelineStore` face at the Session instance (the operations belong to the Session store, #2018) and no longer provides the Agent's configuration, the Skills or Collaboration factory texts, or the five host ports; those names leave the catalog (delivery). +SessionScope injects nothing. The assembly gives the owner its creation record and the Session anchor; the trusted host installs the content definitions the Session may mount. SessionScope no longer provides the Agent's configuration, the Skills or Collaboration factory texts, or the five host ports; those names leave the catalog (delivery). + +The Session store constructs the Timeline engine and its Session-scope binding; SessionScope installs that binding in the Session instance and never hands it to a process caller. The operations are the engine's (#2018): the Session face publishes the per-line reads and the completion subscriptions, while `query` and `sessionConfig` stay on the process face `store` because an unloaded Session has no Session instance to host them. One engine, one operation set, one spelling per operation. ### Operations @@ -118,6 +122,7 @@ SessionScope injects nothing. The assembly gives the owner its creation record a | `config` | The Session's creation record | `{}` | `SessionConfig` | None; the owner completes the read | None | | `identity` | Who this Session is | `{}` | `{sessionId, restored}` | None | None | | `phase` | The phase now | `{}` | `{phase}`: `loading`, `active`, `closing`, `closed` | None | None | +| `lineInstance` | The instance of a line this Session opened, for a Session part reaching that line's owners | `{line}` | `{instanceId}` | None | `unknown`, `closed` | | `activated` | Wait until the Session is published or starts closing | `{}` | `{active}`: true only when published and not closing | The caller drops the call; the owner's close ends the wait with `active: false` | None | | `closing` | Wait until the Session starts closing | `{}` | `{}` | The caller drops the call | None | | `withHold` | Run the caller's work under a lease for the extent of the call | `{work}` | `{}` | The caller's cancel drops the work; the owner releases the lease and answers `cancelled` | `cancelled`, `closed` | @@ -138,6 +143,7 @@ SessionScope injects nothing. The assembly gives the owner its creation record a | --- | --- | --- | | `closed` | `withHold`, `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | | `cancelled` | `withHold` | The caller's cancel stopped the work before it finished; the lease is released and nothing else changed | +| `unknown` | `lineInstance` | The id names no open line of this Session; the line ended or never existed; the caller stops acting on it | | `invalid` | `release`, `unmount`, `mount` | Fix the id or the definition: an id of another row or Session, a group outside this Session's subtree, an unknown definition | | `not_ready` | `mount` | Act on the reported row and state: the definition's rows did not activate; the instance was shut down and nothing is left to release | | `cleanup` | `mount`, `unmount` | The instance is unreachable but its shutdown failed; the Session will report it as a fault; treat the content as unavailable | @@ -149,6 +155,7 @@ SessionScope injects nothing. The assembly gives the owner its creation record a | Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | +| `lineInstance` | The owner answers the instance it mounted for the line | Nothing to release: the instance belongs to the Session subtree | After the Session's close the line answers nothing; the generation answers `closed` | SessionScope; the line's owners live in that instance | | `withHold` | The owner takes a lease, calls the work, and releases the lease when the work returns | The dropped call stops the work; the owner releases the lease and answers `cancelled` | An in-flight call ends `closed`; a lease never delays a close | SessionScope; the work's own cleanup by the calling row | | `hold` | The owner checks the phase, increments the hold count and registers the lease under the calling row | The row's unload releases every lease the row still holds | No new lease is issued once an idle release is decided; an existing lease never delays a close | SessionScope | | `observeFault` | The owner registers a listener under the calling row, calls it once with the fault in force (none included), then on every later report | The row's unload stops the listener and drops the registration | The listener stays until the generation unloads; a report after close is ignored | SessionScope; the listener's work by the calling row | @@ -160,6 +167,8 @@ SessionScope injects nothing. The assembly gives the owner its creation record a ## Exceptions with reasons - `openBranch` hands out the branch's runtime context: an id would put branch runtime state behind a second set of operations owned by SessionScope, while ADR 002 D1 gives the branch's directory and close to TimelineTree, and the branch's whole capability machine runs behind that context. The joint design is [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md): the owner creates the context inside the Session subtree after the branch scope loads; TimelineTree holds it, hands it to the branch's parts and closes it; the Session unloads only after its branches close; a failed construction reports `cause` before `cleanup` and settles both before the branch is visible; a Session scope never reloads, so the context never outlives its generation. +- `lineInstance` answers an address, not a proxy: a Session part that steers a member writes an input by calling that line's input owner at the returned instance, and a part that reads a line's published value calls the publishing owner there. SessionScope forwards neither the write nor the read; the instance is the mechanism's record of what it mounted, not the branch directory's. +- The Session-scoped `timelineStore` binding is assembly infrastructure: the store owns the engine and the operations, SessionScope installs the binding and states the spelling, and a process caller uses `store` (§2018's requirement). - `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. - The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. - `identity` carries no version: the id and the restored flag are fixed at creation. @@ -207,7 +216,8 @@ SessionScope injects nothing. The assembly gives the owner its creation record a ## Requirements raised to mechanism owners -- [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns `timelineStore`. SessionScope keeps binding that face at the Session instance; the store's contract must keep the binding and must not keep `createSession`, `releaseSession`, `rollbackSession` or `append` on it. The operations those four serve belong to the Agent's own path or to the owner's internal commit path. +- [#2024](https://github.com/arcships/dim/issues/2024): the id-to-instance step is the mechanism's — the runtime mounts a branch instance and SessionScope answers `lineInstance` from that record. Two things must hold for the surface: a line's instance stays addressable while the line is open, and a part of another language can address a service at that instance, not only a Rust part through a typed key. TimelineTree supplies the line id and the line's state, never the address. +- [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns the Timeline engine and constructs the Session-scope binding; SessionScope installs it. The Session face publishes the per-line reads and the completion subscriptions; `query` and `sessionConfig` stay on `store`; `createSession`, `releaseSession`, `rollbackSession` and `append` are not on the Session face. ## Binding appendix @@ -240,6 +250,12 @@ pub struct ActivatedReply { pub active: bool, } +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LineInstance { + pub instance_id: u64, +} + #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct LeaseRequest { @@ -310,6 +326,8 @@ pub enum SessionScopeError { Cleanup(String), #[error("{0}")] Build(String), + #[error("{0}")] + Unknown(String), } impl PublicService for SessionScope {} @@ -319,6 +337,7 @@ impl SessionScope { pub fn config(&self) -> SessionConfig { /* ... */ } pub fn identity(&self) -> Identity { /* ... */ } pub fn phase(&self) -> PhaseReply { /* ... */ } + pub fn line_instance(&self, line: String) -> Result { /* ... */ } pub async fn activated(&self) -> ActivatedReply { /* ... */ } pub async fn closing(&self) { /* ... */ } pub async fn with_hold( From f331fe75806cdc94dfe20e318d78a25a6137bc11 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 15:26:57 +0800 Subject: [PATCH 04/19] docs(design): add the line-addressed call to the Session surface SessionScope publishes lineOwner.call: a Session part names a branch-scope operation and the owner runs it at the line's instance, answering that owner's reply and errors unchanged. A line that is not live answers ended or unknown; a closing Session answers closed. Refs #2025 --- docs/design/plugins/SessionScope.md | 57 +++++++++++++++++++++++------ 1 file changed, 45 insertions(+), 12 deletions(-) diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index b07db8c208..e9f313758a 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -14,7 +14,7 @@ SessionScope owns: - **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. Every lease is bound to the calling row and the owner settles it at the row's unload, so no caller frees anything on an error path. `withHold` holds one for the extent of the caller's callback; `hold` answers an id for work that outlives the call. A lease reports nothing and cancels nothing. - **The failure record.** The first fault that stopped the Session; a storage failure supersedes an earlier non-storage fault and the first storage failure wins. `reportFault` writes, `failure` reads, `observeFault` subscribes. - **Content instances.** Session-owned content mounted from a definition — a Skill's content, an MCP connection — inside this Session's subtree, addressed by instance id. The owner admits only groups whose configured parent is the Session group. -- **Line addresses.** The instance of each line this Session opened, so a Session part reaches that line's owners by line id. The owner answers the address; the write and the read are those owners' operations. +- **Line-addressed calls.** A Session part acts on one line by line id: it names a branch-scope operation from the catalog and this owner runs it at the instance the runtime built for that line, answering that owner's reply and errors unchanged. This owner adds no operation of its own to the line; the two families that use the call are writing an input to the line's input owner and reading the value a line owner publishes. - **The branch's runtime context.** One construction per branch id, handed to the branch tree, which owns and settles the context (see Exceptions with reasons). Callers keep as business: @@ -37,7 +37,7 @@ Callers keep as business: | Record a fault: Prompt on a prompt or recovery failure | No | `reportFault` | | Read the current fault | No | `failure` | | Subscribe to later faults: a part in another language | No: a subscription is the owner's, not a poll loop in the caller | `observeFault` | -| Act on one line's owner by line id: write an input to that line (a Session method steering a member), read the value that line's owner publishes (a tool reading its own line's binding) | No: the id-to-instance step is the mechanism's; composing it makes every Session part carry the loader's instance table | `lineInstance`; the write is the line's input owner's operation, the read is the publishing owner's | +| Act on one line's owner by line id: write an input (`inputQueue.submit`), withdraw one (`inputQueue.withdraw`), read usage (`contextUsage.read`), read the adopted configuration (`prompt.adoptedConfiguration`), read pending approvals (`approval.pending`) | No: a part of another language cannot address a line's instance, and making every part carry the loader's instance table would put the mechanism's index in every owner | `lineOwner.call` with the branch-scope operation's catalog name and request; that owner answers with its own reply and errors | | Mount and retire Session content: Skills' content instances, MCP's connections | No: the Session's anchor and the group admission are the owner's knowledge | `mount`, `unmount` | | Open a branch's runtime context: TimelineTree | No: only the runtime constructs a branch's context, in its own subtree | `openBranch` | @@ -122,7 +122,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; | `config` | The Session's creation record | `{}` | `SessionConfig` | None; the owner completes the read | None | | `identity` | Who this Session is | `{}` | `{sessionId, restored}` | None | None | | `phase` | The phase now | `{}` | `{phase}`: `loading`, `active`, `closing`, `closed` | None | None | -| `lineInstance` | The instance of a line this Session opened, for a Session part reaching that line's owners | `{line}` | `{instanceId}` | None | `unknown`, `closed` | +| `lineOwner.call` | Run one catalog branch-scope operation at a line's instance | `{line, operation, request}` | the operation's own reply, unchanged | The caller's cancel is passed to the operation; a dropped call ends the wait | `ended`, `unknown`, `closed`, and the called operation's own errors unchanged | | `activated` | Wait until the Session is published or starts closing | `{}` | `{active}`: true only when published and not closing | The caller drops the call; the owner's close ends the wait with `active: false` | None | | `closing` | Wait until the Session starts closing | `{}` | `{}` | The caller drops the call | None | | `withHold` | Run the caller's work under a lease for the extent of the call | `{work}` | `{}` | The caller's cancel drops the work; the owner releases the lease and answers `cancelled` | `cancelled`, `closed` | @@ -141,9 +141,10 @@ The Session store constructs the Timeline engine and its Session-scope binding; | Kind | Operation | What the caller does next | | --- | --- | --- | -| `closed` | `withHold`, `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | +| `closed` | `lineOwner.call`, `withHold`, `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | | `cancelled` | `withHold` | The caller's cancel stopped the work before it finished; the lease is released and nothing else changed | -| `unknown` | `lineInstance` | The id names no open line of this Session; the line ended or never existed; the caller stops acting on it | +| `ended` | `lineOwner.call` | The line has ended; stop acting on it and read the directory for the line in force | +| `unknown` | `lineOwner.call` | No live line of this Session has the id; read the directory and act on the right line | | `invalid` | `release`, `unmount`, `mount` | Fix the id or the definition: an id of another row or Session, a group outside this Session's subtree, an unknown definition | | `not_ready` | `mount` | Act on the reported row and state: the definition's rows did not activate; the instance was shut down and nothing is left to release | | `cleanup` | `mount`, `unmount` | The instance is unreachable but its shutdown failed; the Session will report it as a fault; treat the content as unavailable | @@ -155,7 +156,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; | Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | -| `lineInstance` | The owner answers the instance it mounted for the line | Nothing to release: the instance belongs to the Session subtree | After the Session's close the line answers nothing; the generation answers `closed` | SessionScope; the line's owners live in that instance | +| `lineOwner.call` | The owner resolves the line to the instance the runtime built, runs the named operation there, and answers that operation's reply and errors | A dropped call ends the wait; the operation's own cancellation applies to its work | A closing Session answers `closed`; a line whose context closed answers `ended` | SessionScope for the addressing; the called owner for the operation | | `withHold` | The owner takes a lease, calls the work, and releases the lease when the work returns | The dropped call stops the work; the owner releases the lease and answers `cancelled` | An in-flight call ends `closed`; a lease never delays a close | SessionScope; the work's own cleanup by the calling row | | `hold` | The owner checks the phase, increments the hold count and registers the lease under the calling row | The row's unload releases every lease the row still holds | No new lease is issued once an idle release is decided; an existing lease never delays a close | SessionScope | | `observeFault` | The owner registers a listener under the calling row, calls it once with the fault in force (none included), then on every later report | The row's unload stops the listener and drops the registration | The listener stays until the generation unloads; a report after close is ignored | SessionScope; the listener's work by the calling row | @@ -167,7 +168,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; ## Exceptions with reasons - `openBranch` hands out the branch's runtime context: an id would put branch runtime state behind a second set of operations owned by SessionScope, while ADR 002 D1 gives the branch's directory and close to TimelineTree, and the branch's whole capability machine runs behind that context. The joint design is [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md): the owner creates the context inside the Session subtree after the branch scope loads; TimelineTree holds it, hands it to the branch's parts and closes it; the Session unloads only after its branches close; a failed construction reports `cause` before `cleanup` and settles both before the branch is visible; a Session scope never reloads, so the context never outlives its generation. -- `lineInstance` answers an address, not a proxy: a Session part that steers a member writes an input by calling that line's input owner at the returned instance, and a part that reads a line's published value calls the publishing owner there. SessionScope forwards neither the write nor the read; the instance is the mechanism's record of what it mounted, not the branch directory's. +- `lineOwner.call` runs another owner's operation and is not a proxy with business logic: `operation` is a branch-scope catalog name, the reply and the errors are that owner's unchanged, and this owner keeps only the line index the runtime builds when it constructs a context. An instance id cannot be the reply because a part of another language cannot address an instance by id; letting each part hold the index instead would put the loader's table in every owner. - The Session-scoped `timelineStore` binding is assembly infrastructure: the store owns the engine and the operations, SessionScope installs the binding and states the spelling, and a process caller uses `store` (§2018's requirement). - `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. - The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. @@ -216,7 +217,8 @@ The Session store constructs the Timeline engine and its Session-scope binding; ## Requirements raised to mechanism owners -- [#2024](https://github.com/arcships/dim/issues/2024): the id-to-instance step is the mechanism's — the runtime mounts a branch instance and SessionScope answers `lineInstance` from that record. Two things must hold for the surface: a line's instance stays addressable while the line is open, and a part of another language can address a service at that instance, not only a Rust part through a typed key. TimelineTree supplies the line id and the line's state, never the address. +- [#2024](https://github.com/arcships/dim/issues/2024): the two contracts agree on `lineOwner.call` and its resolution; nothing further is required from TimelineTree. The line index is built by this owner when it constructs a line's context and dropped when that context closes. +- The runtime's `Session` facade stops forwarding line operations: `end_branch`, `set_default_branch`, `branch`, `branches`, `directory`, `default_and_directory`, `ended_head`, `sequence`, `batch_end` and `query` are TimelineTree's, and the Session access surface must not restate them. - [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns the Timeline engine and constructs the Session-scope binding; SessionScope installs it. The Session face publishes the per-line reads and the completion subscriptions; `query` and `sessionConfig` stay on `store`; `createSession`, `releaseSession`, `rollbackSession` and `append` are not on the Session face. ## Binding appendix @@ -251,9 +253,25 @@ pub struct ActivatedReply { } #[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct LineInstance { - pub instance_id: u64, +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct LineOwnerCall { + pub line: String, + /// A branch-scope operation's catalog name, for example `inputQueue.submit`. + pub operation: String, + pub request: serde_json::Value, +} + +/// The called owner's error, unchanged, or the addressing's own refusal. +#[derive(Debug, thiserror::Error)] +pub enum LineOwnerError { + #[error("the line has ended")] + Ended, + #[error("no live line has this id")] + Unknown, + #[error("the Session is closing")] + Closed, + #[error("the line owner answered an error")] + Owner(serde_json::Value), } #[derive(serde::Serialize, serde::Deserialize)] @@ -328,6 +346,8 @@ pub enum SessionScopeError { Build(String), #[error("{0}")] Unknown(String), + #[error("{0}")] + Ended(String), } impl PublicService for SessionScope {} @@ -337,7 +357,6 @@ impl SessionScope { pub fn config(&self) -> SessionConfig { /* ... */ } pub fn identity(&self) -> Identity { /* ... */ } pub fn phase(&self) -> PhaseReply { /* ... */ } - pub fn line_instance(&self, line: String) -> Result { /* ... */ } pub async fn activated(&self) -> ActivatedReply { /* ... */ } pub async fn closing(&self) { /* ... */ } pub async fn with_hold( @@ -361,4 +380,18 @@ impl SessionScope { } ``` +```rust +impl PublicService for LineOwner {} + +/// The same owner's second name: the Session access surface's line-addressed call. +#[rutis::service(name = "lineOwner")] +impl LineOwner { + pub async fn call( + &self, + request: LineOwnerCall, + cancelled: dim_agent_capabilities::host::CancelledFn, + ) -> Result { /* ... */ } +} +``` + `caller: &Ctx` and `cancelled: CancelledFn` are the binding's caller row and cancellation argument; the dispatch fills them and no caller sends or names a row. `LeaseId`, `InstanceId` and the ancestor pairs cross as strings and numbers. From d954cd2f166ae074134fbd73c3a7558a5cb41209 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 19:27:41 +0800 Subject: [PATCH 05/19] docs(design): drop the line call and state the branch handover A line's owner is reached by the mechanism's typed resolution by line id; SessionScope adds no forwarding operation or request envelope. The branch context handover now states who creates, holds and closes it, and what either side's close means, citing lifecycle.md and single-tree. Refs #2025 --- docs/design/plugins/SessionScope.md | 69 +++++++++-------------------- 1 file changed, 20 insertions(+), 49 deletions(-) diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index e9f313758a..c089f2fb48 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -14,7 +14,6 @@ SessionScope owns: - **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. Every lease is bound to the calling row and the owner settles it at the row's unload, so no caller frees anything on an error path. `withHold` holds one for the extent of the caller's callback; `hold` answers an id for work that outlives the call. A lease reports nothing and cancels nothing. - **The failure record.** The first fault that stopped the Session; a storage failure supersedes an earlier non-storage fault and the first storage failure wins. `reportFault` writes, `failure` reads, `observeFault` subscribes. - **Content instances.** Session-owned content mounted from a definition — a Skill's content, an MCP connection — inside this Session's subtree, addressed by instance id. The owner admits only groups whose configured parent is the Session group. -- **Line-addressed calls.** A Session part acts on one line by line id: it names a branch-scope operation from the catalog and this owner runs it at the instance the runtime built for that line, answering that owner's reply and errors unchanged. This owner adds no operation of its own to the line; the two families that use the call are writing an input to the line's input owner and reading the value a line owner publishes. - **The branch's runtime context.** One construction per branch id, handed to the branch tree, which owns and settles the context (see Exceptions with reasons). Callers keep as business: @@ -24,6 +23,7 @@ Callers keep as business: - What a fault means for their work; the failure record says only that the Session stopped. - Which definitions to mount and when to retire them. - Which branches exist, their ids and their ancestors: TimelineTree owns the branch directory (#2024). +- Acting on a line's owners: the mechanism resolves a branch-scope service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation. SessionScope publishes no operation, request or reply for that path. | Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | @@ -37,7 +37,7 @@ Callers keep as business: | Record a fault: Prompt on a prompt or recovery failure | No | `reportFault` | | Read the current fault | No | `failure` | | Subscribe to later faults: a part in another language | No: a subscription is the owner's, not a poll loop in the caller | `observeFault` | -| Act on one line's owner by line id: write an input (`inputQueue.submit`), withdraw one (`inputQueue.withdraw`), read usage (`contextUsage.read`), read the adopted configuration (`prompt.adoptedConfiguration`), read pending approvals (`approval.pending`) | No: a part of another language cannot address a line's instance, and making every part carry the loader's instance table would put the mechanism's index in every owner | `lineOwner.call` with the branch-scope operation's catalog name and request; that owner answers with its own reply and errors | +| Act on one line's owner by line id: write an input (`inputQueue.submit`), withdraw one (`inputQueue.withdraw`), read usage (`contextUsage.read`), read the adopted configuration (`prompt.adoptedConfiguration`), read pending approvals (`approval.pending`) | No: a part cannot address a line's instance itself, and a forwarding operation here would be the facade §7 forbids | Not this owner: the mechanism resolves the branch-scope service by line id (`line_owner::(line)`), and the caller calls that owner's operation | | Mount and retire Session content: Skills' content instances, MCP's connections | No: the Session's anchor and the group admission are the owner's knowledge | `mount`, `unmount` | | Open a branch's runtime context: TimelineTree | No: only the runtime constructs a branch's context, in its own subtree | `openBranch` | @@ -122,7 +122,6 @@ The Session store constructs the Timeline engine and its Session-scope binding; | `config` | The Session's creation record | `{}` | `SessionConfig` | None; the owner completes the read | None | | `identity` | Who this Session is | `{}` | `{sessionId, restored}` | None | None | | `phase` | The phase now | `{}` | `{phase}`: `loading`, `active`, `closing`, `closed` | None | None | -| `lineOwner.call` | Run one catalog branch-scope operation at a line's instance | `{line, operation, request}` | the operation's own reply, unchanged | The caller's cancel is passed to the operation; a dropped call ends the wait | `ended`, `unknown`, `closed`, and the called operation's own errors unchanged | | `activated` | Wait until the Session is published or starts closing | `{}` | `{active}`: true only when published and not closing | The caller drops the call; the owner's close ends the wait with `active: false` | None | | `closing` | Wait until the Session starts closing | `{}` | `{}` | The caller drops the call | None | | `withHold` | Run the caller's work under a lease for the extent of the call | `{work}` | `{}` | The caller's cancel drops the work; the owner releases the lease and answers `cancelled` | `cancelled`, `closed` | @@ -141,10 +140,8 @@ The Session store constructs the Timeline engine and its Session-scope binding; | Kind | Operation | What the caller does next | | --- | --- | --- | -| `closed` | `lineOwner.call`, `withHold`, `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | +| `closed` | `withHold`, `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | | `cancelled` | `withHold` | The caller's cancel stopped the work before it finished; the lease is released and nothing else changed | -| `ended` | `lineOwner.call` | The line has ended; stop acting on it and read the directory for the line in force | -| `unknown` | `lineOwner.call` | No live line of this Session has the id; read the directory and act on the right line | | `invalid` | `release`, `unmount`, `mount` | Fix the id or the definition: an id of another row or Session, a group outside this Session's subtree, an unknown definition | | `not_ready` | `mount` | Act on the reported row and state: the definition's rows did not activate; the instance was shut down and nothing is left to release | | `cleanup` | `mount`, `unmount` | The instance is unreachable but its shutdown failed; the Session will report it as a fault; treat the content as unavailable | @@ -156,7 +153,6 @@ The Session store constructs the Timeline engine and its Session-scope binding; | Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | -| `lineOwner.call` | The owner resolves the line to the instance the runtime built, runs the named operation there, and answers that operation's reply and errors | A dropped call ends the wait; the operation's own cancellation applies to its work | A closing Session answers `closed`; a line whose context closed answers `ended` | SessionScope for the addressing; the called owner for the operation | | `withHold` | The owner takes a lease, calls the work, and releases the lease when the work returns | The dropped call stops the work; the owner releases the lease and answers `cancelled` | An in-flight call ends `closed`; a lease never delays a close | SessionScope; the work's own cleanup by the calling row | | `hold` | The owner checks the phase, increments the hold count and registers the lease under the calling row | The row's unload releases every lease the row still holds | No new lease is issued once an idle release is decided; an existing lease never delays a close | SessionScope | | `observeFault` | The owner registers a listener under the calling row, calls it once with the fault in force (none included), then on every later report | The row's unload stops the listener and drops the registration | The listener stays until the generation unloads; a report after close is ignored | SessionScope; the listener's work by the calling row | @@ -165,10 +161,23 @@ The Session store constructs the Timeline engine and its Session-scope binding; | `unmount` | The owner shuts the instance down, propagates a shutdown failure as `cleanup`, and forgets the id | A dropped call does not cancel the shutdown | The Session's unload shuts down every remaining instance | SessionScope | | `openBranch` | The owner admits the id, waits for the branch scope and its required parts, and hands the context to the tree | A dropped call settles the half-made branch before it is visible | `closed` once the Session is closing; a Construction in flight settles or ends `closed` | SessionScope creates; TimelineTree holds and closes (Exceptions) | +### A branch's runtime context: the handover + +`openBranch` hands one object between two owners. Both cite [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md) for the scope tree, its close rights and the unload order, and [single-tree §Close](../../architecture/rust-agent/single-tree.md#关闭) for what a failed construction settles before its cause is reported. + +| Question | Answer | +| --- | --- | +| Who creates | SessionScope, inside the Session subtree, after the branch scope and its required parts are Active and the branch's loop state exists. | +| Who holds | TimelineTree: the context is inserted under the line id and handed to that line's parts; SessionScope keeps no reference after the reply. | +| Handover order | The line is admitted first, in the tree's directory; the construction answers only when the context is runnable; a failed construction settles its cleanup before the reply, and the line never becomes visible. | +| Who closes | TimelineTree, when the line ends and when the tree closes, before the Session scope unloads. | +| TimelineTree closes first | Normal Session close: every line's context closes, then the Session scope unloads. | +| SessionScope closes first | `openBranch` refuses new lines with `closed`; a construction in flight settles or ends `closed`; a context already handed over is closed by the tree in the Session's close. | +| Reload | The Session scope never reloads, so a context never outlives its generation. | + ## Exceptions with reasons -- `openBranch` hands out the branch's runtime context: an id would put branch runtime state behind a second set of operations owned by SessionScope, while ADR 002 D1 gives the branch's directory and close to TimelineTree, and the branch's whole capability machine runs behind that context. The joint design is [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md): the owner creates the context inside the Session subtree after the branch scope loads; TimelineTree holds it, hands it to the branch's parts and closes it; the Session unloads only after its branches close; a failed construction reports `cause` before `cleanup` and settles both before the branch is visible; a Session scope never reloads, so the context never outlives its generation. -- `lineOwner.call` runs another owner's operation and is not a proxy with business logic: `operation` is a branch-scope catalog name, the reply and the errors are that owner's unchanged, and this owner keeps only the line index the runtime builds when it constructs a context. An instance id cannot be the reply because a part of another language cannot address an instance by id; letting each part hold the index instead would put the loader's table in every owner. +- `openBranch` hands out the branch's runtime context: an id would put branch runtime state behind a second set of operations owned by SessionScope, while ADR 002 D1 gives the directory and the close to TimelineTree, and the branch's whole capability machine runs behind that context. Ids, values and callbacks cannot carry it, so the object crosses under the handover design above. - The Session-scoped `timelineStore` binding is assembly infrastructure: the store owns the engine and the operations, SessionScope installs the binding and states the spelling, and a process caller uses `store` (§2018's requirement). - `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. - The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. @@ -204,7 +213,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; | §4 rule 7 | Callers use these operations; no caller reads the hold count, the fault slot or an instance's fiber. | | §4 rule 8 | No infrastructure change. SessionScope is the runtime's Session part and its shape is the runtime's decision; the operations above are the data face those decisions already require. | | §4 rule 9 | No Timeline fact: the phase and the fault record are runtime state, read live and never persisted as events. | -| §7 values, ids and objects | The record, identity, phase and fault are values; `withHold` takes the caller's work as a callback; a lease id and a content instance id are the owner's, bound to the calling row and settled at its unload; the one object is `openBranch`, with the joint design above. | +| §7 values, ids and objects | The record, identity, phase and fault are values; `withHold` takes the caller's work as a callback; a lease id and a content instance id are the owner's, bound to the calling row and settled at its unload; the one object is `openBranch`, with the handover design above. | | §7 no proxy lookup | The owner returns only its own state; the Agent's configuration and the Skills and Collaboration factory texts leave this face. | | §7 one interface | One name, `sessionScope`, on the owner type; the Rust binding and the wire call the same methods; no facade or wrapper type. | | §7 cross-language | Every operation is data, a callback by reference or an id; no method exists only for Rust. | @@ -217,7 +226,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; ## Requirements raised to mechanism owners -- [#2024](https://github.com/arcships/dim/issues/2024): the two contracts agree on `lineOwner.call` and its resolution; nothing further is required from TimelineTree. The line index is built by this owner when it constructs a line's context and dropped when that context closes. +- [#2024](https://github.com/arcships/dim/issues/2024) and the runtime: resolve a branch group's service by line id (`line_owner::(line)?`), so a Session part calls that owner's typed operation directly. No forwarding operation, operation-name routing or reply envelope is added to this owner; TimelineTree supplies the line id and the line's state, never the address. - The runtime's `Session` facade stops forwarding line operations: `end_branch`, `set_default_branch`, `branch`, `branches`, `directory`, `default_and_directory`, `ended_head`, `sequence`, `batch_end` and `query` are TimelineTree's, and the Session access surface must not restate them. - [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns the Timeline engine and constructs the Session-scope binding; SessionScope installs it. The Session face publishes the per-line reads and the completion subscriptions; `query` and `sessionConfig` stay on `store`; `createSession`, `releaseSession`, `rollbackSession` and `append` are not on the Session face. @@ -252,28 +261,6 @@ pub struct ActivatedReply { pub active: bool, } -#[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct LineOwnerCall { - pub line: String, - /// A branch-scope operation's catalog name, for example `inputQueue.submit`. - pub operation: String, - pub request: serde_json::Value, -} - -/// The called owner's error, unchanged, or the addressing's own refusal. -#[derive(Debug, thiserror::Error)] -pub enum LineOwnerError { - #[error("the line has ended")] - Ended, - #[error("no live line has this id")] - Unknown, - #[error("the Session is closing")] - Closed, - #[error("the line owner answered an error")] - Owner(serde_json::Value), -} - #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct LeaseRequest { @@ -346,8 +333,6 @@ pub enum SessionScopeError { Build(String), #[error("{0}")] Unknown(String), - #[error("{0}")] - Ended(String), } impl PublicService for SessionScope {} @@ -380,18 +365,4 @@ impl SessionScope { } ``` -```rust -impl PublicService for LineOwner {} - -/// The same owner's second name: the Session access surface's line-addressed call. -#[rutis::service(name = "lineOwner")] -impl LineOwner { - pub async fn call( - &self, - request: LineOwnerCall, - cancelled: dim_agent_capabilities::host::CancelledFn, - ) -> Result { /* ... */ } -} -``` - `caller: &Ctx` and `cancelled: CancelledFn` are the binding's caller row and cancellation argument; the dispatch fills them and no caller sends or names a row. `LeaseId`, `InstanceId` and the ancestor pairs cross as strings and numbers. From c101548d3c9306bc3078f5197fdf17316cf0682c Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 21:31:40 +0800 Subject: [PATCH 06/19] docs(design): apply the round-three review - Drop withHold: every lease-taking run outlives the call, so hold carries the id and the owner settles it at the calling row. - FileAccessFacts uses FileAccess and GrantMode, and workspaceRoots answers the workspace and managed worktree roots. - Lease operations take caller: &Ctx; the binding errors carry the code, message and cleanup. - Contributions return the counter's facts; count takes the request. - The streamed projection keeps its fields without the event list. - No legal cut is skipped; the caller measures the duration. - State the record's one mutable member and the request id Loop writes. - Supersede the Session rows in runtime-owner-operations, service-faces and plugin-contract, and replace timelineTree.call with typed line resolution. Refs #2025 --- .../contracts/runtime-owner-operations.md | 36 +++--- docs/design/plugin-contract.md | 5 +- docs/design/plugins/ContextFacts.md | 50 ++++++-- docs/design/plugins/ContextProjection.md | 32 +++-- docs/design/plugins/FileAccessFacts.md | 56 ++++----- docs/design/plugins/README.md | 2 +- docs/design/plugins/RequestSettings.md | 18 ++- docs/design/plugins/SessionScope.md | 116 +++++++++--------- docs/design/plugins/SummaryStrategy.md | 19 ++- docs/design/service-faces.md | 18 +-- 10 files changed, 204 insertions(+), 148 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 3d36fd9d6d..344aab18d4 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -8,7 +8,7 @@ | Language readers → PromptSources | `sessionLanguage.get`. | | Language updates → App Server | [`session.language.update`](session-access.md) accepts the existing language code or clear action. The owner serializes persistence, live-state replacement and Prompt adoption on main and loaded branches before replying. | | Prompt → PromptRegistry; guide and tool contributors → their registries | `initialPromptConfiguration.get`, `promptHost.load`, `guideEntries.register`, `toolRegistry.register`, `toolSourcesView.get/observe`. | -| Session and branch parts → their lifecycle; branch fact consumers → Dispatcher | `sessionLifecycle.activated/closing/hold/release`, `branchLifecycle.activated/closing`, `dispatcher.listen/consume/committed`. | +| Session and branch parts → their lifecycle; branch fact consumers → Dispatcher | `sessionScope.activated/closing/hold/release` and its fault operations ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093); `branchLifecycle.activated/closing`, `dispatcher.listen/consume/committed`. The old `sessionLifecycle` name is superseded. | ## New rutis APIs on existing owners @@ -17,7 +17,7 @@ | Caller → owner | New API | | --- | --- | | Branch directory readers → `timelineTree` | `timelineTree.directory({}) → [{info, head, state, endEvent?}]`, including ending and ended branches. | -| Skills content and MCP publication → Session loader | `sessionLoader.create({group, definitionId, instanceData}) → {instanceId}`; `remove({instanceId}) → void`. The Session loader admits groups whose configured parent is the Session group. Registered Session extension definitions must activate their instance rows. Host-added optional groups retain their optional rows. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration. | +| Skills content and MCP publication → Session mounts | `sessionScope.mount({group, definitionId, instanceData}) → {instanceId}`; `unmount({instanceId})`. The owner admits groups whose configured parent is the Session group, waits for the definition's rows and settles a rejected instance. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | | Goal → timelineTree | `inputs(id, inputs) → committed events`. One validated atomic batch for the Goal record and trigger. | | Branch-detail RPC → timelineTree | `display(id) → {entry,purpose?,cutMessages?,end?}`. | | History RPC and line-read tools → timelineTree | `batchEnd(id, sequence) → void`, `pageEnd(id, after, limit, through) → sequence`, and `page` at the same cutoff. Preserve complete batches and the fixed head of ended lines. | @@ -26,26 +26,18 @@ | InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | | PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.query` at the selected head for evidence. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | -| Fault producers and Session observers → `sessionLifecycle` | `reportFault(error) → void`, `failure({}) → SessionFault or null`, `observeFault(listener) → id`, `release(id) → boolean`. The listener receives the current failure (initially null) and subsequent reports. Caller unload releases the observation. The first fault wins until a storage failure supersedes it; the first storage failure wins. | +| Fault producers and Session observers → `sessionScope` | `reportFault(fault) → void`, `failure() → SessionFault or none`, `observeFault(listener) → id`, `release({leaseId}) → boolean`. The listener receives the current failure (none included) and later reports; the calling row's unload releases the observation. The first fault wins until a storage failure supersedes it ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | | Check providers and input admission → SubmitChecks | `register(name, check) → void`; `check({entry, branchId, user?, mode}, cancelled) → proceed{blocks, warnings} or block{message}`. Run in name order through the first block. Interrupted checks write nothing. | | Compaction, stop and activity callers → `agentLoop` | `agentLoop.compact({}) → sequence`, `stopTurn({turnId, reason}) → sequence or null`; `agentLoop.state({}) → {phase, turnId?}`, `observe(listener)` delivers that snapshot. | ### Calls from a Session to a selected branch -Within a branch, inject its owner face directly. For Session callers the existing -`timelineTree` face gains `call({branchId,operation}, cancelled) → operation reply`. -TimelineTree resolves the admitted live branch once using its existing branch lookup and -dispatches on that branch instance. The operation is a tagged union of the calls below; -Direct variants use the owner method's arguments, reply and error. The compact RPC variant below returns the existing settled client result. The Session caller gets data. -Ended and unknown branches retain their original errors. Calls admitted before close stay -with that generation. Tree history, directory and batch input continue to use the tree's -own methods. - -| Session caller | Target operation | -| --- | --- | -| Context RPC / PromptSuggestion | `contextUsage.read`. The `compactAndWait` variant runs the existing compact RPC handler: it calls `agentLoop.compact` and waits for the compaction fact matching that command sequence and returns the existing completed/skipped/failed reply. The committed sequence watch and bounded query run inside the selected branch for that wait. | -| Session language / Agent configuration / Report | `prompt.configure` or `prompt.adoptedConfiguration` with the existing source, model and outcome records. | -| InputQueue management / Collaboration | `inputQueue.withdraw` with the existing command; the caller runs the existing submit checks for steer before writing. `approval.pending` returns the branch's existing pending requests, and `approval.decide` settles the selected request. Collaboration retains its ended response on closed/ended/unknown detail lookup. | +Within a branch, inject its owner face directly. A Session part reaches one line's owners by +line id: `line_owner::(line)?.op(..)` resolves the branch-group service at the instance the +runtime built for that line, and the caller calls that owner's typed operation. Any branch-group +data face is reachable this way except registration points and lifecycle services; there is no +generic operation-name dispatch and no `timelineTree.call`. A line that is not live answers +`ended` or `unknown`, and a closing Session answers `closed`. For a live main branch, Report captures its published head once at draft capture (`directory({id:"main"}).head`) and stores it as `conversationThrough` on that draft. Activity evidence and later opt-in @@ -66,11 +58,11 @@ substitutes a newer head. | Caller → owner | New API | | --- | --- | -| Loop → PrepareModelHost | `prepare({turnId, requestId, history, availableTools}) → ModelSettings`, with pinned tool definitions in order. | -| ContextPreparation → PrepareContextHost | `prepare({request, source:{turnId, requestId, through}}, cancelled) → ModelRequest`. | -| Context accounting and compaction → ContextModelHost | `describe(model facts) → {contextWindow, outputTokens, thresholdTokens, algorithm?}`, `count(request) → tokens`, `contributions({model, fixed?, messages}) → {algorithm, fixed?, messages}`, `estimate({model, algorithm, contribution}) → tokens`. | -| Loop and ContextPreparation → CompactionStrategyHost | `describe(model facts) → {name, replacementSize}`; `compact(input, cancelled) → completed, skipped or failed` with StrategyDiagnostics. Input carries history, checkpoint, request, legal cuts, trigger, budgets, prior diagnostics and model facts. | -| Loop and ContextPreparation → HistoryRenderer | `context({branchId, through}) → ContextHistory`, `renderedContext({branchId, through}) → {context, history: HistoryEntry[]}`, `snapshot({context, retainFrom, anchor}) → RecoverySnapshot`, `streamCheckpoint({branchId, through, retainFrom, batch}) → ProjectionCheckpoint`. | +| Loop → `requestSettings` | `settings() → {providerId, modelId, capabilitySnapshot?, config?, system?, metadata?}`; Loop adds the pinned tools, the guide's system and the turn's ids ([Request settings](../../../docs/design/plugins/RequestSettings.md), #2093). | +| ContextPreparation → no host port | The request transformation has no owner and leaves the catalog; a content change enters only through adopted inputs or tool results (#2093). | +| Context accounting and compaction → `contextFacts` | `describe({model})`, `count({request})`, `contributions({model, fixed?, messages}) → {algorithm, fixed?, messages}`, `estimate({model, algorithm, contribution})` ([Context facts](../../../docs/design/plugins/ContextFacts.md), #2093). | +| Loop and ContextPreparation → `summaryStrategy` | `describe({model}) → {name, replacementSize}`; `compact(input, cancelled) → completed, skipped or failed` with diagnostics. The input carries history, checkpoint, request, legal cuts, trigger, budgets and prior diagnostics, and no model object ([Summary strategy](../../../docs/design/plugins/SummaryStrategy.md), #2093). | +| Loop and ContextPreparation → `contextProjection` | `renderedStream({through, batch})`, `renderedContext({through})`, `snapshot({context, retainFrom, anchor})`, `streamCheckpoint({through, retainFrom, batch})`, `snapshotFromCheckpoint({checkpoint, anchor})`; the fold is the branch's own ([Context projection](../../../docs/design/plugins/ContextProjection.md), #2093). | | Loop and ModelProvider → ContextPreparation | `prepare({source: ContextPrepareData, projection?}, cancelled) → ModelRequest`, `validate({requestId, request}, cancelled) → void`. Reuse the prepared projection at the original cutoff. | | ContextPreparation and usage readers → ContextUsage | `read({through?}, cancelled) → {through, contextWindow, outputTokens, thresholdTokens, estimatedInputTokens, baselineSource}`. | | Loop, ToolExecutor and Code Mode definition readers → `toolBinding` | `bind({requestId, through, tools, toolSources}) → void`, `bindCurrent({requestId, declared?}) → ToolDefinition[]`, `definitions({requestId}) → ToolDefinition[]`, `transfer({from, to}) → void`, `release({requestId}) → void`. ToolBinding retains the pinned handler generation. | diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 1d34d18338..990cd2bd4b 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -115,10 +115,7 @@ R4). This table says what each name Dim defines is for. | `eventHub` | process | EventHub | designed, not implemented | A producer declares a source and publishes an event; EventHub delivers it to the Sessions subscribed, through Agents' `sessions` ([EventHub](plugins/EventHub.md)) | | `collaborationMembers:` | process | the member provider | designed, not implemented | [ExternalAgent](plugins/ExternalAgent.md); registers with Collaboration when built (rutis usage R6) | | `treeCommands` | `session` | TimelineTree | yes | `input` by branch id, `create`, `list`, `info` | -| `sessionIdentity` | `session` | SessionScope | yes | `get()`: `{sessionId, restored}` | -| `sessionLifecycle` | `session` | SessionScope | yes | `activated`, `closing`, `hold`, `release`: a hold is an id the calling row owns, ended by `release(id)` or that row's unload. `reportFault` reports a fault, `failure` reads it and `observeFault` subscribes. The calling row releases its subscription with `release(id)` or on unload. | -| `sessionConfig` | `session` | SessionScope | yes | `get()`: the creation-time configuration, the snapshot a tool call carries | -| `agentConfig` | `session` | SessionScope | yes | `get()`: the Agent's identity and default model | +| `sessionScope` | `session` | SessionScope | yes | `config`, `identity`, `phase`, `activated`, `closing`, `hold`, `release`, `reportFault`, `failure`, `observeFault`, `mount`, `unmount`, `openBranch` ([SessionScope](plugins/SessionScope.md), #2093) | | `timeline` | `branch` | BranchScope | yes, except `before` | `append`, the published sequence and the event query (§5.4); the query reaches other languages with its declaration | | `dispatcher` | `branch` | BranchScope | yes, `consume`, `listen` and reads; their Rust forms are the same `consume` and `subscribe`, which is Rust-only | Ordered consumption (§5.2) | | `branchLifecycle` | `branch` | BranchScope | yes | `activated`, `closing`. `registerOpening` registers work that branch opening waits for. | diff --git a/docs/design/plugins/ContextFacts.md b/docs/design/plugins/ContextFacts.md index 123b0337bb..c0e1311654 100644 --- a/docs/design/plugins/ContextFacts.md +++ b/docs/design/plugins/ContextFacts.md @@ -41,12 +41,29 @@ let Some(algorithm) = described.algorithm else { return Err(UsageError::NotCountable); // the caller keeps complete-request counts only }; let parts = facts.contributions(ContributionsRequest { - model: selection, + model: selection.clone(), fixed: Some(Fixed { system, tools }), messages, }).await?; -let total: f64 = parts.fixed.map(|fixed| fixed.estimated).unwrap_or_default() - + parts.messages.iter().map(|message| message.estimated).sum::(); +// Contributions are the counter's facts; the caller estimates them, now and after a restart. +let total = match parts.fixed { + Some(fixed) => facts.estimate(EstimateRequest { + model: selection.clone(), + algorithm: parts.algorithm.clone(), + contribution: fixed, + }).await?.tokens, + None => 0.0, +} + { + let mut sum = 0.0; + for message in parts.messages { + sum += facts.estimate(EstimateRequest { + model: selection.clone(), + algorithm: parts.algorithm.clone(), + contribution: message, + }).await?.tokens; + } + sum +}; ``` ## Own contract @@ -60,11 +77,11 @@ None. The capability snapshot, the config and the messages arrive in the request | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `describe` | The model's limits and counter identity | `{model}` | `{contextWindow, outputTokens, thresholdTokens, algorithm?}` | None; the owner completes the read | `not_adopted`, `closed` | -| `count` | One complete request's tokens | `{model, request}` | `{tokens}` | None | `not_adopted`, `closed` | -| `contributions` | The fixed and per-message contributions of a request | `{model, fixed?, messages}` | `{algorithm, fixed?, messages}` | None | `not_adopted`, `unsupported`, `closed` | +| `count` | One complete request's tokens | `{request}` | `{tokens}` | None | `not_adopted`, `closed` | +| `contributions` | The fixed and per-message contributions of a request, as the counter's facts | `{model, fixed?, messages}` | `{algorithm, fixed?: Contribution, messages: [Contribution]}` | None | `not_adopted`, `unsupported`, `closed` | | `estimate` | The tokens of one contribution | `{model, algorithm, contribution}` | `{tokens}` | None | `not_adopted`, `unsupported`, `algorithm_mismatch`, `closed` | -`model` is the Session's model selection: provider, model, adopted capability snapshot, config and metadata. `contributions` answers contributions in request order and, when `fixed` is present, the fixed contribution of the given system and tools. +`model` is the Session's model selection: provider, model, adopted capability snapshot, config and metadata; `count` takes the request, which already carries the selection. `contributions` answers the counter's facts in request order and, when `fixed` is present, the fixed contribution of the given system and tools. A `Contribution` is the serialized-byte and image facts the counter works from, so a caller can save it and estimate it again after a restart. ### Errors @@ -94,8 +111,8 @@ The four operations hold no resource and wait for nothing; their rows cover only ## Verification - `describe` answers the window, allowance and threshold of an adopted model; a missing or foreign snapshot is `not_adopted`. -- `count` equals the fixed contribution plus the message contributions summed through `estimate`, for a model with an additive counter. -- `contributions` is `unsupported` for a model without a counter; `estimate` with another algorithm is `algorithm_mismatch`. +- `count` equals the fixed contribution plus the message contributions, each summed through `estimate`, for a model with an additive counter; a saved contribution estimates again after a restart with the same number. +- `contributions` answers the counter's facts for a model with an additive counter and is `unsupported` otherwise; `estimate` with another algorithm is `algorithm_mismatch`. - A call in flight when the generation closes ends `closed`. ## Rule check @@ -126,6 +143,15 @@ The four operations hold no resource and wait for nothing; their rows cover only None. +## Supersedes + +This contract replaces the `contextModelHost` object; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `Context accounting and compaction → ContextModelHost` row of "Model preparation, history and tools". +- `docs/design/service-faces.md`: §3.5's `contextModelHost` row. + +Rule D: no client wire protocol or user-visible behavior changes; the statistics ContextUsage persists keep the same facts. + ## Binding appendix ```rust @@ -151,7 +177,6 @@ pub struct Limits { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CountRequest { - pub model: ModelSelection, pub request: ModelRequest, } @@ -187,8 +212,9 @@ pub struct Contribution { #[serde(rename_all = "camelCase")] pub struct ContributionsReply { pub algorithm: String, - pub fixed: Option, - pub messages: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fixed: Option, + pub messages: Vec, } #[derive(serde::Serialize, serde::Deserialize)] @@ -225,4 +251,4 @@ impl ContextFacts { } ``` -`ContributionsReply.fixed` and `.messages` are token counts, aligned with the request's messages; `Contribution` stays the serialized-bytes and image facts the counter works from. +`ContributionsReply.fixed` and `.messages` are the counter's facts, aligned with the request's messages; `estimate` turns one into tokens. `Contribution` stays the serialized-bytes and image facts the counter works from. `ContributionsReply.fixed` and `.messages` are the counter's facts, aligned with the request's messages; `estimate` turns one into tokens. Errors cross as `{code, message}`, `code` from the variant name. diff --git a/docs/design/plugins/ContextProjection.md b/docs/design/plugins/ContextProjection.md index 5f9d5896a5..7706ed2ddb 100644 --- a/docs/design/plugins/ContextProjection.md +++ b/docs/design/plugins/ContextProjection.md @@ -10,7 +10,7 @@ The owner answers: - **The context at a cutoff.** Which events place context, how a compaction's replacement and baseline apply, and the positions the fold covered. - **Rendered entries.** The context and its `HistoryEntry` list at one cutoff, for callers that need both. -- **A request-local projection.** The same content as the fold's streamed form, so a long history is released page by page instead of held whole. +- **A request-local projection.** The rendered entries and the compaction in force at a cutoff, folded page by page; the fold releases each page and the reply carries no event list, so a long history is not held whole. - **Recovery snapshots.** Encode the projection at a completed compaction's cut, validate a saved snapshot against its anchor, and decode the checkpoint it carries. Callers keep: @@ -64,8 +64,8 @@ else { | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `renderedStream` | The context and rendered entries at a cutoff, folded page by page | `{through, batch}` | `{context, history, configuration?, prompt?}` | The caller drops the call; the fold stops at its last page | `future_sequence`, `invalid`, `storage`, `closed` | -| `renderedContext` | The context and rendered entries at a cutoff | `{through}` | `{context, history}` | The caller drops the call | `future_sequence`, `storage`, `closed` | +| `renderedStream` | The rendered entries and the compaction in force at a cutoff, folded page by page, without retaining events | `{through, batch}` | `{history, configuration?, prompt?, ancestry, compaction?, branches, compactionCut?}` | The caller drops the call; the fold stops at its last page | `future_sequence`, `invalid`, `storage`, `closed` | +| `renderedContext` | The context and rendered entries at a cutoff, with the events the projection kept | `{through}` | `{context, history}` | The caller drops the call | `future_sequence`, `invalid`, `storage`, `closed` | | `snapshot` | Encode the projection at a completed compaction's cut | `{context, retainFrom, anchor}` | `{snapshot}` | None; the owner completes the read | `invalid`, `storage`, `closed` | | `streamCheckpoint` | The checkpoint of the fold that starts after a compaction's cut | `{through, retainFrom, batch}` | `{checkpoint}` | The caller drops the call | `future_sequence`, `invalid`, `storage`, `closed` | | `snapshotFromCheckpoint` | A snapshot that carries an already-computed checkpoint | `{checkpoint, anchor}` | `{snapshot}` or none when the anchor does not match | None | `invalid`, `storage`, `closed` | @@ -103,7 +103,7 @@ else { ## Verification - A fold at a cutoff returns the events that place context and the compaction in force, with positions that compare across the branch chain. -- `renderedStream` releases each page: a fold larger than one page keeps only the current projection. +- `renderedStream` releases each page and its reply carries no event list: a fold larger than one page keeps only the current projection. `renderedContext` materializes the events and is the inspection read. - `snapshot` encodes the checkpoint of a completed compaction; a snapshot of another interpreter or a mismatched anchor is `invalid` or answers none. - `context_in` no longer exists; every read is the caller's own branch. - A call in flight when the branch closes ends `closed`. @@ -137,6 +137,15 @@ else { None: the owner needs only the branch's `timeline` operations. +## Supersedes + +This contract replaces the `historyRenderer` value; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `Loop and ContextPreparation → HistoryRenderer` row of "Model preparation, history and tools". +- `docs/design/service-faces.md`: §3.5's `historyRenderer` row. + +Rule D: no client wire protocol or user-visible behavior changes; `StreamedContext` keeps its fields and the model-visible text is unchanged. + ## Binding appendix ```rust @@ -153,12 +162,21 @@ pub struct RenderedStreamRequest { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct StreamedContext { - pub context: ContextHistory, pub history: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub configuration: Option, #[serde(default, skip_serializing_if = "Option::is_none")] - pub prompt: Option, + pub prompt: Option, + /// Root first: how positions compare across the branch chain. + pub ancestry: Vec, + /// The completed compaction in force, with its cut and baseline. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction: Option, + /// Root first: the segments the fold read. + pub branches: Vec, + /// The position of the cut in effect. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub compaction_cut: Option, } #[derive(serde::Serialize, serde::Deserialize)] @@ -245,4 +263,4 @@ impl ContextProjection { } ``` -`ContextHistory`, `HistoryEntry`, `ProjectionCheckpoint`, `RecoverySnapshot`, `AgentEvent` and `TimelinePosition` are the types those facts already use; the reply carries no event handle beyond the events the facts are. +`ContextHistory`, `HistoryEntry`, `ProjectionCheckpoint`, `RecoverySnapshot`, `AgentEvent` and `TimelinePosition` are the types those facts already use and gain `Serialize`/`Deserialize` for this face; their fields do not change. `renderedStream` carries no `ContextHistory`, so a streamed fold never holds the event list; `renderedContext` and the snapshot reads carry events or checkpoints because their callers need them. Errors cross as `{code, message}`, `code` from the variant name. diff --git a/docs/design/plugins/FileAccessFacts.md b/docs/design/plugins/FileAccessFacts.md index c308dc9cb1..c29733decc 100644 --- a/docs/design/plugins/FileAccessFacts.md +++ b/docs/design/plugins/FileAccessFacts.md @@ -9,8 +9,8 @@ The owner answers what one call's target path is and which file-access facts hol The owner answers: - **The resolved target.** The path a call names with `~`, the working directory, `..` and links resolved, as the workspace sees it. -- **The facts.** Workspace, system, owned and grant membership under the effective access mode, plus the reason a workspace discovery failed when it did. -- **The confirmed roots.** The workspace and confirmed grant roots a command's process boundary may use. +- **The facts.** Workspace, system, owned and grant membership under the branch's effective access preset and the grant mode the call asks for, plus the reason a workspace discovery failed when it did. +- **The confirmed roots.** The workspace and the managed worktree roots a command's process boundary may use. Callers keep: @@ -20,14 +20,16 @@ Callers keep: | Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| Permission resolves a file call's target and decides with the facts | No: `~`, cwd, `..` and link resolution are the workspace's knowledge, and the owned and grant facts come from two owners the caller would otherwise each hold | `check` | -| A command's preparation needs the confirmed workspace roots | No: the roots are validated against the Session's workspace and grants; a caller that composed them could start a process with an expired grant | `workspaceRoots` | +| Permission resolves a file call's target and decides with the facts under the branch's access preset | No: `~`, cwd, `..` and link resolution are the workspace's knowledge, the grant rule reads the preset, and the owned and grant facts come from two owners the caller would otherwise each hold | `check` | +| A command's preparation needs the confirmed workspace boundary | No: the workspace and the managed worktree roots are validated against the Session's workspace; a caller that composed them could start a process outside the boundary | `workspaceRoots` | ## Caller example ```rust // Permission: one file call's target and facts under the requested access. -let facts = access.check(Check { access: FileAccess::Write, mode: GrantMode::Ask, path }).await?; +let facts = access + .check(Check { access: FileAccess::WorkspaceReadWrite, mode: GrantMode::Write, path }, cancelled) + .await?; let inside = facts.workspace || facts.system || facts.owned || facts.grant; ``` @@ -43,17 +45,17 @@ let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; - The Session's working directory and identity: the owner's own Session part. - `P:fileStorage` — `stat` and the path validation the workspace root uses. - `P:sessionFiles` — whether the Session owns the target file. -- `S:sessionGrants` — the Session's file grants. +- `S:sessionGrants` — the Session's file grants, read by `check` only. - `P:worktrees` — managed worktree roots that extend the workspace. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `check` | Resolve a call's target and answer the facts under one access mode | `{access, mode, path}` | `{target, workspace, system, owned, grant, discoveryError?}` | The caller drops the call; the reads stop | `invalid`, `unavailable`, `cancelled`, `closed` | -| `workspaceRoots` | The workspace and confirmed grant roots a command may use | `{cwd}` | `{roots}` | The caller drops the call | `invalid`, `unavailable`, `cancelled`, `closed` | +| `check` | Resolve a call's target and answer the facts under the branch's access preset | `{access, mode, path}` | `{target, workspace, system, owned, grant, discoveryError?}` | The caller drops the call; the reads stop | `invalid`, `unavailable`, `cancelled`, `closed` | +| `workspaceRoots` | The workspace and managed worktree roots a command may use | `{cwd}` | `{roots}` | The caller drops the call | `invalid`, `unavailable`, `cancelled`, `closed` | -`access` is read or write; `mode` is the grant mode the call asks for; `path` is the path the call named. `target` is the resolved path, and it is what the caller passes to the file operation. +`access` is the branch's access preset (`dim_agent_types::FileAccess`: `read-only`, `workspace-read-write`, `unrestricted`); `mode` is the grant mode the call asks for (`dim_agent_types::GrantMode`: `read`, `write`); `path` is the path the call named. `target` is the resolved path, and it is what the caller passes to the file operation. A write grant is inert under `read-only` and active under `workspace-read-write` or `unrestricted`. ### Errors @@ -71,20 +73,21 @@ let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; | Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | | `check` | The owner resolves the target, reads the owned file and the grants, and answers the facts | A dropped call ends the reads; nothing is decided | An in-flight call ends `closed` | The calling row; the owner holds no resource | -| `workspaceRoots` | The owner resolves the cwd, returns the workspace and the confirmed grant roots | A dropped call ends the read | `closed` | The calling row | +| `workspaceRoots` | The owner resolves the cwd, returns the workspace and the managed worktree roots | A dropped call ends the read | `closed` | The calling row | ## Exceptions with reasons - No `sessionId` in the request: the owner is the Session's instance, so the Session id is the owner's own identity; a request field would let one Session ask for another's facts. - `discoveryError` is a field: a workspace that cannot be discovered is a fact the caller shows, not a refusal; approvals the user already gave stay available. +- `access` is the three-valued access preset, not a read/write flag: under `read-only` a write grant is inert, and the owner decides that from the preset the caller passes. - `workspaceRoots` fails rather than answering an empty list: a command started with an unconfirmed boundary would run outside the workspace the user approved. ## Verification -- `check` resolves `~`, `..` and a link before answering; the target is absolute. +- `check` resolves `~`, `..` and a link before answering; the target is absolute; a write grant under `read-only` answers `grant: false`. - An owned Session file and a granted path each answer their fact under the requested mode; a path outside every fact answers all false. - A failed discovery answers `workspace: false` with `discoveryError` and no error. -- `workspaceRoots` answers the workspace plus confirmed grants; `unavailable` when the grants cannot be read. +- `workspaceRoots` answers the workspace plus the managed worktree roots; `unavailable` when the workspace cannot be read. - A call in flight when the Session closes ends `closed`. ## Rule check @@ -115,31 +118,28 @@ let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; None. +## Supersedes + +This contract replaces the object shape of the file-access facts; the delivery in #2025 carries the migration. + +- [ADR 014](../../adr/014-file-access-facts.md): the query is stated here as a Session-scoped operation `check`, with the Session instance supplying the session id and `FileAccess` and `GrantMode` as the same query arguments the ADR names. +- `crate::file_access::ReadFileAccessFacts` and the `FileAccessFacts` wrapper: the two reads replace the trait and the object. + +Rule D: no client wire protocol or user-visible behavior changes; the change is plugin-facing. + ## Binding appendix ```rust use dim_agent_capabilities::host::CancelledFn; use dim_agent_runtime::PublicService; +use dim_agent_types::{FileAccess, GrantMode}; -#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Access { - Read, - Write, -} - -#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum GrantMode { - Ask, - Session, - Once, -} +use dim_agent_types::{FileAccess, GrantMode}; #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Check { - pub access: Access, + pub access: FileAccess, pub mode: GrantMode, pub path: String, } @@ -193,4 +193,4 @@ impl FileAccessFacts { } ``` -`cancelled` is the binding's cancellation argument, not a request field. Paths cross as UTF-8 strings; a path that is not UTF-8 is `invalid`. +`cancelled` is the binding's cancellation argument, not a request field. Paths cross as UTF-8 strings; a path that is not UTF-8 is `invalid`. Errors cross as `{code, message}`, `code` from the variant name. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index ad598766a5..62f95cb967 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -26,7 +26,7 @@ A plugin is split by the owner of its state into parts, each placed in its owner | [Pursuit](Pursuit.md) (evaluator judge mode of Goal) | — | `judge` on `session.goal.set` | completion requests decided by evaluator branches; conclusion inputs and Goal's outcomes | M2; #422 | | [ModelRecovery (proposal)](ModelRecovery.md) | — | — | proposed disposer registration (Loop port not implemented); the handover input it writes | [#1210](https://github.com/arcships/dim/issues/1210) | | [Web](Web.md) | — | `web_search`, `web_fetch` tools | — | P2; optional package | -| [ContextCompaction](ContextCompaction.md) (supplements to Loop and ContextPreparation; [ContextUsage proposal](ContextUsage.md)) | — | `ContextModelHost`, summary `CompactionStrategyHost`, `session.context.*` | `context/compact` command and compaction step in Loop; K-turn cut and usage query in ContextPreparation | P2 | +| [ContextCompaction](ContextCompaction.md) (supplements to Loop and ContextPreparation; [ContextUsage proposal](ContextUsage.md)) | — | `session.context.*`; the model facts and the summary policy are [Context facts](ContextFacts.md) and [Summary strategy](SummaryStrategy.md) (#2025) | `context/compact` command and compaction step in Loop; K-turn cut and usage query in ContextPreparation | P2 | | [Prompt](Prompt.md) | — | `guideEntries`: the input guide's frame, the entries in force and their composition | `Prompt`: the System its publisher adopts carries the composition over the entries in force, and a host-prepared request carries the same composition, placed by Loop | #548 | | [PromptSources](PromptSources.md) | — | the named sources, their policy texts at the factory configuration, and the state and rule entries | — | #548 | | [EnvironmentClients](EnvironmentClients.md) | App Server read-only `sessionClientsHost` presence (Connection and UiHost) | — | presence snapshots as `` inputs at branch open and on `ClientsChanged` | #1019 | diff --git a/docs/design/plugins/RequestSettings.md b/docs/design/plugins/RequestSettings.md index 983a464efd..cceea3f28c 100644 --- a/docs/design/plugins/RequestSettings.md +++ b/docs/design/plugins/RequestSettings.md @@ -22,13 +22,13 @@ Callers keep: | --- | --- | --- | | Loop prepares the model settings of a turn that has no adopted configuration yet | No: the catalog defaults and the allowance rule are the owner's knowledge; composing them in Loop duplicates the provider profile's decision | `settings` | | Loop requests with a configuration Prompt adopted during the run | Yes: Loop reads the adopted record from the Timeline | Business | -| A caller changes the model for the next turn | Yes: the Session's model methods write the record and Prompt adopts it | Business | +| A caller changes the model for the next turn | Yes: Prompt adopts the change as the `context/configured` Timeline record; the creation record does not change | Business | ## Caller example ```rust // Loop: the first request of a Session before any configuration is adopted. -let defaults = request_settings.settings()?; +let defaults = request_settings.settings(); let settings = ModelSettings { provider_id: defaults.provider_id, model_id: defaults.model_id, @@ -39,6 +39,7 @@ let settings = ModelSettings { metadata: defaults.metadata.map(|mut metadata| { metadata.session_id = Some(session_id); metadata.turn_id = Some(turn_id); + metadata.extensions.insert("requestId".into(), request_id); // per request, written by Loop metadata }), }; @@ -68,7 +69,7 @@ None: the operation holds no resource and waits for nothing. - `config` may already be the adopted allowance repair: the owner repairs the stored allowance against the declared limits, so a request started from this value cannot exceed the model's capacity. - The value is fixed at creation: a model change during the run is a Timeline record (`context/configured`), and Loop reads that record; the value is never stale for its one use. -- `metadata` carries the profile's extensions (for example a request-id extension); the owner publishes them and Loop only adds the turn's ids. +- `metadata` carries the profile's static extensions. The per-request members — session, turn and request id — are Loop's: the aimux request log reads `requestId` from the request in flight, so the value cannot carry it. ## Verification @@ -103,6 +104,15 @@ None: the operation holds no resource and waits for nothing. None. +## Supersedes + +This contract replaces the `prepareModelHost` object; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `Loop → PrepareModelHost` row of "Model preparation, history and tools". +- `docs/design/service-faces.md`: §3.5's `prepareModelHost` row. + +Rule D: no client wire protocol or user-visible behavior changes; the aimux request log keeps its `requestId`, now written by Loop. + ## Binding appendix ```rust @@ -132,4 +142,4 @@ impl RequestSettings { } ``` -`ModelSelection`, `ModelId` and the reply's members are the crate's existing data; `settings` answers the value itself, as `agentConfig.get` did before this owner existed. +`ModelSelection`, `ModelId` and the reply's members are the crate's existing data; `settings` answers the value itself, as `agentConfig.get` did before this owner existed. The reply's members are the crate's existing data. Errors cross as `{code, message}`; this owner has none. diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index c089f2fb48..48423dfa8d 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -8,10 +8,10 @@ SessionScope is the runtime's Session owner: the creation record and identity, t SessionScope owns: -- **The creation record.** The Session's mount list, working directory, model selection, system prompt, permission preset, collaboration role, interactive flag, language seed and initial title, fixed when the Session is built. The record never changes while the Session runs. +- **The creation record.** The Session's mount list, working directory, model selection, system prompt, permission preset, collaboration role, interactive flag, language seed and initial title, fixed when the Session is built. Every member is fixed except `language`, which the native store updates in place; a caller reads the live reply language from `sessionLanguage`, never from this value. - **Identity.** The Session id and whether the Session was restored from the store. - **The phase.** Loading, Active, Closing, Closed, monotonic and never replaced by an earlier phase. `activated` and `closing` are the waits on the two transitions. -- **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. Every lease is bound to the calling row and the owner settles it at the row's unload, so no caller frees anything on an error path. `withHold` holds one for the extent of the caller's callback; `hold` answers an id for work that outlives the call. A lease reports nothing and cancels nothing. +- **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. Every lease is bound to the calling row and the owner settles it at the row's unload, so no caller frees anything on an error path. `hold` answers an id for accepted work; the id is bound to the calling row and the owner settles it at the row's unload. A lease reports nothing and cancels nothing. - **The failure record.** The first fault that stopped the Session; a storage failure supersedes an earlier non-storage fault and the first storage failure wins. `reportFault` writes, `failure` reads, `observeFault` subscribes. - **Content instances.** Session-owned content mounted from a definition — a Skill's content, an MCP connection — inside this Session's subtree, addressed by instance id. The owner admits only groups whose configured parent is the Session group. - **The branch's runtime context.** One construction per branch id, handed to the branch tree, which owns and settles the context (see Exceptions with reasons). @@ -23,7 +23,7 @@ Callers keep as business: - What a fault means for their work; the failure record says only that the Session stopped. - Which definitions to mount and when to retire them. - Which branches exist, their ids and their ancestors: TimelineTree owns the branch directory (#2024). -- Acting on a line's owners: the mechanism resolves a branch-scope service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation. SessionScope publishes no operation, request or reply for that path. +- Acting on a line's owners: the mechanism resolves a branch-group service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation. Any branch-group data face is reachable this way except registration points and lifecycle services. SessionScope publishes no operation, request or reply for that path. | Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | @@ -31,13 +31,12 @@ Callers keep as business: | Read identity: Attachments' ownership check, Permission and tool-source attribution, the store key | No | `identity` | | Wait for publication or for close to start: BranchLine's writer, Skills' replacement, ShellInput's refusal, FileAccess' gate | No: polling a value makes every caller write the wait | `activated`, `closing` | | Read the phase now: Goal's state read, MCP's admission, ShellInput's refusal | No | `phase` | -| Run accepted work under a hold for the extent of the call: ShellInput's command | No: the idle-release decision is the owner's, and composing it makes the caller hold a counter or a token across every error path | `withHold` | -| Hold across work that outlives the call: BackgroundExec's task, Report's draft, Collaboration's member | No: a callback would have to stay pending for the whole task, and a tool that answers a task id returns before the command ends | `hold`, settled at the row's unload | +| Keep accepted work from being ended by an idle release: ShellInput's command, BackgroundExec's task, Report's draft, Collaboration's member; each run outlives the call that started it | No: the idle-release decision is the owner's, and a callback cannot cover work that continues after the call returns | `hold`, settled at the row's unload | | End a hold early, after the work's last fact, so an idle release may happen sooner | No: the id is bound to the calling row and only the owner releases it | `release` | | Record a fault: Prompt on a prompt or recovery failure | No | `reportFault` | | Read the current fault | No | `failure` | | Subscribe to later faults: a part in another language | No: a subscription is the owner's, not a poll loop in the caller | `observeFault` | -| Act on one line's owner by line id: write an input (`inputQueue.submit`), withdraw one (`inputQueue.withdraw`), read usage (`contextUsage.read`), read the adopted configuration (`prompt.adoptedConfiguration`), read pending approvals (`approval.pending`) | No: a part cannot address a line's instance itself, and a forwarding operation here would be the facade §7 forbids | Not this owner: the mechanism resolves the branch-scope service by line id (`line_owner::(line)`), and the caller calls that owner's operation | +| Act on one line's owners by line id: any branch-group data face — `inputQueue.submit` or `withdraw`, `contextUsage.read`, `prompt.adoptedConfiguration`, `approval.pending` — except registration points and lifecycle services | No: a part cannot address a line's instance itself, and a forwarding operation here would be the facade §7 forbids | Not this owner: the mechanism resolves the branch-group service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation | | Mount and retire Session content: Skills' content instances, MCP's connections | No: the Session's anchor and the group admission are the owner's knowledge | `mount`, `unmount` | | Open a branch's runtime context: TimelineTree | No: only the runtime constructs a branch's context, in its own subtree | `openBranch` | @@ -65,26 +64,16 @@ scope.unmount(UnmountRequest { instance_id: mounted.instance_id }).await?; ShellInput refuses after closing starts and holds the Session while a command runs: -```rust -// ShellInput: the hold covers the command; the owner releases it when the call returns, -// and the row's unload releases it if the caller never returns. -scope.phase()?; // closing or closed -> RpcError::closed() -scope - .with_hold( - WithHoldRequest { work: Arc::new(move || Box::pin(run_command(cancel.clone()))) }, - cancel.clone(), - ) - .await?; -``` - -BackgroundExec's task outlives the call, so the part takes an id; the owner settles it at -the row's unload, and the part releases it when the task ends only so an idle release may -happen sooner: +ShellInput's run outlives the `shell.run` call: a cancelled call returns at once and the +run keeps its hold until it leaves ShellInput's registry. BackgroundExec and Report keep the +same shape. The id belongs to the part's row; the owner settles it at the row's unload, and +the part releases it when the work ends only so an idle release may happen sooner. ```rust -// The id belongs to this part's row; a lost id is settled by the owner. +// ShellInput: the run's hold lives in the part's registry, not in the call. +scope.phase()?; // closing or closed -> RpcError::closed() let lease = scope.hold().await?.lease_id; -self.leases.lock().unwrap().insert(task_id, lease); +self.runs.lock().unwrap().insert(run_id, lease); ``` A part in another language subscribes to the fault record: @@ -111,7 +100,7 @@ self.nodes.insert(id, branch); ### Dependencies -SessionScope injects nothing. The assembly gives the owner its creation record and the Session anchor; the trusted host installs the content definitions the Session may mount. SessionScope no longer provides the Agent's configuration, the Skills or Collaboration factory texts, or the five host ports; those names leave the catalog (delivery). +SessionScope injects nothing. The assembly gives the owner its creation record and the Session anchor; the trusted host installs the content definitions the Session may mount. SessionScope no longer publishes the Agent's configuration, the Skills or Collaboration factory texts, or the names of the five host ports (`historyRenderer`, `contextModelHost`, `prepareModelHost`, `prepareContextHost`, `compactionStrategyHost`); those names leave the catalog (delivery). The Session store constructs the Timeline engine and its Session-scope binding; SessionScope installs that binding in the Session instance and never hands it to a process caller. The operations are the engine's (#2018): the Session face publishes the per-line reads and the completion subscriptions, while `query` and `sessionConfig` stay on the process face `store` because an unloaded Session has no Session instance to host them. One engine, one operation set, one spelling per operation. @@ -124,14 +113,13 @@ The Session store constructs the Timeline engine and its Session-scope binding; | `phase` | The phase now | `{}` | `{phase}`: `loading`, `active`, `closing`, `closed` | None | None | | `activated` | Wait until the Session is published or starts closing | `{}` | `{active}`: true only when published and not closing | The caller drops the call; the owner's close ends the wait with `active: false` | None | | `closing` | Wait until the Session starts closing | `{}` | `{}` | The caller drops the call | None | -| `withHold` | Run the caller's work under a lease for the extent of the call | `{work}` | `{}` | The caller's cancel drops the work; the owner releases the lease and answers `cancelled` | `cancelled`, `closed` | -| `hold` | Keep an idle release from ending this Session for work that outlives the call | `{}` | `{leaseId}` | None; the call does not wait | `closed` | +| `hold` | Keep an idle release from ending this Session while accepted work runs | `{}` | `{leaseId}` | None; the call does not wait | `closed` | | `observeFault` | Receive the current fault and later reports until released or the row unloads | `{listener}` | `{leaseId}` | None; the call does not wait | `closed` | | `release` | End a lease or a subscription before the row unloads | `{leaseId}` | `{released}`: false when the id was already released | None | `invalid` when the id belongs to another row; `closed` | | `reportFault` | Record the fault that stopped the Session | `{fault}` | `{}` | None | None | | `failure` | The fault in force, if any | `{}` | `{fault?}` | None | None | | `mount` | Create a Session-owned content instance from a definition | `{group, definitionId, instanceData}` | `{instanceId}` | The caller drops the call; an instance it no longer waits for is shut down before the reply | `invalid`, `not_ready`, `cleanup`, `closed` | -| `unmount` | Retire a content instance this Session owns | `{instanceId}` | `{}` | None; the owner completes the release | `invalid` when the id belongs to another Session; `cleanup`; `closed` | +| `unmount` | Retire a content instance this Session owns | `{instanceId}` | `{}` | None; the owner completes the release | `unknown` when no live instance has the id; `cleanup`; `closed` | | `openBranch` | Construct a branch's runtime context for the branch tree | `{branchId, ancestors}` | the branch's runtime context (see Exceptions) | The caller drops the call; a construction the caller abandoned is shut down before the branch becomes visible | `closed`, `build` | `listener` and `work` are callbacks by reference: they run outside the owner's locks and outside the Timeline's commit lock. `work` returns nothing; its failure and its cleanup stay with the caller. A lease id is an owner-issued token bound to the calling row; it carries no authority, the owner settles it at the row's unload, and a caller never has to free it on an error path. @@ -140,9 +128,9 @@ The Session store constructs the Timeline engine and its Session-scope binding; | Kind | Operation | What the caller does next | | --- | --- | --- | -| `closed` | `withHold`, `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | -| `cancelled` | `withHold` | The caller's cancel stopped the work before it finished; the lease is released and nothing else changed | -| `invalid` | `release`, `unmount`, `mount` | Fix the id or the definition: an id of another row or Session, a group outside this Session's subtree, an unknown definition | +| `closed` | `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | +| `invalid` | `release`, `mount` | Fix the id or the definition: an id of another row, a group outside this Session's subtree, an unknown definition | +| `unknown` | `unmount` | The id names no live instance of this Session; nothing to retire | | `not_ready` | `mount` | Act on the reported row and state: the definition's rows did not activate; the instance was shut down and nothing is left to release | | `cleanup` | `mount`, `unmount` | The instance is unreachable but its shutdown failed; the Session will report it as a fault; treat the content as unavailable | | `build` | `openBranch` | The branch did not open: `cause` is why, `cleanup` is a shutdown that also failed; the tree records the branch as failed and settles it | @@ -153,7 +141,6 @@ The Session store constructs the Timeline engine and its Session-scope binding; | Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | -| `withHold` | The owner takes a lease, calls the work, and releases the lease when the work returns | The dropped call stops the work; the owner releases the lease and answers `cancelled` | An in-flight call ends `closed`; a lease never delays a close | SessionScope; the work's own cleanup by the calling row | | `hold` | The owner checks the phase, increments the hold count and registers the lease under the calling row | The row's unload releases every lease the row still holds | No new lease is issued once an idle release is decided; an existing lease never delays a close | SessionScope | | `observeFault` | The owner registers a listener under the calling row, calls it once with the fault in force (none included), then on every later report | The row's unload stops the listener and drops the registration | The listener stays until the generation unloads; a report after close is ignored | SessionScope; the listener's work by the calling row | | `release` | The owner removes the lease or subscription and disposes it | A dropped call leaves the lease in place; the row's unload settles it | An id of an unloaded generation is `closed` | SessionScope | @@ -182,14 +169,12 @@ The Session store constructs the Timeline engine and its Session-scope binding; - `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. - The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. - `identity` carries no version: the id and the restored flag are fixed at creation. -- `withHold` cannot replace `hold`: a tool that answers a task id returns before the command ends, and a member, a draft or a background task outlives many calls, so a callback kept pending for the whole work would make the tool wait for its own task. Long-running commands are fine with the callback: `withHold` awaits the work, and a client in another language passes the callback by reference while the row stays the settlement owner. - A lease is a value, not a handle: it names nothing the caller can use except in `release`, and the owner releases every lease at the row's unload, so a caller that loses the id leaks nothing. `release` only lets an idle release happen sooner. - Content instance ids are the Session's, not the caller's: the Session's close shuts down every instance it mounted, so a part that never unmounts leaves obsolete content published until the Session ends, without breaking the owner. ## Verification -- `withHold` releases its lease when the work returns, and answers `cancelled` with the lease released when the caller cancels; the work's error path needs no release. -- `hold` answers `closed` once an idle release is decided; a lease taken before it keeps the Session loaded until released, and never refuses a close; a lost id is settled at the row's unload. +- `hold` answers `closed` once an idle release is decided; a lease taken before it keeps the Session loaded until released, and never refuses a close; a lost id is settled at the row's unload; another row's id is `invalid` on release. - `observeFault` delivers the fault in force and later reports; `release` answers `released: true` then `false`; another row's id is `invalid`; the row's unload stops delivery. - `reportFault` keeps the first fault; a storage fault after a non-storage one wins; a non-storage fault after a storage one loses. - `mount` answers `invalid` for a group outside the Session's subtree, `not_ready` for a definition whose row failed (and leaves no instance), and shuts down an abandoned mount; `unmount` answers `cleanup` when the shutdown fails and `invalid` for another Session's id. @@ -213,7 +198,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; | §4 rule 7 | Callers use these operations; no caller reads the hold count, the fault slot or an instance's fiber. | | §4 rule 8 | No infrastructure change. SessionScope is the runtime's Session part and its shape is the runtime's decision; the operations above are the data face those decisions already require. | | §4 rule 9 | No Timeline fact: the phase and the fault record are runtime state, read live and never persisted as events. | -| §7 values, ids and objects | The record, identity, phase and fault are values; `withHold` takes the caller's work as a callback; a lease id and a content instance id are the owner's, bound to the calling row and settled at its unload; the one object is `openBranch`, with the handover design above. | +| §7 values, ids and objects | The record, identity, phase and fault are values; a lease id and a content instance id are the owner's, bound to the calling row and settled at its unload; the one object is `openBranch`, with the handover design above. | | §7 no proxy lookup | The owner returns only its own state; the Agent's configuration and the Skills and Collaboration factory texts leave this face. | | §7 one interface | One name, `sessionScope`, on the owner type; the Rust binding and the wire call the same methods; no facade or wrapper type. | | §7 cross-language | Every operation is data, a callback by reference or an id; no method exists only for Rust. | @@ -230,12 +215,23 @@ The Session store constructs the Timeline engine and its Session-scope binding; - The runtime's `Session` facade stops forwarding line operations: `end_branch`, `set_default_branch`, `branch`, `branches`, `directory`, `default_and_directory`, `ended_head`, `sequence`, `batch_end` and `query` are TimelineTree's, and the Session access surface must not restate them. - [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns the Timeline engine and constructs the Session-scope binding; SessionScope installs it. The Session face publishes the per-line reads and the completion subscriptions; `query` and `sessionConfig` stay on `store`; `createSession`, `releaseSession`, `rollbackSession` and `append` are not on the Session face. +## Supersedes + +This contract replaces the Session-scope paragraphs and rows that state these names; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `sessionLifecycle` rows of "Retained operations" and "New rutis APIs on existing owners", the `sessionLoader` row, and the "Calls from a Session to a selected branch" section — a branch-group service is resolved by line id (`line_owner::(line)`), and `timelineTree.call` is removed rather than kept. +- `docs/design/contracts/service-faces.md`: §3.6's `timelineFactory` row and §3.2's `agentConfig`, `skillsConfig` and `collaborationConfig` rows; the Session-scoped `timelineStore` spelling in §3.4 is stated by this contract, with the engine's operations left to #2018. +- `docs/design/plugin-contract.md`: the `sessionIdentity`, `sessionLifecycle`, `sessionConfig` and `agentConfig` rows of the named-services table. +- `docs/design/contracts/resource-faces.md` §5: the Session-scoped `timelineStore` names this contract spells; the engine and its process face remain #2018's. + +Rule D: no client wire protocol or user-visible behavior changes; every change here is plugin-facing. + ## Binding appendix The service is marked on the owner type under one name; the existing names `sessionConfig`, `sessionIdentity`, `sessionLifecycle`, `sessionLoader` and `timelineFactory` stop existing. ```rust -use dim_agent_runtime::{PublicService, SessionConfig, SessionFault, SessionPhase}; +use dim_agent_runtime::{PublicService, SessionConfig, SessionFault}; use rutis::Ctx; use std::sync::Arc; @@ -252,7 +248,17 @@ pub struct Identity { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct PhaseReply { - pub phase: SessionPhase, + pub phase: Phase, +} + +/// The wire form of the four phases; the owner maps its internal phase onto it. +#[derive(Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Phase { + Loading, + Active, + Closing, + Closed, } #[derive(serde::Serialize, serde::Deserialize)] @@ -309,16 +315,6 @@ pub struct OpenBranchRequest { pub type FaultListener = Arc) -> rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + Send + Sync>; -/// The caller's accepted work; its error and cleanup stay with the caller. -pub type WorkFn = - Arc rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + Send + Sync>; - -#[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct WithHoldRequest { - pub work: WorkFn, -} - #[derive(Debug, thiserror::Error)] pub enum SessionScopeError { #[error("{0}")] @@ -329,8 +325,11 @@ pub enum SessionScopeError { NotReady(String), #[error("{0}")] Cleanup(String), - #[error("{0}")] - Build(String), + #[error("{cause}")] + Build { + cause: String, + cleanup: Option, + }, #[error("{0}")] Unknown(String), } @@ -344,16 +343,19 @@ impl SessionScope { pub fn phase(&self) -> PhaseReply { /* ... */ } pub async fn activated(&self) -> ActivatedReply { /* ... */ } pub async fn closing(&self) { /* ... */ } - pub async fn with_hold( + pub async fn hold(&self, caller: &Ctx) -> Result { /* ... */ } + pub async fn observe_fault( &self, - request: WithHoldRequest, - cancelled: dim_agent_capabilities::host::CancelledFn, - ) -> Result<(), SessionScopeError> { /* ... */ } - pub async fn hold(&self) -> Result { /* ... */ } - pub async fn observe_fault(&self, listener: FaultListener) -> Result { /* ... */ } + caller: &Ctx, + listener: FaultListener, + ) -> Result { /* ... */ } pub async fn report_fault(&self, fault: SessionFault) { /* ... */ } pub fn failure(&self) -> Option { /* ... */ } - pub async fn release(&self, request: LeaseRequest) -> Result { /* ... */ } + pub async fn release( + &self, + caller: &Ctx, + request: LeaseRequest, + ) -> Result { /* ... */ } pub async fn mount(&self, definition: MountDefinition) -> Result { /* ... */ } pub async fn unmount(&self, request: UnmountRequest) -> Result<(), SessionScopeError> { /* ... */ } pub async fn open_branch( @@ -365,4 +367,4 @@ impl SessionScope { } ``` -`caller: &Ctx` and `cancelled: CancelledFn` are the binding's caller row and cancellation argument; the dispatch fills them and no caller sends or names a row. `LeaseId`, `InstanceId` and the ancestor pairs cross as strings and numbers. +`caller: &Ctx` and `cancelled: CancelledFn` are the binding's caller row and cancellation argument; the dispatch fills them and no caller sends or names a row. `LeaseId`, `InstanceId` and the ancestor pairs cross as strings and numbers. `cancelled` and `caller: &Ctx` are the binding's cancellation and caller-row arguments, not request fields; the dispatch fills them. Errors cross as `{code, message}`: `code` is the variant name in snake_case, `message` is `Display`, and a variant's own members (for example `build`'s `cleanup`) travel beside them. diff --git a/docs/design/plugins/SummaryStrategy.md b/docs/design/plugins/SummaryStrategy.md index a8156fca42..2042444faa 100644 --- a/docs/design/plugins/SummaryStrategy.md +++ b/docs/design/plugins/SummaryStrategy.md @@ -62,6 +62,7 @@ match outcome.outcome { - `P:modelHost` — the summarizer's model calls, under the existing failure and credential policy. - `P:providerConnectionResolver` — the connection each summarizer request uses; the connection lives only inside the call. - `S:summaryPromptSettingsHost` — optional: the operator's system prompt override, read once when the owner loads. +- `S:guideEntries` — the `` entry, registered until the owner unloads. ### Operations @@ -72,7 +73,7 @@ match outcome.outcome { `model` is a model selection; the owner asks `contextFacts` for its limits and counts. `retainLimit` is the cut the retention rule allows; `cuts` lists every legal cut in order; `request` is the request whose context is compacted. -`completed` carries `{retainFrom, replacement, diagnostics}`; `skipped` carries `{reason, diagnostics}`; `failed` carries `{error, diagnostics}`. `diagnostics` holds the model call count, the summed usage, the strategy's own record and the duration. +`completed` carries `{retainFrom, replacement, diagnostics}`; `skipped` carries `{reason, diagnostics}`; `failed` carries `{error, diagnostics}`. A compaction with no legal cut, or nothing before the cut, is `skipped { reason: "nothing_to_compact" }` with no model call. `diagnostics` holds the model call count, the summed usage and the strategy's own record; the caller measures the duration in its compaction record. ### Errors @@ -80,7 +81,7 @@ match outcome.outcome { | --- | --- | --- | | `cancelled` | `compact` | The call was stopped before any model work or by the caller's cancellation; the history is unchanged | | `closed` | both | The owner is unloading; the compaction did not run | -| `invalid` | `compact` | Fix the input: no legal cut, a cut outside the history, a request without an adopted model | +| `invalid` | `compact` | Fix the input: a cut outside the history, or a request without an adopted model. A history with no legal cut is the `skipped` outcome, not an error | | `not_adopted` | `describe` | Adopt the model again; without it the plan cannot be computed | A strategy failure after model work is the `failed` outcome with its diagnostics, not an error: the caller writes the compaction fact with those diagnostics. @@ -100,7 +101,7 @@ A strategy failure after model work is the `failed` outcome with its diagnostics ## Verification -- A threshold compaction over the retention limit completes, skips or fails with diagnostics; a compaction with no legal cut is `invalid` and sends no model call. +- A threshold compaction over the retention limit completes, skips or fails with diagnostics; a compaction with no legal cut is `skipped { reason: "nothing_to_compact" }` and sends no model call. - `describe` equals the target rule plus the empty wrapper's count; a caller that reserved that size keeps it. - A cancel during the model call answers nothing and leaves the history unchanged. - A re-planned compaction sums both passes' model calls and usage. @@ -135,6 +136,16 @@ A strategy failure after model work is the `failed` outcome with its diagnostics None. +## Supersedes + +This contract replaces the `compactionStrategyHost` object; the delivery in #2025 carries the migration. + +- `docs/design/contracts/runtime-owner-operations.md`: the `Loop and ContextPreparation → CompactionStrategyHost` row of "Model preparation, history and tools". +- `docs/design/service-faces.md`: §3.5's `compactionStrategyHost` row. +- `docs/design/plugins/ContextCompaction.md` §4.2's ports table: `CompactionStrategyHost` becomes this owner's two operations, and `CompactionInput.model` leaves the input. + +Rule D: no client wire protocol or user-visible behavior changes; `completed`, `skipped` and `failed` keep their fact shapes and the summary's model-visible text is unchanged. + ## Binding appendix ```rust @@ -235,4 +246,4 @@ impl SummaryStrategy { } ``` -`cancelled` is the binding's cancellation argument, not a request field. `AgentEvent` is not part of the request: the caller writes the compaction facts. +`cancelled` is the binding's cancellation argument, not a request field. `AgentEvent` is not part of the request: the caller writes the compaction facts. `CompactionCut`, `CompactionCheckpoint` and `StrategyDiagnostics` gain `Serialize`/`Deserialize` for this face; their fields do not change. Errors cross as `{code, message}`, `code` from the variant name; a strategy failure is the `failed` outcome, not an error. diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..c6f4423acb 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -94,10 +94,10 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `sessionFiles` | `sessionFiles.put/import/read/register/owns/owned_paths` | 形状按 [Session files](appserver/session-files.md) §9.1,`SessionFiles` 是进程内绑定。 | | `commandRules` | `commandRules.read` | Session 命令规则读取,按 [命令规则](appserver/permission-command-rules.md#41-language-neutral-adr-002-d5) §4.1。 | | `managedSearch` | `managedSearch.search` | 凭据由实现持有,见 §4.6。 | -| `agentConfig` | `agentConfig.get()` | 形状见 §4.8。 | +| ~~`agentConfig`~~ | 无 | 面移出(#2093):Agent 的配置不归 Session,值仍由装配提供 | | `sessionLanguage` | `sessionLanguage.get()` | 形状见 §4.8。 | -| `skillsConfig` | `skillsConfig.get()` | 形状见 §4.8。 | -| `collaborationConfig` | `collaborationConfig.get()` | 形状见 §4.8。 | +| ~~`skillsConfig`~~ | 无 | 面移出(#2093):工厂文本只在自己的 part 内读 | +| ~~`collaborationConfig`~~ | 无 | 面移出(#2093):工厂文本只在自己的 part 内读 | | `worktreeAssociations` | `store.associateWorktree` | 形状见 §4.8。 | | `toolSourcesView` | `toolSourcesView.get/observe` | 同一 ToolRegistry owner 的独立只读观察面;贡献注册仍由 `toolRegistry` 负责,见 [工具贡献 §7.5](../architecture/rust-agent/tool-contributions.md#75-服务接口)。 | @@ -180,11 +180,11 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `configurationPublisher` | branch | ContextPreparation | hot-path | 待迁移;按 #1292 定义操作面 | | `configureControl` | branch | Prompt | hot-path | 待迁移;按 #1292 定义操作面 | | `fileReads` | branch | FileReads | hot-path | 待迁移;按 #1292 定义操作面 | -| `historyRenderer` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | -| `contextModelHost` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | -| `prepareModelHost` | session | PrepareModelHost | hot-path | 待迁移;按 #1292 定义操作面 | -| `prepareContextHost` | session | SessionScope | hot-path | 待迁移;按 #1292 定义操作面 | -| `compactionStrategyHost` | session | ProductSummaryStrategy | hot-path | 待迁移;按 #1292 定义操作面 | +| ~~`historyRenderer`~~ | session | SessionScope | hot-path | 由 `contextProjection` 取代([Context projection](plugins/ContextProjection.md),#2093) | +| ~~`contextModelHost`~~ | session | SessionScope | hot-path | 由 `contextFacts` 取代([Context facts](plugins/ContextFacts.md),#2093) | +| ~~`prepareModelHost`~~ | session | PrepareModelHost | hot-path | 由 `requestSettings` 值取代([Request settings](plugins/RequestSettings.md),#2093) | +| ~~`prepareContextHost`~~ | session | SessionScope | hot-path | 无目标,移出目录(#2093) | +| ~~`compactionStrategyHost`~~ | session | ProductSummaryStrategy | hot-path | 由 `summaryStrategy` 取代([Summary strategy](plugins/SummaryStrategy.md),#2093) | ### 3.6 入口、凭据与宿主资源 @@ -203,7 +203,7 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow | `hooksService` | process | HooksSettings | host-resource | | `providerService` | process | Provider | 当前为 secret,迁移后通过数据操作使用凭据 | | `providerConnectionResolver` | process | Provider | host-resource | -| `timelineFactory` | session | SessionScope | control | +| ~~`timelineFactory`~~ | session | SessionScope | control | 由 `sessionScope.openBranch` 取代([SessionScope](plugins/SessionScope.md),#2093) | ## 4. 批次契约(#1292) From 603849133fe8e021196b264f12315651ed7ff3ee Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 11:23:27 +0800 Subject: [PATCH 07/19] docs(design): apply the round-four review - openBranch is the one Rust-only method, marked service(skip), with the handover design as its reason. - The Session timelineStore spelling is fixed in service-faces and resource-faces; plugin-contract's scope and R2 rows name sessionScope. - Verification states what changes; unmount answers unknown. - Error enums derive serde with the code tag and struct message variants. - Count takes the request; contributions stay facts; imports and serde derives named; line access cites ADR 027 and #2127. Refs #2025 --- .../contracts/runtime-owner-operations.md | 2 +- docs/design/plugin-contract.md | 13 ++-- docs/design/plugins/ContextFacts.md | 39 +++++------ docs/design/plugins/ContextProjection.md | 23 ++++--- docs/design/plugins/FileAccessFacts.md | 27 ++++---- docs/design/plugins/RequestSettings.md | 10 +-- docs/design/plugins/SessionScope.md | 66 +++++++++++-------- docs/design/plugins/SummaryStrategy.md | 28 ++++---- docs/design/resource-faces.md | 2 +- docs/design/service-faces.md | 2 +- 10 files changed, 114 insertions(+), 98 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 344aab18d4..02a2ffa385 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -24,7 +24,7 @@ | Context RPC → target branch | `agentLoop.compact` and `contextUsage.read`. | | Goal and Shell admission → timelineTree | `directory({id})` returns the matching directory entry or the unknown-branch error using a single-branch lookup. Goal reads ended history through `query`; writes retain the ended/unknown errors. | | InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | -| PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.query` at the selected head for evidence. | +| PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.read` at the selected head for evidence. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | | Fault producers and Session observers → `sessionScope` | `reportFault(fault) → void`, `failure() → SessionFault or none`, `observeFault(listener) → id`, `release({leaseId}) → boolean`. The listener receives the current failure (none included) and later reports; the calling row's unload releases the observation. The first fault wins until a storage failure supersedes it ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | | Check providers and input admission → SubmitChecks | `register(name, check) → void`; `check({entry, branchId, user?, mode}, cancelled) → proceed{blocks, warnings} or block{message}`. Run in name order through the first block. Interrupted checks write nothing. | diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 990cd2bd4b..d71e4284cd 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -59,7 +59,7 @@ process (root) process parts: storage, catalogs, connections, Ag | --- | --- | --- | --- | | Process (root) | Host start | Host shutdown | — (process parts provide their own) | | Agent (`agent`) | Agents creates an Agent | Agent close, host shutdown | Host-internal | -| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionIdentity`, `sessionLifecycle`, `treeCommands` | +| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionScope`, `treeCommands` | | Branch (`branch`) | TimelineTree creates a branch | The branch ends, or its Session closes | `timeline`, `dispatcher`, `branchLifecycle`, `timelineIdentity` | Visibility follows the tree, as in [principles §2](../architecture/rust-agent/principles.md): @@ -359,12 +359,11 @@ design is merged. R4–R7 concern how Dim uses rutis and are in The row learns its Session id from the C4 setup rather than from a service. - **Existing mechanisms considered:** C4's per-row setup carries the id but not the phases. `branchLifecycle` already exists for branch rows. -- **Needed:** `sessionLifecycle` (`activated`, `closing`, `hold`) and `sessionIdentity` - (`{sessionId, restored}`) as catalog services in `session`, with serde shapes, next to the existing - `branchLifecycle` and `timelineIdentity` in `branch`. `hold` returns a handle released by a call or - by the row's unload; in the serde form the handle is a hold id, which `release(id)` ends, and the - hold is a cleanup of the calling row. `sessionConfig` exposes the creation-time configuration the C4 - setup carried, so the setup goes. The process scope gets none: process parts follow the host's +- **Needed:** `sessionScope` (`activated`, `closing`, `hold`, `release`, the fault operations, and + the `config` and `identity` reads) as one catalog service in `session`, with serde shapes, next to + `branchLifecycle` and `timelineIdentity` in `branch`. `hold` answers a lease id bound to the + calling row, which `release` ends early and the row's unload settles. `config` exposes the + creation-time configuration the C4 setup carried, so the setup goes ([SessionScope](plugins/SessionScope.md)). The process scope gets none: process parts follow the host's start and shutdown through the rutis lifecycle. - **Effect:** none on the Timeline. It exposes the existing phases. - **Owner:** Dim runtime (SessionScope) and App Server (catalog). Delivered in phase 4 diff --git a/docs/design/plugins/ContextFacts.md b/docs/design/plugins/ContextFacts.md index c0e1311654..4af971527c 100644 --- a/docs/design/plugins/ContextFacts.md +++ b/docs/design/plugins/ContextFacts.md @@ -29,25 +29,25 @@ Callers keep: ```rust // ContextPreparation: one request's budget. -let facts = facts.describe(DescribeRequest { model: selection.clone() }).await?; -let counted = facts.count(CountRequest { model: selection.clone(), request: request.clone() }).await?; -let over = counted.tokens > facts.threshold_tokens; +let limits = owner.describe(DescribeRequest { model: selection.clone() }).await?; +let counted = owner.count(CountRequest { request: request.clone() }).await?; +let over = counted.tokens > limits.threshold_tokens; ``` ```rust // ContextUsage: the contributions of one request, when the model has an additive counter. -let described = facts.describe(DescribeRequest { model: selection.clone() }).await?; +let described = owner.describe(DescribeRequest { model: selection.clone() }).await?; let Some(algorithm) = described.algorithm else { return Err(UsageError::NotCountable); // the caller keeps complete-request counts only }; -let parts = facts.contributions(ContributionsRequest { +let parts = owner.contributions(ContributionsRequest { model: selection.clone(), fixed: Some(Fixed { system, tools }), messages, }).await?; // Contributions are the counter's facts; the caller estimates them, now and after a restart. let total = match parts.fixed { - Some(fixed) => facts.estimate(EstimateRequest { + Some(fixed) => owner.estimate(EstimateRequest { model: selection.clone(), algorithm: parts.algorithm.clone(), contribution: fixed, @@ -56,7 +56,7 @@ let total = match parts.fixed { } + { let mut sum = 0.0; for message in parts.messages { - sum += facts.estimate(EstimateRequest { + sum += owner.estimate(EstimateRequest { model: selection.clone(), algorithm: parts.algorithm.clone(), contribution: message, @@ -155,8 +155,8 @@ Rule D: no client wire protocol or user-visible behavior changes; the statistics ## Binding appendix ```rust -use dim_agent_runtime::{ModelSelection, PublicService}; -use dim_agent_types::{Message, ModelRequest, SystemPrompt, ToolDefinition}; +use dim_agent_runtime::PublicService; +use dim_agent_types::{Message, ModelRequest, ModelSelection, SystemPrompt, ToolDefinition}; #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -225,16 +225,17 @@ pub struct EstimateRequest { pub contribution: Contribution, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum ContextFactsError { - #[error("{0}")] - NotAdopted(String), - #[error("{0}")] - Unsupported(String), - #[error("{0}")] - AlgorithmMismatch(String), - #[error("{0}")] - Closed(String), + #[error("{message}")] + NotAdopted { message: String }, + #[error("{message}")] + Unsupported { message: String }, + #[error("{message}")] + AlgorithmMismatch { message: String }, + #[error("{message}")] + Closed { message: String }, } impl PublicService for ContextFacts {} @@ -251,4 +252,4 @@ impl ContextFacts { } ``` -`ContributionsReply.fixed` and `.messages` are the counter's facts, aligned with the request's messages; `estimate` turns one into tokens. `Contribution` stays the serialized-bytes and image facts the counter works from. `ContributionsReply.fixed` and `.messages` are the counter's facts, aligned with the request's messages; `estimate` turns one into tokens. Errors cross as `{code, message}`, `code` from the variant name. +`ContributionsReply.fixed` and `.messages` are the counter's facts, aligned with the request's messages; `estimate` turns one into tokens. `Contribution` stays the serialized-bytes and image facts the counter works from. Errors derive `serde` with `#[serde(tag = "code", rename_all = "snake_case")]`, so the wire code is the variant name. diff --git a/docs/design/plugins/ContextProjection.md b/docs/design/plugins/ContextProjection.md index 7706ed2ddb..107f8c6428 100644 --- a/docs/design/plugins/ContextProjection.md +++ b/docs/design/plugins/ContextProjection.md @@ -143,14 +143,16 @@ This contract replaces the `historyRenderer` value; the delivery in #2025 carrie - `docs/design/contracts/runtime-owner-operations.md`: the `Loop and ContextPreparation → HistoryRenderer` row of "Model preparation, history and tools". - `docs/design/service-faces.md`: §3.5's `historyRenderer` row. +- `docs/design/plugins/ContextCompaction.md` §4.2 and the sections that name `HistoryRenderer`: the projection is this owner's, and the history renderer's name leaves the catalog. Rule D: no client wire protocol or user-visible behavior changes; `StreamedContext` keeps its fields and the model-visible text is unchanged. ## Binding appendix ```rust +use dim_agent_capabilities::history::HistoryEntry; use dim_agent_runtime::{ContextHistory, PublicService}; -use dim_agent_types::{AgentEvent, HistoryEntry, ProjectionCheckpoint, RecoverySnapshot, TimelinePosition}; +use dim_agent_types::{AgentEvent, ProjectionCheckpoint, RecoverySnapshot, TimelinePosition}; #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -227,16 +229,17 @@ pub struct SnapshotFromCheckpointRequest { pub anchor: AgentEvent, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum ProjectionError { - #[error("{0}")] - FutureSequence(String), - #[error("{0}")] - Invalid(String), - #[error("{0}")] - Storage(String), - #[error("the projection owner is unloading")] - Closed, + #[error("{message}")] + FutureSequence { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + Storage { message: String }, + #[error("{message}")] + Closed { message: String }, } impl PublicService for ContextProjection {} diff --git a/docs/design/plugins/FileAccessFacts.md b/docs/design/plugins/FileAccessFacts.md index c29733decc..ef926f5c02 100644 --- a/docs/design/plugins/FileAccessFacts.md +++ b/docs/design/plugins/FileAccessFacts.md @@ -47,6 +47,7 @@ let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; - `P:sessionFiles` — whether the Session owns the target file. - `S:sessionGrants` — the Session's file grants, read by `check` only. - `P:worktrees` — managed worktree roots that extend the workspace. +- `P:hostPlatform` — the platform roots the `system` fact compares against. ### Operations @@ -55,7 +56,7 @@ let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; | `check` | Resolve a call's target and answer the facts under the branch's access preset | `{access, mode, path}` | `{target, workspace, system, owned, grant, discoveryError?}` | The caller drops the call; the reads stop | `invalid`, `unavailable`, `cancelled`, `closed` | | `workspaceRoots` | The workspace and managed worktree roots a command may use | `{cwd}` | `{roots}` | The caller drops the call | `invalid`, `unavailable`, `cancelled`, `closed` | -`access` is the branch's access preset (`dim_agent_types::FileAccess`: `read-only`, `workspace-read-write`, `unrestricted`); `mode` is the grant mode the call asks for (`dim_agent_types::GrantMode`: `read`, `write`); `path` is the path the call named. `target` is the resolved path, and it is what the caller passes to the file operation. A write grant is inert under `read-only` and active under `workspace-read-write` or `unrestricted`. +`access` is the branch's access preset (`dim_agent_types::FileAccess`: `read-only`, `workspace-read-write`, `unrestricted`); `mode` is the grant mode the call asks for (`dim_agent_types::grant::GrantMode`: `read`, `write`); `path` is the path the call named. `target` is the resolved path, and it is what the caller passes to the file operation. A write grant is inert under `read-only` and active under `workspace-read-write`; `unrestricted` does not widen grants because it already allows every write. ### Errors @@ -132,9 +133,8 @@ Rule D: no client wire protocol or user-visible behavior changes; the change is ```rust use dim_agent_capabilities::host::CancelledFn; use dim_agent_runtime::PublicService; -use dim_agent_types::{FileAccess, GrantMode}; - -use dim_agent_types::{FileAccess, GrantMode}; +use dim_agent_types::grant::GrantMode; +use dim_agent_types::FileAccess; #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -168,16 +168,17 @@ pub struct Roots { pub roots: Vec, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum FactsError { - #[error("{0}")] - Invalid(String), - #[error("{0}")] - Unavailable(String), - #[error("the call was cancelled")] - Cancelled, - #[error("the facts owner is unloading")] - Closed, + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + Unavailable { message: String }, + #[error("{message}")] + Cancelled { message: String }, + #[error("{message}")] + Closed { message: String }, } impl PublicService for FileAccessFacts {} diff --git a/docs/design/plugins/RequestSettings.md b/docs/design/plugins/RequestSettings.md index cceea3f28c..ebaf1aa4c0 100644 --- a/docs/design/plugins/RequestSettings.md +++ b/docs/design/plugins/RequestSettings.md @@ -39,7 +39,7 @@ let settings = ModelSettings { metadata: defaults.metadata.map(|mut metadata| { metadata.session_id = Some(session_id); metadata.turn_id = Some(turn_id); - metadata.extensions.insert("requestId".into(), request_id); // per request, written by Loop + metadata.extensions.insert("requestId".into(), request_id.into()); // per request, written by Loop metadata }), }; @@ -116,8 +116,10 @@ Rule D: no client wire protocol or user-visible behavior changes; the aimux requ ## Binding appendix ```rust -use dim_agent_runtime::{ModelId, ModelSelection, PublicService}; -use dim_agent_types::{ModelCapabilitySnapshot, ModelConfig, RequestMetadata, SystemPrompt}; +use dim_agent_runtime::PublicService; +use dim_agent_types::{ + ModelCapabilitySnapshot, ModelConfig, ModelSelection, RequestMetadata, SystemPrompt, +}; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -142,4 +144,4 @@ impl RequestSettings { } ``` -`ModelSelection`, `ModelId` and the reply's members are the crate's existing data; `settings` answers the value itself, as `agentConfig.get` did before this owner existed. The reply's members are the crate's existing data. Errors cross as `{code, message}`; this owner has none. +`ModelSelection` and the reply's members are `dim_agent_types` data; `settings` answers the value itself. Errors: this owner has none. diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index 48423dfa8d..f9eac846d4 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -36,7 +36,7 @@ Callers keep as business: | Record a fault: Prompt on a prompt or recovery failure | No | `reportFault` | | Read the current fault | No | `failure` | | Subscribe to later faults: a part in another language | No: a subscription is the owner's, not a poll loop in the caller | `observeFault` | -| Act on one line's owners by line id: any branch-group data face — `inputQueue.submit` or `withdraw`, `contextUsage.read`, `prompt.adoptedConfiguration`, `approval.pending` — except registration points and lifecycle services | No: a part cannot address a line's instance itself, and a forwarding operation here would be the facade §7 forbids | Not this owner: the mechanism resolves the branch-group service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation | +| Act on one line's owners by line id: any branch-group data face — `inputQueue.submit` or `withdraw`, `contextUsage.read`, `prompt.adoptedConfiguration`, `approval.pending` — except registration points and lifecycle services ([ADR 027 D1 and D3](https://github.com/arcships/dim/pull/2029)) | No: a part cannot address a line's instance itself, and a forwarding operation here would be the facade §7 forbids | Not this owner: the runtime routes by line id ([#2127](https://github.com/arcships/dim/issues/2127)), and the caller calls that owner's typed operation | | Mount and retire Session content: Skills' content instances, MCP's connections | No: the Session's anchor and the group admission are the owner's knowledge | `mount`, `unmount` | | Open a branch's runtime context: TimelineTree | No: only the runtime constructs a branch's context, in its own subtree | `openBranch` | @@ -47,7 +47,7 @@ An operation exists only where the row says No. Skills replaces content after publication, and stops when the Session closes: ```rust -if !scope.activated().await?.active { +if !scope.activated().await.active { return Ok(()); // the Session never published } let mounted = scope @@ -71,8 +71,10 @@ the part releases it when the work ends only so an idle release may happen soone ```rust // ShellInput: the run's hold lives in the part's registry, not in the call. -scope.phase()?; // closing or closed -> RpcError::closed() -let lease = scope.hold().await?.lease_id; +if !matches!(scope.phase().phase, Phase::Loading | Phase::Active) { + return Err(RpcError::closed()); +} +let lease = scope.hold(ctx).await?.lease_id; self.runs.lock().unwrap().insert(run_id, lease); ``` @@ -88,8 +90,9 @@ const { leaseId } = await sessionScope.observeFault(async fault => { TimelineTree opens a branch after admitting it: ```rust +// `openBranch` is the one Rust-only method; TimelineTree is the only caller. let branch = scope - .open_branch(OpenBranchRequest { branch_id: id, ancestors }, cancelled) + .open_branch(ctx, OpenBranchRequest { branch_id: id, ancestors }, cancelled) .await?; // The tree owns `branch` from here: it hands it to the branch's parts and closes it // before the Session scope unloads. @@ -120,7 +123,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; | `failure` | The fault in force, if any | `{}` | `{fault?}` | None | None | | `mount` | Create a Session-owned content instance from a definition | `{group, definitionId, instanceData}` | `{instanceId}` | The caller drops the call; an instance it no longer waits for is shut down before the reply | `invalid`, `not_ready`, `cleanup`, `closed` | | `unmount` | Retire a content instance this Session owns | `{instanceId}` | `{}` | None; the owner completes the release | `unknown` when no live instance has the id; `cleanup`; `closed` | -| `openBranch` | Construct a branch's runtime context for the branch tree | `{branchId, ancestors}` | the branch's runtime context (see Exceptions) | The caller drops the call; a construction the caller abandoned is shut down before the branch becomes visible | `closed`, `build` | +| `openBranch` (Rust-only, `#[rutis::service(skip)]`) | Construct a branch's runtime context for the branch tree | `{branchId, ancestors}` | the branch's runtime context (see Exceptions) | The caller drops the call; a construction the caller abandoned is shut down before the branch becomes visible | `closed`, `build` | `listener` and `work` are callbacks by reference: they run outside the owner's locks and outside the Timeline's commit lock. `work` returns nothing; its failure and its cleanup stay with the caller. A lease id is an owner-issued token bound to the calling row; it carries no authority, the owner settles it at the row's unload, and a caller never has to free it on an error path. @@ -168,6 +171,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; - The Session-scoped `timelineStore` binding is assembly infrastructure: the store owns the engine and the operations, SessionScope installs the binding and states the spelling, and a process caller uses `store` (§2018's requirement). - `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. - The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. +- A fault listener that returns an error stops receiving: the owner drops the registration and the lease, and the fault record is unchanged. - `identity` carries no version: the id and the restored flag are fixed at creation. - A lease is a value, not a handle: it names nothing the caller can use except in `release`, and the owner releases every lease at the row's unload, so a caller that loses the id leaks nothing. `release` only lets an idle release happen sooner. - Content instance ids are the Session's, not the caller's: the Session's close shuts down every instance it mounted, so a part that never unmounts leaves obsolete content published until the Session ends, without breaking the owner. @@ -177,10 +181,10 @@ The Session store constructs the Timeline engine and its Session-scope binding; - `hold` answers `closed` once an idle release is decided; a lease taken before it keeps the Session loaded until released, and never refuses a close; a lost id is settled at the row's unload; another row's id is `invalid` on release. - `observeFault` delivers the fault in force and later reports; `release` answers `released: true` then `false`; another row's id is `invalid`; the row's unload stops delivery. - `reportFault` keeps the first fault; a storage fault after a non-storage one wins; a non-storage fault after a storage one loses. -- `mount` answers `invalid` for a group outside the Session's subtree, `not_ready` for a definition whose row failed (and leaves no instance), and shuts down an abandoned mount; `unmount` answers `cleanup` when the shutdown fails and `invalid` for another Session's id. +- `mount` answers `invalid` for a group outside the Session's subtree, `not_ready` for a definition whose row failed (and leaves no instance), and shuts down an abandoned mount; `unmount` answers `cleanup` when the shutdown fails and `unknown` for an id this Session never issued. - `activated` answers false when the Session closes before publishing; `closing` returns when the close starts. - `openBranch` answers `closed` during the Session's close; a failed construction settles the branch scope before the reply; the tree closes every branch before the Session scope unloads. -- `config`, `identity` and `phase` do not change while the Session runs. +- `identity` is fixed; `phase` only moves forward through the four phases; `config` is fixed except `config.language`, which the native store updates in place. ## Rule check @@ -200,8 +204,8 @@ The Session store constructs the Timeline engine and its Session-scope binding; | §4 rule 9 | No Timeline fact: the phase and the fault record are runtime state, read live and never persisted as events. | | §7 values, ids and objects | The record, identity, phase and fault are values; a lease id and a content instance id are the owner's, bound to the calling row and settled at its unload; the one object is `openBranch`, with the handover design above. | | §7 no proxy lookup | The owner returns only its own state; the Agent's configuration and the Skills and Collaboration factory texts leave this face. | -| §7 one interface | One name, `sessionScope`, on the owner type; the Rust binding and the wire call the same methods; no facade or wrapper type. | -| §7 cross-language | Every operation is data, a callback by reference or an id; no method exists only for Rust. | +| §7 one interface | One name, `sessionScope`, on the owner type; the wire calls every method except `openBranch`, which is marked `#[rutis::service(skip)]`; no facade or wrapper type. | +| §7 cross-language | Every operation is data, a callback by reference or an id, except `openBranch`: it hands TimelineTree the branch's runtime context, which has no serde form, and the tree is a Rust part. That is the only Rust-only method, and it is marked skip. | | §7 one change | The implementation task deletes the old names and migrates every caller in one change. | | ADR 002 D1 | Session scope: the record, phase, leases, faults and mounts live and die with the Session. | | ADR 002 D2 | No wiring plugin: the operations are on the owner type; no adapter exists beside it. | @@ -211,7 +215,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; ## Requirements raised to mechanism owners -- [#2024](https://github.com/arcships/dim/issues/2024) and the runtime: resolve a branch group's service by line id (`line_owner::(line)?`), so a Session part calls that owner's typed operation directly. No forwarding operation, operation-name routing or reply envelope is added to this owner; TimelineTree supplies the line id and the line's state, never the address. +- [#2127](https://github.com/arcships/dim/issues/2127), owned by the dim runtime, and [#2024](https://github.com/arcships/dim/issues/2024): route by line id so a Session part resolves a branch-group data face with `line_owner::(line)?` and calls that owner's typed operation, per [ADR 027 D1–D3](https://github.com/arcships/dim/pull/2029). The instance key never leaves the instance, the caller keeps no resolution between calls, and this owner adds no forwarding operation, operation-name routing or reply envelope. TimelineTree supplies the line id and the line's state, never the address. - The runtime's `Session` facade stops forwarding line operations: `end_branch`, `set_default_branch`, `branch`, `branches`, `directory`, `default_and_directory`, `ended_head`, `sequence`, `batch_end` and `query` are TimelineTree's, and the Session access surface must not restate them. - [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns the Timeline engine and constructs the Session-scope binding; SessionScope installs it. The Session face publishes the per-line reads and the completion subscriptions; `query` and `sessionConfig` stay on `store`; `createSession`, `releaseSession`, `rollbackSession` and `append` are not on the Session face. @@ -219,10 +223,10 @@ The Session store constructs the Timeline engine and its Session-scope binding; This contract replaces the Session-scope paragraphs and rows that state these names; the delivery in #2025 carries the migration. -- `docs/design/contracts/runtime-owner-operations.md`: the `sessionLifecycle` rows of "Retained operations" and "New rutis APIs on existing owners", the `sessionLoader` row, and the "Calls from a Session to a selected branch" section — a branch-group service is resolved by line id (`line_owner::(line)`), and `timelineTree.call` is removed rather than kept. -- `docs/design/contracts/service-faces.md`: §3.6's `timelineFactory` row and §3.2's `agentConfig`, `skillsConfig` and `collaborationConfig` rows; the Session-scoped `timelineStore` spelling in §3.4 is stated by this contract, with the engine's operations left to #2018. -- `docs/design/plugin-contract.md`: the `sessionIdentity`, `sessionLifecycle`, `sessionConfig` and `agentConfig` rows of the named-services table. -- `docs/design/contracts/resource-faces.md` §5: the Session-scoped `timelineStore` names this contract spells; the engine and its process face remain #2018's. +- `docs/design/contracts/runtime-owner-operations.md`: the `sessionLifecycle` rows of "Retained operations" and "New rutis APIs on existing owners", the `sessionLoader` row, and the "Calls from a Session to a selected branch" section — a branch-group data face is resolved by line id, and `timelineTree.call` is removed rather than kept. `line_owner::(line)` reaches any branch-group data face except registration points and lifecycle services ([ADR 027 D1 and D3](https://github.com/arcships/dim/pull/2029); the routing mechanism is [#2127](https://github.com/arcships/dim/issues/2127)). +- `docs/design/service-faces.md`: §3.6's `timelineFactory` row, §3.2's `agentConfig`, `skillsConfig` and `collaborationConfig` rows, and §3.4's `timelineStore` row, which now spells the Session face and leaves `query` and `sessionConfig` on the process face `store`. +- `docs/design/resource-faces.md` §5: the Timeline family row, updated to the same spelling; the engine and its process face remain #2018's. +- `docs/design/plugin-contract.md`: the `sessionIdentity`, `sessionLifecycle`, `sessionConfig` and `agentConfig` rows of the named-services table, the `session` row of the scope table, and R2's needed names. Rule D: no client wire protocol or user-visible behavior changes; every change here is plugin-facing. @@ -315,23 +319,24 @@ pub struct OpenBranchRequest { pub type FaultListener = Arc) -> rutis::host::BoxFuture<'static, Result<(), rutis::Error>> + Send + Sync>; -#[derive(Debug, thiserror::Error)] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum SessionScopeError { - #[error("{0}")] - Closed(String), - #[error("{0}")] - Invalid(String), - #[error("{0}")] - NotReady(String), - #[error("{0}")] - Cleanup(String), - #[error("{cause}")] + #[error("{message}")] + Closed { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + NotReady { message: String }, + #[error("{message}")] + Cleanup { message: String }, + #[error("{message}")] Build { - cause: String, + message: String, cleanup: Option, }, - #[error("{0}")] - Unknown(String), + #[error("{message}")] + Unknown { message: String }, } impl PublicService for SessionScope {} @@ -358,6 +363,9 @@ impl SessionScope { ) -> Result { /* ... */ } pub async fn mount(&self, definition: MountDefinition) -> Result { /* ... */ } pub async fn unmount(&self, request: UnmountRequest) -> Result<(), SessionScopeError> { /* ... */ } + /// The one Rust-only method: the branch's runtime context has no serde form, + /// and TimelineTree, which holds and closes it, is a Rust part. + #[rutis::service(skip)] pub async fn open_branch( &self, caller: &Ctx, @@ -367,4 +375,4 @@ impl SessionScope { } ``` -`caller: &Ctx` and `cancelled: CancelledFn` are the binding's caller row and cancellation argument; the dispatch fills them and no caller sends or names a row. `LeaseId`, `InstanceId` and the ancestor pairs cross as strings and numbers. `cancelled` and `caller: &Ctx` are the binding's cancellation and caller-row arguments, not request fields; the dispatch fills them. Errors cross as `{code, message}`: `code` is the variant name in snake_case, `message` is `Display`, and a variant's own members (for example `build`'s `cleanup`) travel beside them. +`caller: &Ctx` and `cancelled: CancelledFn` are the binding's caller-row and cancellation arguments, not request fields; the dispatch fills them and no caller sends or names a row. `LeaseId`, `InstanceId` and the ancestor pairs cross as strings and numbers. Errors derive `serde` with `#[serde(tag = "code", rename_all = "snake_case")]`, so the wire `code` is the variant name; `build` also carries `cleanup`. `openBranch` has no serde reply and is marked skip. diff --git a/docs/design/plugins/SummaryStrategy.md b/docs/design/plugins/SummaryStrategy.md index 2042444faa..d2c79f0835 100644 --- a/docs/design/plugins/SummaryStrategy.md +++ b/docs/design/plugins/SummaryStrategy.md @@ -149,11 +149,12 @@ Rule D: no client wire protocol or user-visible behavior changes; `completed`, ` ## Binding appendix ```rust -use dim_agent_capabilities::host::StrategyDiagnostics; -use dim_agent_runtime::{ModelSelection, PublicService}; +use dim_agent_capabilities::history::HistoryEntry; +use dim_agent_capabilities::host::{CompactionCut, StrategyDiagnostics}; +use dim_agent_runtime::PublicService; use dim_agent_types::{ - AgentEvent, BaselineSource, CompactionCut, CompactionTrigger, HistoryEntry, Message, - ModelRequest, ProviderOutputBudgetFacts, + BaselineSource, CompactionTrigger, Message, ModelRequest, ModelSelection, + ProviderOutputBudgetFacts, }; use std::sync::Arc; @@ -221,16 +222,17 @@ pub struct CompactionReply { pub outcome: StrategyOutcome, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum StrategyError { - #[error("the compaction was cancelled")] - Cancelled, - #[error("the strategy owner is unloading")] - Closed, - #[error("{0}")] - Invalid(String), - #[error("{0}")] - NotAdopted(String), + #[error("{message}")] + Cancelled { message: String }, + #[error("{message}")] + Closed { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + NotAdopted { message: String }, } impl PublicService for SummaryStrategy {} diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index e5dd257f13..bea6aa4f24 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -613,7 +613,7 @@ SessionTitle and FileAccess use the process repository operations in the [resour | Family | Operations | | --- | --- | -| Timeline (`timelineStore`) | `createSession`, `sessionConfig`, `releaseSession`, `rollbackSession`, `append` (sync), `head`, `branches`, `readPage`, `readSegments`, `query`, `trace`, `batchEnd`, `batchEndAt`, `saveSnapshot`, `latestSnapshot` | +| Timeline (`timelineStore`) | Session face: `head`, `branches`, `readPage`, `readSegments`, `trace`, `batchEnd`, `batchEndAt`, `saveSnapshot`, `latestSnapshot`; the process face `store` keeps `query` and `sessionConfig`; `createSession`, `releaseSession`, `rollbackSession` and `append` are the engine's own path ([SessionScope](plugins/SessionScope.md), #2093) | | Timeline completion (`timelineStore`) | `commits`, `closeCommits`; notifications `{subscriptionId, batchId, branchId, through, result}` | | Session rows (`store`) | The repository operations listed in §5.2 | | Worktree association (`store`) | `associateWorktree`; [service faces](service-faces.md) §4.8 | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index c6f4423acb..b0762934b1 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -126,7 +126,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 数据面 `execHost`:`start`/`wait`/`kill`/`settle`/`output`/`tail`/`removeOutputDirectory`/`shell`/`write`/`resize`/`info`/`confined`/`configured`([resource and store data faces](resource-faces.md) §3,#1295);`hostPlatform` 是提供方和它的 Rust binding | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | -| `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):`createSession`/`sessionConfig`/`releaseSession`/`rollbackSession`/`append`(同步受理)/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`TimelineStore` trait 是 binding(#1298) | +| `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):每行读取与完成通知 `head`/`branches`/`readPage`/`readSegments`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`/`commits`/`closeCommits`;`query` 与 `sessionConfig` 只在进程面 `store`(未加载的 Session 也能读),`createSession`/`releaseSession`/`rollbackSession`/`append` 不在 Session 面。引擎归 SessionStore,SessionScope 安装该绑定([SessionScope](plugins/SessionScope.md),#2093) | | `promptSourcesBranch` | 分支 prompt 装配 | 按 #1292 确认公共操作与装配内部职责。 | 这些行按当前对象形状分组。前四行的数据契约由 [resource and store data faces](resource-faces.md) 定义(#1295/#1297/#1298)。其余行按 #1292 逐批确定操作面。 From 4d03ffbce60882d141b0efa781681bc10b9c4f40 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 11:48:01 +0800 Subject: [PATCH 08/19] docs(design): carry the projection and compaction replies as wire types Entry, History, Cut, Diagnostics and CompactionCheckpoint are the faces' own serde forms; the owner maps HistoryEntry, ContextHistory, CompactionCut and StrategyDiagnostics in one place and the internal types stay unchanged. The binding appendix now compiles as written. Refs #2025 --- docs/design/plugins/ContextProjection.md | 44 +++++++++++++++++---- docs/design/plugins/SummaryStrategy.md | 50 +++++++++++++++++------- 2 files changed, 71 insertions(+), 23 deletions(-) diff --git a/docs/design/plugins/ContextProjection.md b/docs/design/plugins/ContextProjection.md index 107f8c6428..8c92ca41b3 100644 --- a/docs/design/plugins/ContextProjection.md +++ b/docs/design/plugins/ContextProjection.md @@ -150,9 +150,11 @@ Rule D: no client wire protocol or user-visible behavior changes; `StreamedConte ## Binding appendix ```rust -use dim_agent_capabilities::history::HistoryEntry; -use dim_agent_runtime::{ContextHistory, PublicService}; -use dim_agent_types::{AgentEvent, ProjectionCheckpoint, RecoverySnapshot, TimelinePosition}; +use dim_agent_runtime::PublicService; +use dim_agent_types::{ + AgentEvent, ContextBaselineEntry, Message, ProjectionCheckpoint, RecoverySnapshot, + TimelinePosition, +}; #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -164,7 +166,7 @@ pub struct RenderedStreamRequest { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct StreamedContext { - pub history: Vec, + pub history: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub configuration: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -181,6 +183,32 @@ pub struct StreamedContext { pub compaction_cut: Option, } +/// The wire form of one rendered entry. The owner maps `HistoryEntry` to it +/// (an `Arc` and an `Arc<[ContextBaselineEntry]>` become owned values); +/// the internal type is unchanged. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Entry { + pub id: String, + pub message: Message, + pub tool_context: bool, + pub baseline: Vec, + pub event_id: String, + pub position: TimelinePosition, +} + +/// The wire form of a folded context. The owner maps `ContextHistory` to it +/// (`Arc` becomes an owned event); the internal type is unchanged. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct History { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub checkpoint: Option, + pub ancestry: Vec, + pub events: Vec, + pub positions: Vec, +} + #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct RenderedContextRequest { @@ -190,14 +218,14 @@ pub struct RenderedContextRequest { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct RenderedContextReply { - pub context: ContextHistory, - pub history: Vec, + pub context: History, + pub history: Vec, } #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SnapshotRequest { - pub context: ContextHistory, + pub context: History, pub retain_from: String, pub anchor: AgentEvent, } @@ -266,4 +294,4 @@ impl ContextProjection { } ``` -`ContextHistory`, `HistoryEntry`, `ProjectionCheckpoint`, `RecoverySnapshot`, `AgentEvent` and `TimelinePosition` are the types those facts already use and gain `Serialize`/`Deserialize` for this face; their fields do not change. `renderedStream` carries no `ContextHistory`, so a streamed fold never holds the event list; `renderedContext` and the snapshot reads carry events or checkpoints because their callers need them. Errors cross as `{code, message}`, `code` from the variant name. +`Entry` and `History` are this face's wire forms of `dim_agent_capabilities::history::HistoryEntry` and `dim_agent_runtime::ContextHistory`; the owner maps them in one place, and the internal types stay unchanged. `ProjectionCheckpoint`, `RecoverySnapshot`, `AgentEvent`, `TimelinePosition`, `Message` and `ContextBaselineEntry` already derive serde, so `Entry` and `History` need no code change elsewhere. `renderedStream` carries no folded event list; `renderedContext` and the snapshot reads carry the events because their callers need them. Errors cross as `{code, message}`, `code` from the variant name. diff --git a/docs/design/plugins/SummaryStrategy.md b/docs/design/plugins/SummaryStrategy.md index d2c79f0835..ac377ae56e 100644 --- a/docs/design/plugins/SummaryStrategy.md +++ b/docs/design/plugins/SummaryStrategy.md @@ -149,14 +149,12 @@ Rule D: no client wire protocol or user-visible behavior changes; `completed`, ` ## Binding appendix ```rust -use dim_agent_capabilities::history::HistoryEntry; -use dim_agent_capabilities::host::{CompactionCut, StrategyDiagnostics}; +use crate::context_projection::Entry; use dim_agent_runtime::PublicService; use dim_agent_types::{ - BaselineSource, CompactionTrigger, Message, ModelRequest, ModelSelection, - ProviderOutputBudgetFacts, + BaselineSource, CompactionStrategyRecord, CompactionTrigger, ContextBaselineEntry, Message, + ModelRequest, ModelSelection, ProviderOutputBudgetFacts, Usage, }; -use std::sync::Arc; #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -171,12 +169,34 @@ pub struct Plan { pub replacement_size: f64, } +/// The wire form of one legal cut. The owner maps `CompactionCut` to it. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Cut { + pub retain_from: String, + pub entry: usize, + pub within_limit: bool, +} + +/// The wire form of the strategy's diagnostics. The owner maps +/// `StrategyDiagnostics` to it; the caller measures the duration itself. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Diagnostics { + pub model_call_count: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model_usage: Option, + pub record: CompactionStrategyRecord, +} + +/// The wire form of the previous compaction's checkpoint; owned vectors replace +/// the internal `Arc<[..]>` fields. #[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] +#[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CompactionCheckpoint { pub retain_from: String, - pub replacement: Arc<[Message]>, - pub context_baseline: Arc<[dim_agent_types::ContextBaselineEntry]>, + pub replacement: Vec, + pub context_baseline: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub replacement_parts: Option, } @@ -184,18 +204,18 @@ pub struct CompactionCheckpoint { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CompactionRequest { - pub history: Vec, + pub history: Vec, pub checkpoint: Option, pub request: ModelRequest, pub retain_limit: Option, - pub cuts: Vec, + pub cuts: Vec, pub trigger: CompactionTrigger, pub estimated_input_tokens: f64, pub baseline_source: BaselineSource, pub baseline_prompt_tokens: Option, pub delta_tokens: Option, pub provider_budget: Option, - pub prior: Option, + pub prior: Option, } #[derive(serde::Serialize, serde::Deserialize)] @@ -204,15 +224,15 @@ pub enum StrategyOutcome { Completed { retain_from: String, replacement: Vec, - diagnostics: StrategyDiagnostics, + diagnostics: Diagnostics, }, Skipped { reason: String, - diagnostics: StrategyDiagnostics, + diagnostics: Diagnostics, }, Failed { error: String, - diagnostics: StrategyDiagnostics, + diagnostics: Diagnostics, }, } @@ -248,4 +268,4 @@ impl SummaryStrategy { } ``` -`cancelled` is the binding's cancellation argument, not a request field. `AgentEvent` is not part of the request: the caller writes the compaction facts. `CompactionCut`, `CompactionCheckpoint` and `StrategyDiagnostics` gain `Serialize`/`Deserialize` for this face; their fields do not change. Errors cross as `{code, message}`, `code` from the variant name; a strategy failure is the `failed` outcome, not an error. +`cancelled` is the binding's cancellation argument, not a request field. `Entry` is the wire entry defined by [Context projection](ContextProjection.md); `Cut`, `Diagnostics` and `CompactionCheckpoint` are this face's wire forms of `CompactionCut`, `StrategyDiagnostics` and `CompactionCheckpoint`, mapped by the owner in one place. The internal types stay unchanged, and `Usage`, `CompactionStrategyRecord`, `Message`, `ContextBaselineEntry` and `ReplacementParts` already derive serde. A strategy failure is the `failed` outcome, not an error. From 1148f55ba7f4fbe8444ba79ff689754fbea9f9a4 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:10:28 +0800 Subject: [PATCH 09/19] docs(design): state the route answers a Session part receives --- docs/design/contracts/runtime-owner-operations.md | 5 ++++- docs/design/plugins/SessionScope.md | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 02a2ffa385..ace27dc130 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -37,7 +37,10 @@ line id: `line_owner::(line)?.op(..)` resolves the branch-group service at th runtime built for that line, and the caller calls that owner's typed operation. Any branch-group data face is reachable this way except registration points and lifecycle services; there is no generic operation-name dispatch and no `timelineTree.call`. A line that is not live answers -`ended` or `unknown`, and a closing Session answers `closed`. +`NoLine`; a Session that is closing answers `SessionClosing`. `NoLine` is final for that line: +the caller takes no hold and does not retry it. `SessionClosing` ends the Session part's work. A +Session part never receives `NoSession`: only a process caller does, and it takes a hold from Agents +before calling again. For a live main branch, Report captures its published head once at draft capture (`directory({id:"main"}).head`) and stores it as `conversationThrough` on that draft. Activity evidence and later opt-in diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index f9eac846d4..e03526fb3e 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -23,7 +23,7 @@ Callers keep as business: - What a fault means for their work; the failure record says only that the Session stopped. - Which definitions to mount and when to retire them. - Which branches exist, their ids and their ancestors: TimelineTree owns the branch directory (#2024). -- Acting on a line's owners: the mechanism resolves a branch-group service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation. Any branch-group data face is reachable this way except registration points and lifecycle services. SessionScope publishes no operation, request or reply for that path. +- Acting on a line's owners: the mechanism resolves a branch-group service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation. Any branch-group data face is reachable this way except registration points and lifecycle services. The route answers `SessionClosing` when this Session is closing, which ends the part's work, and `NoLine` when the line is not live, which is final for that line. `NoSession` never reaches a Session part. SessionScope publishes no operation, request or reply for that path. | Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | From faca8be50e90e24eb237d7a243ebde5553f85add Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:28:11 +0800 Subject: [PATCH 10/19] docs(design): cite the routing mechanism for the route answers --- docs/design/contracts/runtime-owner-operations.md | 2 +- docs/design/plugins/SessionScope.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index ace27dc130..a4e53da6d2 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -40,7 +40,7 @@ generic operation-name dispatch and no `timelineTree.call`. A line that is not l `NoLine`; a Session that is closing answers `SessionClosing`. `NoLine` is final for that line: the caller takes no hold and does not retry it. `SessionClosing` ends the Session part's work. A Session part never receives `NoSession`: only a process caller does, and it takes a hold from Agents -before calling again. +before calling again ([#2127](https://github.com/arcships/dim/issues/2127)). For a live main branch, Report captures its published head once at draft capture (`directory({id:"main"}).head`) and stores it as `conversationThrough` on that draft. Activity evidence and later opt-in diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index e03526fb3e..2bff72f891 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -23,7 +23,7 @@ Callers keep as business: - What a fault means for their work; the failure record says only that the Session stopped. - Which definitions to mount and when to retire them. - Which branches exist, their ids and their ancestors: TimelineTree owns the branch directory (#2024). -- Acting on a line's owners: the mechanism resolves a branch-group service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation. Any branch-group data face is reachable this way except registration points and lifecycle services. The route answers `SessionClosing` when this Session is closing, which ends the part's work, and `NoLine` when the line is not live, which is final for that line. `NoSession` never reaches a Session part. SessionScope publishes no operation, request or reply for that path. +- Acting on a line's owners: the mechanism resolves a branch-group service by line id (`line_owner::(line)`), and the caller calls that owner's typed operation. Any branch-group data face is reachable this way except registration points and lifecycle services. The route answers `SessionClosing` when this Session is closing, which ends the part's work, and `NoLine` when the line is not live, which is final for that line. `NoSession` never reaches a Session part ([#2127](https://github.com/arcships/dim/issues/2127)). SessionScope publishes no operation, request or reply for that path. | Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | From 86bb7dda7ef1acfcc270f76430eaa039bd4baebf Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:53:15 +0800 Subject: [PATCH 11/19] docs(design): apply the round-six decisions read is TimelineTree's and named in #2092; query and sessionConfig exist only on the store's process face. The catalog row marks openBranch as Rust-only and cites the shared lifecycle design that section 7 requires for an object. The projection's wire types are this contract's; the upper contract aligns its import. Refs #2025 --- docs/design/contracts/runtime-owner-operations.md | 6 +++--- docs/design/plugin-contract.md | 2 +- docs/design/plugins/ContextProjection.md | 4 +++- docs/design/plugins/RequestSettings.md | 2 +- docs/design/plugins/SessionScope.md | 10 +++++----- 5 files changed, 13 insertions(+), 11 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index a4e53da6d2..782d62fd55 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -4,7 +4,7 @@ | Caller → owner | Final API | | --- | --- | -| Branch management, input and history callers → `timelineTree` | `create/end/info/input/list/page/query` retain their existing signatures on the single Session tree face. Creation returns the branch ID. | +| Branch management, input and history callers → `timelineTree` | `create`, `end`, `set_default`, `directory`, `line` and `read` on the single Session tree face; creation returns the line id ([TimelineTree](https://github.com/arcships/dim/pull/2092), #2024). `query` is not the tree's: a stored Session's history is `store.query` on the process face ([SessionStore](https://github.com/arcships/dim/pull/2091), #2018). | | Language readers → PromptSources | `sessionLanguage.get`. | | Language updates → App Server | [`session.language.update`](session-access.md) accepts the existing language code or clear action. The owner serializes persistence, live-state replacement and Prompt adoption on main and loaded branches before replying. | | Prompt → PromptRegistry; guide and tool contributors → their registries | `initialPromptConfiguration.get`, `promptHost.load`, `guideEntries.register`, `toolRegistry.register`, `toolSourcesView.get/observe`. | @@ -20,9 +20,9 @@ | Skills content and MCP publication → Session mounts | `sessionScope.mount({group, definitionId, instanceData}) → {instanceId}`; `unmount({instanceId})`. The owner admits groups whose configured parent is the Session group, waits for the definition's rows and settles a rejected instance. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | | Goal → timelineTree | `inputs(id, inputs) → committed events`. One validated atomic batch for the Goal record and trigger. | | Branch-detail RPC → timelineTree | `display(id) → {entry,purpose?,cutMessages?,end?}`. | -| History RPC and line-read tools → timelineTree | `batchEnd(id, sequence) → void`, `pageEnd(id, after, limit, through) → sequence`, and `page` at the same cutoff. Preserve complete batches and the fixed head of ended lines. | +| History RPC and line-read tools → timelineTree | `read({line, through, …})` at one cutoff, with the complete batches and the fixed head of an ended line; the reply carries the events or the selected fields. | | Context RPC → target branch | `agentLoop.compact` and `contextUsage.read`. | -| Goal and Shell admission → timelineTree | `directory({id})` returns the matching directory entry or the unknown-branch error using a single-branch lookup. Goal reads ended history through `query`; writes retain the ended/unknown errors. | +| Goal and Shell admission → timelineTree | `directory({id})` returns the matching directory entry or the unknown-branch error using a single-branch lookup. Goal reads ended history through `read` at the line's fixed head; writes retain the ended/unknown errors. | | InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | | PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.read` at the selected head for evidence. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index d71e4284cd..639622e6e4 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -115,7 +115,7 @@ R4). This table says what each name Dim defines is for. | `eventHub` | process | EventHub | designed, not implemented | A producer declares a source and publishes an event; EventHub delivers it to the Sessions subscribed, through Agents' `sessions` ([EventHub](plugins/EventHub.md)) | | `collaborationMembers:` | process | the member provider | designed, not implemented | [ExternalAgent](plugins/ExternalAgent.md); registers with Collaboration when built (rutis usage R6) | | `treeCommands` | `session` | TimelineTree | yes | `input` by branch id, `create`, `list`, `info` | -| `sessionScope` | `session` | SessionScope | yes | `config`, `identity`, `phase`, `activated`, `closing`, `hold`, `release`, `reportFault`, `failure`, `observeFault`, `mount`, `unmount`, `openBranch` ([SessionScope](plugins/SessionScope.md), #2093) | +| `sessionScope` | `session` | SessionScope | yes, except `openBranch` | `config`, `identity`, `phase`, `activated`, `closing`, `hold`, `release`, `reportFault`, `failure`, `observeFault`, `mount`, `unmount`; `openBranch` is Rust-only (`#[rutis::service(skip)]`) because the branch's runtime context has a shared lifecycle but no serde form ([SessionScope](plugins/SessionScope.md), #2093) | | `timeline` | `branch` | BranchScope | yes, except `before` | `append`, the published sequence and the event query (§5.4); the query reaches other languages with its declaration | | `dispatcher` | `branch` | BranchScope | yes, `consume`, `listen` and reads; their Rust forms are the same `consume` and `subscribe`, which is Rust-only | Ordered consumption (§5.2) | | `branchLifecycle` | `branch` | BranchScope | yes | `activated`, `closing`. `registerOpening` registers work that branch opening waits for. | diff --git a/docs/design/plugins/ContextProjection.md b/docs/design/plugins/ContextProjection.md index 8c92ca41b3..9908fa0352 100644 --- a/docs/design/plugins/ContextProjection.md +++ b/docs/design/plugins/ContextProjection.md @@ -145,7 +145,9 @@ This contract replaces the `historyRenderer` value; the delivery in #2025 carrie - `docs/design/service-faces.md`: §3.5's `historyRenderer` row. - `docs/design/plugins/ContextCompaction.md` §4.2 and the sections that name `HistoryRenderer`: the projection is this owner's, and the history renderer's name leaves the catalog. -Rule D: no client wire protocol or user-visible behavior changes; `StreamedContext` keeps its fields and the model-visible text is unchanged. +Rule D: no client wire protocol or user-visible behavior changes; the streamed reply keeps the fields the callers use, and the model-visible text is unchanged. + +Left to the upper layer: #2102's `PrepareRequest.projection` still names the internal `history::StreamedContext`. The wire types are `contextProjection::StreamedContext`, `contextProjection::Entry` and `contextProjection::History` as defined here; #2102 aligns its import to these names when it rebases on this contract. ## Binding appendix diff --git a/docs/design/plugins/RequestSettings.md b/docs/design/plugins/RequestSettings.md index ebaf1aa4c0..98586c76cc 100644 --- a/docs/design/plugins/RequestSettings.md +++ b/docs/design/plugins/RequestSettings.md @@ -118,7 +118,7 @@ Rule D: no client wire protocol or user-visible behavior changes; the aimux requ ```rust use dim_agent_runtime::PublicService; use dim_agent_types::{ - ModelCapabilitySnapshot, ModelConfig, ModelSelection, RequestMetadata, SystemPrompt, + ModelCapabilitySnapshot, ModelConfig, RequestMetadata, SystemPrompt, }; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index 2bff72f891..792188210a 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -125,7 +125,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; | `unmount` | Retire a content instance this Session owns | `{instanceId}` | `{}` | None; the owner completes the release | `unknown` when no live instance has the id; `cleanup`; `closed` | | `openBranch` (Rust-only, `#[rutis::service(skip)]`) | Construct a branch's runtime context for the branch tree | `{branchId, ancestors}` | the branch's runtime context (see Exceptions) | The caller drops the call; a construction the caller abandoned is shut down before the branch becomes visible | `closed`, `build` | -`listener` and `work` are callbacks by reference: they run outside the owner's locks and outside the Timeline's commit lock. `work` returns nothing; its failure and its cleanup stay with the caller. A lease id is an owner-issued token bound to the calling row; it carries no authority, the owner settles it at the row's unload, and a caller never has to free it on an error path. +`listener` is a callback by reference: it runs outside the owner's locks and outside the Timeline's commit lock. A lease id is an owner-issued token bound to the calling row; it carries no authority, the owner settles it at the row's unload, and a caller never has to free it on an error path. ### Errors @@ -167,7 +167,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; ## Exceptions with reasons -- `openBranch` hands out the branch's runtime context: an id would put branch runtime state behind a second set of operations owned by SessionScope, while ADR 002 D1 gives the directory and the close to TimelineTree, and the branch's whole capability machine runs behind that context. Ids, values and callbacks cannot carry it, so the object crosses under the handover design above. +- `openBranch` hands out the branch's runtime context: an id would put branch runtime state behind a second set of operations owned by SessionScope, while ADR 002 D1 gives the directory and the close to TimelineTree, and the branch's whole capability machine runs behind that context. Ids, values and callbacks cannot carry it. §7 allows the object only with a lifecycle design both sides cite, and [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md) is that design: the handover table above states who creates, holds and closes it and what either side's close means. - The Session-scoped `timelineStore` binding is assembly infrastructure: the store owns the engine and the operations, SessionScope installs the binding and states the spelling, and a process caller uses `store` (§2018's requirement). - `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. - The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. @@ -216,8 +216,8 @@ The Session store constructs the Timeline engine and its Session-scope binding; ## Requirements raised to mechanism owners - [#2127](https://github.com/arcships/dim/issues/2127), owned by the dim runtime, and [#2024](https://github.com/arcships/dim/issues/2024): route by line id so a Session part resolves a branch-group data face with `line_owner::(line)?` and calls that owner's typed operation, per [ADR 027 D1–D3](https://github.com/arcships/dim/pull/2029). The instance key never leaves the instance, the caller keeps no resolution between calls, and this owner adds no forwarding operation, operation-name routing or reply envelope. TimelineTree supplies the line id and the line's state, never the address. -- The runtime's `Session` facade stops forwarding line operations: `end_branch`, `set_default_branch`, `branch`, `branches`, `directory`, `default_and_directory`, `ended_head`, `sequence`, `batch_end` and `query` are TimelineTree's, and the Session access surface must not restate them. -- [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns the Timeline engine and constructs the Session-scope binding; SessionScope installs it. The Session face publishes the per-line reads and the completion subscriptions; `query` and `sessionConfig` stay on `store`; `createSession`, `releaseSession`, `rollbackSession` and `append` are not on the Session face. +- The runtime's `Session` facade stops forwarding line operations: `end_branch`, `set_default_branch`, `branch`, `branches`, `directory`, `default_and_directory`, `ended_head`, `sequence` and `batch_end` are TimelineTree's own operations, and the Session access surface must not restate them. History reads of a line go through `timelineTree.read`, never a second `query`. +- [#2018](https://github.com/arcships/dim/issues/2018): the Session store owns the Timeline engine and constructs the Session-scope binding; SessionScope installs it. The Session face publishes the per-line reads and the completion subscriptions; `query` and `sessionConfig` exist only on the process `store`; `createSession`, `releaseSession`, `rollbackSession` and `append` are not on the Session face. ## Supersedes @@ -235,7 +235,7 @@ Rule D: no client wire protocol or user-visible behavior changes; every change h The service is marked on the owner type under one name; the existing names `sessionConfig`, `sessionIdentity`, `sessionLifecycle`, `sessionLoader` and `timelineFactory` stop existing. ```rust -use dim_agent_runtime::{PublicService, SessionConfig, SessionFault}; +use dim_agent_runtime::{PublicService, SessionConfig, SessionFault, TimelineContext}; use rutis::Ctx; use std::sync::Arc; From d23ea2f81a43f7c21a9c35dc350d7b05a976f92e Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 14:55:36 +0800 Subject: [PATCH 12/19] docs(design): close the round-three leftovers The build error table names the message it carries, the contributions example has no unused binding, and the snapshot reads state which one answers none. Refs #2025 --- docs/design/plugins/ContextFacts.md | 8 ++++---- docs/design/plugins/ContextProjection.md | 2 +- docs/design/plugins/SessionScope.md | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/design/plugins/ContextFacts.md b/docs/design/plugins/ContextFacts.md index 4af971527c..e43a754858 100644 --- a/docs/design/plugins/ContextFacts.md +++ b/docs/design/plugins/ContextFacts.md @@ -36,10 +36,10 @@ let over = counted.tokens > limits.threshold_tokens; ```rust // ContextUsage: the contributions of one request, when the model has an additive counter. -let described = owner.describe(DescribeRequest { model: selection.clone() }).await?; -let Some(algorithm) = described.algorithm else { - return Err(UsageError::NotCountable); // the caller keeps complete-request counts only -}; +// A model without an additive counter has no algorithm; the caller keeps complete-request counts only. +if owner.describe(DescribeRequest { model: selection.clone() }).await?.algorithm.is_none() { + return Err(UsageError::NotCountable); +} let parts = owner.contributions(ContributionsRequest { model: selection.clone(), fixed: Some(Fixed { system, tools }), diff --git a/docs/design/plugins/ContextProjection.md b/docs/design/plugins/ContextProjection.md index 9908fa0352..d1f99d96c8 100644 --- a/docs/design/plugins/ContextProjection.md +++ b/docs/design/plugins/ContextProjection.md @@ -97,7 +97,7 @@ else { - `renderedStream` and `renderedContext` take a cutoff, not a branch id: the owner is a branch part and folds its own branch's facts; a Session-scoped fold by branch id returned another owner's history and is removed. - The projection policy is factory configuration rather than a Session value: a table of Rust functions cannot cross languages, and a host that substitutes the projection installs another part, so no Rust-only value sits on the public face. -- `snapshotFromCheckpoint` answers none instead of failing when the anchor does not match: a snapshot is optional acceleration, and the caller's next step is the same fold the snapshot would have skipped. +- `snapshotFromCheckpoint` answers none instead of failing when the anchor does not match: a snapshot is optional acceleration, and the caller's next step is the same fold the snapshot would have skipped. `snapshot` is the caller's own cutoff and answers `invalid` when the interpreter is not current or the cut is outside the chain; it never answers none. - `streamCheckpoint` takes `batch`: a streamed fold's page size is the caller's memory decision, and the checkpoint must be built from the same fold the caller will use. ## Verification diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index 792188210a..a5c87d8ec1 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -136,7 +136,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; | `unknown` | `unmount` | The id names no live instance of this Session; nothing to retire | | `not_ready` | `mount` | Act on the reported row and state: the definition's rows did not activate; the instance was shut down and nothing is left to release | | `cleanup` | `mount`, `unmount` | The instance is unreachable but its shutdown failed; the Session will report it as a fault; treat the content as unavailable | -| `build` | `openBranch` | The branch did not open: `cause` is why, `cleanup` is a shutdown that also failed; the tree records the branch as failed and settles it | +| `build` | `openBranch` | The branch did not open: `message` says why, `cleanup` is a shutdown that also failed; the tree records the branch as failed and settles it | `reportFault`, `failure`, `config`, `identity`, `phase`, `activated` and `closing` have no error kinds: nothing in the owner refuses them. From 17705b28d851fdda864f5cba0d2e6038f1edd7c0 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 15:36:58 +0800 Subject: [PATCH 13/19] docs(design): point the Report read at the line read and index the owner contracts Report's extraction calls timelineTree.read with the request shape #2092 defines. The architecture plugin README points at the six Session-scope owner contracts, which have no page there. Refs #2025 --- docs/architecture/rust-agent/plugins/README.md | 5 +++++ docs/design/contracts/runtime-owner-operations.md | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/README.md b/docs/architecture/rust-agent/plugins/README.md index 1fd80891c6..accbb65f70 100644 --- a/docs/architecture/rust-agent/plugins/README.md +++ b/docs/architecture/rust-agent/plugins/README.md @@ -20,6 +20,11 @@ runtime assembly and scripted model hosts: a newly assembled capability needs it entry here. Excluded rows can still appear as providers or consumers in the generated blocks. A service dependency is not necessarily a plugin with the same name. +The Session-scope owner contracts have no page here because their parts are infrastructure or +scripted rows: [SessionScope](../../../design/plugins/SessionScope.md), [Request settings](../../../design/plugins/RequestSettings.md), +[Context facts](../../../design/plugins/ContextFacts.md), [Context projection](../../../design/plugins/ContextProjection.md), +[Summary strategy](../../../design/plugins/SummaryStrategy.md) and [File access facts](../../../design/plugins/FileAccessFacts.md) (#2025). + ## Index | Plugin | Process | Session parts | Branch parts | diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 782d62fd55..81d5a36611 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -44,8 +44,8 @@ before calling again ([#2127](https://github.com/arcships/dim/issues/2127)). For a live main branch, Report captures its published head once at draft capture (`directory({id:"main"}).head`) and stores it as `conversationThrough` on that draft. Activity evidence and later opt-in -conversation extraction call `timelineTree.query` with the same explicit `through`, -existing bounded window and `include_publishing: false`. Zero yields an empty window. +conversation extraction call `timelineTree.read` with `{line: "main", through: conversationThrough, limit: }`; +the read answers committed facts at that cutoff only, so there is no publishing flag and zero rows yield an empty window. A draft without a captured cutoff does not fetch a conversation. Plan generation never substitutes a newer head. From 3d979a7fdc56d6d51542986d85adb08af5a0e6c6 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 17:08:11 +0800 Subject: [PATCH 14/19] docs(design): hand the superseded rows to their owners as pointers The Report rows and the Session-scoped timelineStore rows become pointers to the contracts that define them; the summary strategy reports calls and usage, and the caller measures the duration. Refs #2025 --- docs/design/contracts/runtime-owner-operations.md | 10 +++------- docs/design/plugins/SummaryStrategy.md | 2 +- docs/design/resource-faces.md | 12 ++++++------ docs/design/service-faces.md | 2 +- 4 files changed, 11 insertions(+), 15 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 81d5a36611..9d0a548b79 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -24,7 +24,7 @@ | Context RPC → target branch | `agentLoop.compact` and `contextUsage.read`. | | Goal and Shell admission → timelineTree | `directory({id})` returns the matching directory entry or the unknown-branch error using a single-branch lookup. Goal reads ended history through `read` at the line's fixed head; writes retain the ended/unknown errors. | | InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | -| PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report also uses `timelineTree.read` at the selected head for evidence. | +| PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report's own tree reads are [TimelineTree's](https://github.com/arcships/dim/pull/2092), not this row's. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | | Fault producers and Session observers → `sessionScope` | `reportFault(fault) → void`, `failure() → SessionFault or none`, `observeFault(listener) → id`, `release({leaseId}) → boolean`. The listener receives the current failure (none included) and later reports; the calling row's unload releases the observation. The first fault wins until a storage failure supersedes it ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | | Check providers and input admission → SubmitChecks | `register(name, check) → void`; `check({entry, branchId, user?, mode}, cancelled) → proceed{blocks, warnings} or block{message}`. Run in name order through the first block. Interrupted checks write nothing. | @@ -42,12 +42,8 @@ the caller takes no hold and does not retry it. `SessionClosing` ends the Sessio Session part never receives `NoSession`: only a process caller does, and it takes a hold from Agents before calling again ([#2127](https://github.com/arcships/dim/issues/2127)). -For a live main branch, Report captures its published head once at draft capture (`directory({id:"main"}).head`) -and stores it as `conversationThrough` on that draft. Activity evidence and later opt-in -conversation extraction call `timelineTree.read` with `{line: "main", through: conversationThrough, limit: }`; -the read answers committed facts at that cutoff only, so there is no publishing flag and zero rows yield an empty window. -A draft without a captured cutoff does not fetch a conversation. Plan generation never -substitutes a newer head. +Report's draft head, its bounded conversation window and the cutoff it keeps are stated by the +[TimelineTree contract](https://github.com/arcships/dim/pull/2092) and Report's own contract; this document keeps neither. ### Prompt, configuration and files diff --git a/docs/design/plugins/SummaryStrategy.md b/docs/design/plugins/SummaryStrategy.md index ac377ae56e..94046a1c7a 100644 --- a/docs/design/plugins/SummaryStrategy.md +++ b/docs/design/plugins/SummaryStrategy.md @@ -9,7 +9,7 @@ The owner replaces a range of a branch's history with a summary produced by mode The owner answers: - **The plan.** The strategy's name and the planned token size of its replacement, so the caller can reserve the space before the strategy runs. -- **The replacement.** One compaction from a request at a cutoff: the chosen cut, the replacement messages, and the model calls, usage and duration it took. +- **The replacement.** One compaction from a request at a cutoff: the chosen cut, the replacement messages, and the model calls and usage it took. The caller measures the duration. - **The outcome as data.** `completed`, `skipped` or `failed`, each with diagnostics; a failure inside the strategy is an outcome, not an error. Callers keep: diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index bea6aa4f24..d9965231ae 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -605,16 +605,16 @@ code the operation already uses, so one code vocabulary serves the local and the ## 5. `store` and `timelineStore` The repository and Timeline operations use two names on the daemon that owns the state: process -`store` provides the repository operations (§5.2), retaining its existing Timeline `query`, -and Session-scoped `timelineStore` provides the Timeline operations and completion notifications -below. Both use the existing state owner; the split follows §9(6), without changing Session -placement or the storage engine. +`store` provides the repository operations (§5.2), retaining its existing Timeline `query`. +The Session-scoped `timelineStore` and its completion notifications are replaced by the +[SessionScope contract](plugins/SessionScope.md) (#2093). Both use the existing state owner; the +split follows §9(6), without changing Session placement or the storage engine. SessionTitle and FileAccess use the process repository operations in the [resource owner contract](contracts/resource-owner-operations.md). | Family | Operations | | --- | --- | -| Timeline (`timelineStore`) | Session face: `head`, `branches`, `readPage`, `readSegments`, `trace`, `batchEnd`, `batchEndAt`, `saveSnapshot`, `latestSnapshot`; the process face `store` keeps `query` and `sessionConfig`; `createSession`, `releaseSession`, `rollbackSession` and `append` are the engine's own path ([SessionScope](plugins/SessionScope.md), #2093) | -| Timeline completion (`timelineStore`) | `commits`, `closeCommits`; notifications `{subscriptionId, batchId, branchId, through, result}` | +| Timeline (`timelineStore`) | Replaced by the [SessionScope contract](plugins/SessionScope.md) (#2093). | +| Timeline completion (`timelineStore`) | Replaced by the [SessionScope contract](plugins/SessionScope.md) (#2093). | | Session rows (`store`) | The repository operations listed in §5.2 | | Worktree association (`store`) | `associateWorktree`; [service faces](service-faces.md) §4.8 | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index b0762934b1..9f2678ca56 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -126,7 +126,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou | `hostPlatform` | `ProcessTree`、`PtyProcessTree`、临时目录 | 数据面 `execHost`:`start`/`wait`/`kill`/`settle`/`output`/`tail`/`removeOutputDirectory`/`shell`/`write`/`resize`/`info`/`confined`/`configured`([resource and store data faces](resource-faces.md) §3,#1295);`hostPlatform` 是提供方和它的 Rust binding | | `fileStorage` | `FilePath`、根与代次 | 数据面 `fsHost`:工具部分 `resolve`/`read`/`write`/`edit`/`glob`/`grep`/`mentions`,存储部分 `stat`/`readBytes`/`openRead`/`readAt`/`closeRead`/`lock`/`unlock`/`backup`/`createDirectory`/`replace`/`list`/`remove`(§4,#1297);`fileStorage` 是提供方和 binding | | `sqliteStorage` | 连接与事务 | Session 行走 `store`;原生 Agent、Provider 和 Settings 的记录操作直接调用 `sqliteStorage`,连接与事务由 SQLite 插件持有。`sqliteStorage.storageReport({})` 返回 SQLite 文件和 WAL 的容量指标([存储契约](appserver/native-storage-format.md)) | -| `timelineStore` | 连接与批次 | Session 作用域的 `timelineStore` 数据面(resource-faces §9 允许与仓储族分名):每行读取与完成通知 `head`/`branches`/`readPage`/`readSegments`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`/`commits`/`closeCommits`;`query` 与 `sessionConfig` 只在进程面 `store`(未加载的 Session 也能读),`createSession`/`releaseSession`/`rollbackSession`/`append` 不在 Session 面。引擎归 SessionStore,SessionScope 安装该绑定([SessionScope](plugins/SessionScope.md),#2093) | +| `timelineStore` | 连接与批次 | Session 面由 [SessionScope](plugins/SessionScope.md) 取代(#2093);进程面 `store` 见 #2018 | | `promptSourcesBranch` | 分支 prompt 装配 | 按 #1292 确认公共操作与装配内部职责。 | 这些行按当前对象形状分组。前四行的数据契约由 [resource and store data faces](resource-faces.md) 定义(#1295/#1297/#1298)。其余行按 #1292 逐批确定操作面。 From 2d9e0ed350cddfb18ae79a29b0ce2b0a7370806d Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 17:08:42 +0800 Subject: [PATCH 15/19] docs(design): match Supersedes to the pointer edits Refs #2025 --- docs/design/plugins/SessionScope.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index a5c87d8ec1..7f3cd683a6 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -223,9 +223,9 @@ The Session store constructs the Timeline engine and its Session-scope binding; This contract replaces the Session-scope paragraphs and rows that state these names; the delivery in #2025 carries the migration. -- `docs/design/contracts/runtime-owner-operations.md`: the `sessionLifecycle` rows of "Retained operations" and "New rutis APIs on existing owners", the `sessionLoader` row, and the "Calls from a Session to a selected branch" section — a branch-group data face is resolved by line id, and `timelineTree.call` is removed rather than kept. `line_owner::(line)` reaches any branch-group data face except registration points and lifecycle services ([ADR 027 D1 and D3](https://github.com/arcships/dim/pull/2029); the routing mechanism is [#2127](https://github.com/arcships/dim/issues/2127)). -- `docs/design/service-faces.md`: §3.6's `timelineFactory` row, §3.2's `agentConfig`, `skillsConfig` and `collaborationConfig` rows, and §3.4's `timelineStore` row, which now spells the Session face and leaves `query` and `sessionConfig` on the process face `store`. -- `docs/design/resource-faces.md` §5: the Timeline family row, updated to the same spelling; the engine and its process face remain #2018's. +- `docs/design/contracts/runtime-owner-operations.md`: the `sessionLifecycle` rows of "Retained operations" and "New rutis APIs on existing owners", the `sessionLoader` row, the Report rows and the Report paragraph of "Calls from a Session to a selected branch" (now pointers to TimelineTree's `read` and `directory`), and the "Calls from a Session to a selected branch" section — a branch-group data face is resolved by line id, and `timelineTree.call` is removed rather than kept. `line_owner::(line)` reaches any branch-group data face except registration points and lifecycle services ([ADR 027 D1 and D3](https://github.com/arcships/dim/pull/2029); the routing mechanism is [#2127](https://github.com/arcships/dim/issues/2127)). +- `docs/design/service-faces.md`: §3.6's `timelineFactory` row, §3.2's `agentConfig`, `skillsConfig` and `collaborationConfig` rows, and §3.4's `timelineStore` row, which is now a pointer to this contract. +- `docs/design/resource-faces.md` §5: the `timelineStore` rows and the Session-scope sentence, now pointers to this contract; the engine and its process face remain #2018's. - `docs/design/plugin-contract.md`: the `sessionIdentity`, `sessionLifecycle`, `sessionConfig` and `agentConfig` rows of the named-services table, the `session` row of the scope table, and R2's needed names. Rule D: no client wire protocol or user-visible behavior changes; every change here is plugin-facing. From 9c46f214ef83ec3930dda258f65d5a5941421bf0 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 17:27:44 +0800 Subject: [PATCH 16/19] docs(design): close the pre-review findings The Session timelineStore rows point at SessionStore's contract, the treeCommands rows follow the line_owner route, the compaction ports point at their owners, config is fixed and resolution stays with Permission. The remaining documents that name the deleted services are listed for delivery. Refs #2025 --- .../contracts/runtime-owner-operations.md | 10 +++--- docs/design/plugin-contract.md | 5 ++- docs/design/plugins/ContextCompaction.md | 32 ++++++++----------- docs/design/plugins/FileAccessFacts.md | 14 ++++---- docs/design/plugins/RequestSettings.md | 7 ++-- docs/design/plugins/SessionScope.md | 14 +++++--- docs/design/plugins/SummaryStrategy.md | 4 +-- docs/design/resource-faces.md | 9 +++--- 8 files changed, 46 insertions(+), 49 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index 9d0a548b79..d670619cda 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -16,14 +16,14 @@ | Caller → owner | New API | | --- | --- | -| Branch directory readers → `timelineTree` | `timelineTree.directory({}) → [{info, head, state, endEvent?}]`, including ending and ended branches. | +| Branch directory readers → `timelineTree` | `timelineTree.directory({}) → {default, lines}` ([TimelineTree](https://github.com/arcships/dim/pull/2092), #2024). | | Skills content and MCP publication → Session mounts | `sessionScope.mount({group, definitionId, instanceData}) → {instanceId}`; `unmount({instanceId})`. The owner admits groups whose configured parent is the Session group, waits for the definition's rows and settles a rejected instance. Skills supplies its content definition; MCP supplies its connection definition ID and retains the resolved transport configuration ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | -| Goal → timelineTree | `inputs(id, inputs) → committed events`. One validated atomic batch for the Goal record and trigger. | -| Branch-detail RPC → timelineTree | `display(id) → {entry,purpose?,cutMessages?,end?}`. | +| Goal → the target line's input owner | `line_owner::(line).submit(...)`; one validated atomic batch for the Goal record and trigger ([ADR 027](https://github.com/arcships/dim/pull/2029)). | +| Branch-detail RPC → timelineTree | `line({line})` for the record and `read({line, …})` for the facts; there is no `display` operation. | | History RPC and line-read tools → timelineTree | `read({line, through, …})` at one cutoff, with the complete batches and the fixed head of an ended line; the reply carries the events or the selected fields. | | Context RPC → target branch | `agentLoop.compact` and `contextUsage.read`. | -| Goal and Shell admission → timelineTree | `directory({id})` returns the matching directory entry or the unknown-branch error using a single-branch lookup. Goal reads ended history through `read` at the line's fixed head; writes retain the ended/unknown errors. | -| InputQueue and Collaboration approvals → target branch | `timelineTree.input`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | +| Goal and Shell admission → timelineTree | `line({line})` returns the matching record or `unknown` ([TimelineTree](https://github.com/arcships/dim/pull/2092)). Goal reads ended history through `read` at the line's fixed head; writes retain the ended/unknown errors. | +| InputQueue and Collaboration approvals → target branch | `line_owner::(line).submit(...)`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | | PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report's own tree reads are [TimelineTree's](https://github.com/arcships/dim/pull/2092), not this row's. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | | Fault producers and Session observers → `sessionScope` | `reportFault(fault) → void`, `failure() → SessionFault or none`, `observeFault(listener) → id`, `release({leaseId}) → boolean`. The listener receives the current failure (none included) and later reports; the calling row's unload releases the observation. The first fault wins until a storage failure supersedes it ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 639622e6e4..1cd8034ff1 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -59,7 +59,7 @@ process (root) process parts: storage, catalogs, connections, Ag | --- | --- | --- | --- | | Process (root) | Host start | Host shutdown | — (process parts provide their own) | | Agent (`agent`) | Agents creates an Agent | Agent close, host shutdown | Host-internal | -| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionScope`, `treeCommands` | +| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionScope` ([SessionScope](plugins/SessionScope.md)); the branch group is reached by line id, not through a Session service | | Branch (`branch`) | TimelineTree creates a branch | The branch ends, or its Session closes | `timeline`, `dispatcher`, `branchLifecycle`, `timelineIdentity` | Visibility follows the tree, as in [principles §2](../architecture/rust-agent/principles.md): @@ -67,7 +67,7 @@ Visibility follows the tree, as in [principles §2](../architecture/rust-agent/p | Direction | How | | --- | --- | | Up (an enclosing instance, the process) | Inject the service by name | -| Down (Session to branch) | `treeCommands`: input by branch id, branch creation. Never by injecting a branch service | +| Down (Session to branch) | `line_owner::(line)`: any branch-group data face by line id ([ADR 027](https://github.com/arcships/dim/pull/2029)); branch creation is `timelineTree.create`. Never by injecting a branch service | | Sideways (sibling branches, other Sessions) | Not visible. Go through a common ancestor's business service, such as `sessions` | The scope roots, the facades and their publication rules are mechanisms. Each Session and branch is @@ -114,7 +114,6 @@ R4). This table says what each name Dim defines is for. | `workflowFiles` | process | App Server | yes | Marked `#[rutis::service]` | | `eventHub` | process | EventHub | designed, not implemented | A producer declares a source and publishes an event; EventHub delivers it to the Sessions subscribed, through Agents' `sessions` ([EventHub](plugins/EventHub.md)) | | `collaborationMembers:` | process | the member provider | designed, not implemented | [ExternalAgent](plugins/ExternalAgent.md); registers with Collaboration when built (rutis usage R6) | -| `treeCommands` | `session` | TimelineTree | yes | `input` by branch id, `create`, `list`, `info` | | `sessionScope` | `session` | SessionScope | yes, except `openBranch` | `config`, `identity`, `phase`, `activated`, `closing`, `hold`, `release`, `reportFault`, `failure`, `observeFault`, `mount`, `unmount`; `openBranch` is Rust-only (`#[rutis::service(skip)]`) because the branch's runtime context has a shared lifecycle but no serde form ([SessionScope](plugins/SessionScope.md), #2093) | | `timeline` | `branch` | BranchScope | yes, except `before` | `append`, the published sequence and the event query (§5.4); the query reaches other languages with its declaration | | `dispatcher` | `branch` | BranchScope | yes, `consume`, `listen` and reads; their Rust forms are the same `consume` and `subscribe`, which is Rust-only | Ordered consumption (§5.2) | diff --git a/docs/design/plugins/ContextCompaction.md b/docs/design/plugins/ContextCompaction.md index fe2dd23d6a..1fea8226aa 100644 --- a/docs/design/plugins/ContextCompaction.md +++ b/docs/design/plugins/ContextCompaction.md @@ -110,14 +110,17 @@ provider must not depend on `TreeCommands`, which the branch tree provides. ### 2.1 Where the manual step lives +The manual compaction step is ContextPreparation's; the paragraphs that assign the command, the +single-flight slot and the steps to Loop are superseded by ContextPreparation's contract (#2027). +The text below records the earlier arrangement. + The Loop runs the manual compaction step itself, in a tracked task, by calling `ContextPolicy::compact_step`. It does not drive ContextPreparation through an event. The reasons: -- **The Loop already holds what the step needs.** Its `Deps` already inject `Timeline`, - `HistoryRenderer` and `ContextModelHost` - ([agent_loop.rs](../../../crates/dim-agent-capabilities/src/agent_loop.rs) `LoopPlugin::Deps`); - F1 adds `CompactionStrategyHost` beside them. The Loop already builds the request from the - latest `context/configured` in `start_preparation`. +- **The Loop already holds what the step needs.** Its `Deps` inject `Timeline`, the context + projection and the model facts ([agent_loop.rs](../../../crates/dim-agent-capabilities/src/agent_loop.rs) + `LoopPlugin::Deps`); the summary policy is `summaryStrategy` ([Summary strategy](SummaryStrategy.md)). + The Loop already builds the request from the latest `context/configured` in `start_preparation`. - **Nothing is handed over.** `context/prepare` hands a request to ContextPreparation and then to ModelProvider. A manual step makes no model request, so a handoff would only add a second command and a second single-flight slot (ContextPreparation's `current`). @@ -195,12 +198,9 @@ disconnect cancels nothing. ### 4.2 Ports (Rust, runtime-internal) -The existing `ContextModel` port is split in two. Each comes from its own Session value. - -| Port | Session value | Methods | F1 implementation | -| --- | --- | --- | --- | -| `ContextModel` (narrowed) | `ContextModelHost(Option>)` (existing) | `context_window`, `output_tokens`, `threshold_tokens`, `count_tokens`; `compact` moves out | `ProductContextModel` (§5.1) | -| `CompactionStrategy` (new) | `CompactionStrategyHost(Option>)` | `name`, `replacement_size(model)`, `compact(input, cancel) -> Completed {retain_from, replacement, strategy, diagnostics} \| Skipped {reason, diagnostics} \| Failed {error, diagnostics} \| Err(HostError)` | `ProductSummaryStrategy` (§5.2) | +The model facts and the summary policy are the `contextFacts` and `summaryStrategy` operations; +the profile that compacts installs both owners' parts. §4.2's object ports are replaced by the +[Context facts](ContextFacts.md) and [Summary strategy](SummaryStrategy.md) contracts (#2025). Both values are bound explicitly in every profile, as `ContextModelHost` is today. The policy exists when both are `Some`. One `Some` without the other is an assembly defect that @@ -508,14 +508,8 @@ pub struct ProductSummaryStrategyPlugin { host: DepKey } pub struct ContextMethodsPlugin; // Deps = (Keyed, Keyed); methods.register(ctx, "session.context", ..) -// dim-app-server/src/cli.rs, defaults::install_compaction, the one install of every profile -// that compacts; the product profile passes ProductContextModel and its product home, -// the --models profile passes AimuxModels and its --home: -builder.session_value(Arc::new(ContextModelHost(Some(model)))) - .require_feature(Feature::new("ContextCompaction") - .session("ProductSummaryStrategy", |names| names.part(ProductSummaryStrategyPlugin::new(names)?)) - .session("ContextMethods", |names| names.part(ContextMethodsPlugin))); -// The mock profile binds ContextModelHost(None) and CompactionStrategyHost(None). +// The binding shapes of these two parts are stated by the Context facts and Summary strategy +// contracts (#2025); this document keeps only the plugin row that installs them. ``` ## 5. Flows diff --git a/docs/design/plugins/FileAccessFacts.md b/docs/design/plugins/FileAccessFacts.md index ef926f5c02..c87e4dbaac 100644 --- a/docs/design/plugins/FileAccessFacts.md +++ b/docs/design/plugins/FileAccessFacts.md @@ -8,7 +8,6 @@ The owner answers what one call's target path is and which file-access facts hol The owner answers: -- **The resolved target.** The path a call names with `~`, the working directory, `..` and links resolved, as the workspace sees it. - **The facts.** Workspace, system, owned and grant membership under the branch's effective access preset and the grant mode the call asks for, plus the reason a workspace discovery failed when it did. - **The confirmed roots.** The workspace and the managed worktree roots a command's process boundary may use. @@ -20,7 +19,7 @@ Callers keep: | Requirement (caller) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| Permission resolves a file call's target and decides with the facts under the branch's access preset | No: `~`, cwd, `..` and link resolution are the workspace's knowledge, the grant rule reads the preset, and the owned and grant facts come from two owners the caller would otherwise each hold | `check` | +| Permission decides a file call with the facts under the branch's access preset | No: the grant rule reads the preset, and the owned and grant facts come from two owners the caller would otherwise each hold | `check`; Permission keeps resolving the target, as ADR 014 D3 assigns it | | A command's preparation needs the confirmed workspace boundary | No: the workspace and the managed worktree roots are validated against the Session's workspace; a caller that composed them could start a process outside the boundary | `workspaceRoots` | ## Caller example @@ -28,7 +27,7 @@ Callers keep: ```rust // Permission: one file call's target and facts under the requested access. let facts = access - .check(Check { access: FileAccess::WorkspaceReadWrite, mode: GrantMode::Write, path }, cancelled) + .check(Check { access: FileAccess::WorkspaceReadWrite, mode: GrantMode::Write, path: resolved }, cancelled) .await?; let inside = facts.workspace || facts.system || facts.owned || facts.grant; ``` @@ -53,10 +52,10 @@ let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `check` | Resolve a call's target and answer the facts under the branch's access preset | `{access, mode, path}` | `{target, workspace, system, owned, grant, discoveryError?}` | The caller drops the call; the reads stop | `invalid`, `unavailable`, `cancelled`, `closed` | +| `check` | Answer the facts of one resolved path under the branch's access preset | `{access, mode, path}` | `{workspace, system, owned, grant, discoveryError?}` | The caller drops the call; the reads stop | `invalid`, `unavailable`, `cancelled`, `closed` | | `workspaceRoots` | The workspace and managed worktree roots a command may use | `{cwd}` | `{roots}` | The caller drops the call | `invalid`, `unavailable`, `cancelled`, `closed` | -`access` is the branch's access preset (`dim_agent_types::FileAccess`: `read-only`, `workspace-read-write`, `unrestricted`); `mode` is the grant mode the call asks for (`dim_agent_types::grant::GrantMode`: `read`, `write`); `path` is the path the call named. `target` is the resolved path, and it is what the caller passes to the file operation. A write grant is inert under `read-only` and active under `workspace-read-write`; `unrestricted` does not widen grants because it already allows every write. +`access` is the branch's access preset (`dim_agent_types::FileAccess`: `read-only`, `workspace-read-write`, `unrestricted`); `mode` is the grant mode the call asks for (`dim_agent_types::grant::GrantMode`: `read`, `write`); `path` is the path the caller already resolved, as ADR 014 D3 assigns resolution to Permission. A write grant is inert under `read-only` and active under `workspace-read-write`; `unrestricted` does not widen grants because it already allows every write. ### Errors @@ -85,7 +84,7 @@ let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; ## Verification -- `check` resolves `~`, `..` and a link before answering; the target is absolute; a write grant under `read-only` answers `grant: false`. +- `check` answers the four facts for the resolved path; a write grant under `read-only` answers `grant: false`; a relative path is `invalid`. - An owned Session file and a granted path each answer their fact under the requested mode; a path outside every fact answers all false. - A failed discovery answers `workspace: false` with `discoveryError` and no error. - `workspaceRoots` answers the workspace plus the managed worktree roots; `unavailable` when the workspace cannot be read. @@ -123,7 +122,7 @@ None. This contract replaces the object shape of the file-access facts; the delivery in #2025 carries the migration. -- [ADR 014](../../adr/014-file-access-facts.md): the query is stated here as a Session-scoped operation `check`, with the Session instance supplying the session id and `FileAccess` and `GrantMode` as the same query arguments the ADR names. +- [ADR 014](../../adr/014-file-access-facts.md): the query is stated here as a Session-scoped operation `check`, with the Session instance supplying the session id and `FileAccess` and `GrantMode` as the same query arguments the ADR names. Resolution stays with Permission, as ADR 014 D3 assigns it; the reply carries the four facts and no `target`. - `crate::file_access::ReadFileAccessFacts` and the `FileAccessFacts` wrapper: the two reads replace the trait and the object. Rule D: no client wire protocol or user-visible behavior changes; the change is plugin-facing. @@ -147,7 +146,6 @@ pub struct Check { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Facts { - pub target: String, pub workspace: bool, pub system: bool, pub owned: bool, diff --git a/docs/design/plugins/RequestSettings.md b/docs/design/plugins/RequestSettings.md index 98586c76cc..c3db24d339 100644 --- a/docs/design/plugins/RequestSettings.md +++ b/docs/design/plugins/RequestSettings.md @@ -36,12 +36,13 @@ let settings = ModelSettings { config: defaults.config, system: Some(guide.compose_system(&branch, defaults.system)), tools: Some(binding.definitions(&request_id)?), - metadata: defaults.metadata.map(|mut metadata| { + metadata: { + let mut metadata = defaults.metadata.unwrap_or_default(); metadata.session_id = Some(session_id); metadata.turn_id = Some(turn_id); metadata.extensions.insert("requestId".into(), request_id.into()); // per request, written by Loop - metadata - }), + Some(metadata) + }, }; ``` diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index 7f3cd683a6..3e9cc6bfc7 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -8,7 +8,7 @@ SessionScope is the runtime's Session owner: the creation record and identity, t SessionScope owns: -- **The creation record.** The Session's mount list, working directory, model selection, system prompt, permission preset, collaboration role, interactive flag, language seed and initial title, fixed when the Session is built. Every member is fixed except `language`, which the native store updates in place; a caller reads the live reply language from `sessionLanguage`, never from this value. +- **The creation record.** The Session's mount list, working directory, model selection, system prompt, permission preset, collaboration role, interactive flag, language seed and initial title, fixed when the Session is built. Every member is fixed for the Session's whole life; a caller reads the live reply language from `sessionLanguage`, never from this value. - **Identity.** The Session id and whether the Session was restored from the store. - **The phase.** Loading, Active, Closing, Closed, monotonic and never replaced by an earlier phase. `activated` and `closing` are the waits on the two transitions. - **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. Every lease is bound to the calling row and the owner settles it at the row's unload, so no caller frees anything on an error path. `hold` answers an id for accepted work; the id is bound to the calling row and the owner settles it at the row's unload. A lease reports nothing and cancels nothing. @@ -122,6 +122,8 @@ The Session store constructs the Timeline engine and its Session-scope binding; | `reportFault` | Record the fault that stopped the Session | `{fault}` | `{}` | None | None | | `failure` | The fault in force, if any | `{}` | `{fault?}` | None | None | | `mount` | Create a Session-owned content instance from a definition | `{group, definitionId, instanceData}` | `{instanceId}` | The caller drops the call; an instance it no longer waits for is shut down before the reply | `invalid`, `not_ready`, `cleanup`, `closed` | + +A registered Session extension definition must activate its instance rows; a host-added optional group keeps its optional rows, so a Pending row there is not `not_ready`. | `unmount` | Retire a content instance this Session owns | `{instanceId}` | `{}` | None; the owner completes the release | `unknown` when no live instance has the id; `cleanup`; `closed` | | `openBranch` (Rust-only, `#[rutis::service(skip)]`) | Construct a branch's runtime context for the branch tree | `{branchId, ancestors}` | the branch's runtime context (see Exceptions) | The caller drops the call; a construction the caller abandoned is shut down before the branch becomes visible | `closed`, `build` | @@ -131,7 +133,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; | Kind | Operation | What the caller does next | | --- | --- | --- | -| `closed` | `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading; stop starting work; a later generation serves the next Session | +| `closed` | `hold`, `observeFault`, `release`, `mount`, `unmount`, `openBranch` | The Session is closing or unloading, or an idle release is decided; stop starting work. An idle-release decision can be withdrawn while `phase` is still `active`, so a lease holder that must continue retries `hold` after the next publication | | `invalid` | `release`, `mount` | Fix the id or the definition: an id of another row, a group outside this Session's subtree, an unknown definition | | `unknown` | `unmount` | The id names no live instance of this Session; nothing to retire | | `not_ready` | `mount` | Act on the reported row and state: the definition's rows did not activate; the instance was shut down and nothing is left to release | @@ -184,7 +186,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; - `mount` answers `invalid` for a group outside the Session's subtree, `not_ready` for a definition whose row failed (and leaves no instance), and shuts down an abandoned mount; `unmount` answers `cleanup` when the shutdown fails and `unknown` for an id this Session never issued. - `activated` answers false when the Session closes before publishing; `closing` returns when the close starts. - `openBranch` answers `closed` during the Session's close; a failed construction settles the branch scope before the reply; the tree closes every branch before the Session scope unloads. -- `identity` is fixed; `phase` only moves forward through the four phases; `config` is fixed except `config.language`, which the native store updates in place. +- `identity` and every member of `config` are fixed; `phase` only moves forward through the four phases. A reply-language change never touches this value: the live language is `sessionLanguage`. ## Rule check @@ -202,7 +204,7 @@ The Session store constructs the Timeline engine and its Session-scope binding; | §4 rule 7 | Callers use these operations; no caller reads the hold count, the fault slot or an instance's fiber. | | §4 rule 8 | No infrastructure change. SessionScope is the runtime's Session part and its shape is the runtime's decision; the operations above are the data face those decisions already require. | | §4 rule 9 | No Timeline fact: the phase and the fault record are runtime state, read live and never persisted as events. | -| §7 values, ids and objects | The record, identity, phase and fault are values; a lease id and a content instance id are the owner's, bound to the calling row and settled at its unload; the one object is `openBranch`, with the handover design above. | +| §7 values, ids and objects | The record, identity, phase and fault are values; a lease id is bound to the calling row and settled at its unload; a content instance id belongs to the Session and is settled by `unmount` or the Session's end; the one object is `openBranch`, with the handover design above. | | §7 no proxy lookup | The owner returns only its own state; the Agent's configuration and the Skills and Collaboration factory texts leave this face. | | §7 one interface | One name, `sessionScope`, on the owner type; the wire calls every method except `openBranch`, which is marked `#[rutis::service(skip)]`; no facade or wrapper type. | | §7 cross-language | Every operation is data, a callback by reference or an id, except `openBranch`: it hands TimelineTree the branch's runtime context, which has no serde form, and the tree is a Rust part. That is the only Rust-only method, and it is marked skip. | @@ -228,11 +230,13 @@ This contract replaces the Session-scope paragraphs and rows that state these na - `docs/design/resource-faces.md` §5: the `timelineStore` rows and the Session-scope sentence, now pointers to this contract; the engine and its process face remain #2018's. - `docs/design/plugin-contract.md`: the `sessionIdentity`, `sessionLifecycle`, `sessionConfig` and `agentConfig` rows of the named-services table, the `session` row of the scope table, and R2's needed names. +These documents still name the deleted Session services in dependencies; #2025's delivery updates them in the same change: `docs/design/session-typescript.md` (307, 320-322, 329, 373, 405, 470), `docs/design/contracts/session-boundary.md:560`, `docs/design/plugins/ShellInput.md:35`, `docs/design/plugins/Questions.md:50,575`, `docs/design/plugins/SessionTitle.md:75-76,126,408`, `docs/design/plugins/Collaboration.md:47,63`, `docs/design/plugins/Report.md:133`, `docs/design/plugins/Pursuit.md:46,184`, `docs/design/plugins/EventHub.md:399,597`, `docs/design/plugins/EnvironmentClients.md:155`, `docs/design/plugins/CodeMode.md:455` and `docs/design/thin-instances.md:281`. + Rule D: no client wire protocol or user-visible behavior changes; every change here is plugin-facing. ## Binding appendix -The service is marked on the owner type under one name; the existing names `sessionConfig`, `sessionIdentity`, `sessionLifecycle`, `sessionLoader` and `timelineFactory` stop existing. +The service is marked on the owner type under one name; the Session-scope entries for `sessionConfig`, `sessionIdentity`, `sessionLifecycle`, `sessionLoader` and `timelineFactory` stop existing (`store.sessionConfig` remains the store's process read). ```rust use dim_agent_runtime::{PublicService, SessionConfig, SessionFault, TimelineContext}; diff --git a/docs/design/plugins/SummaryStrategy.md b/docs/design/plugins/SummaryStrategy.md index 94046a1c7a..143bbe57ca 100644 --- a/docs/design/plugins/SummaryStrategy.md +++ b/docs/design/plugins/SummaryStrategy.md @@ -61,7 +61,7 @@ match outcome.outcome { - `S:contextFacts` — the limits and the token count the plan and the chunk budget need. - `P:modelHost` — the summarizer's model calls, under the existing failure and credential policy. - `P:providerConnectionResolver` — the connection each summarizer request uses; the connection lives only inside the call. -- `S:summaryPromptSettingsHost` — optional: the operator's system prompt override, read once when the owner loads. +- `P:summaryPromptSettingsHost` — optional: the operator's system prompt override, read once when the owner loads. - `S:guideEntries` — the `` entry, registered until the owner unloads. ### Operations @@ -142,7 +142,7 @@ This contract replaces the `compactionStrategyHost` object; the delivery in #202 - `docs/design/contracts/runtime-owner-operations.md`: the `Loop and ContextPreparation → CompactionStrategyHost` row of "Model preparation, history and tools". - `docs/design/service-faces.md`: §3.5's `compactionStrategyHost` row. -- `docs/design/plugins/ContextCompaction.md` §4.2's ports table: `CompactionStrategyHost` becomes this owner's two operations, and `CompactionInput.model` leaves the input. +- `docs/design/plugins/ContextCompaction.md` §4.2's ports table: `CompactionStrategyHost` becomes this owner's two operations, and `CompactionInput.model` leaves the input; the document's remaining mentions of the object ports are descriptive, and the delivery removes them. Rule D: no client wire protocol or user-visible behavior changes; `completed`, `skipped` and `failed` keep their fact shapes and the summary's model-visible text is unchanged. diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index d9965231ae..7908fa5e30 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -607,14 +607,15 @@ code the operation already uses, so one code vocabulary serves the local and the The repository and Timeline operations use two names on the daemon that owns the state: process `store` provides the repository operations (§5.2), retaining its existing Timeline `query`. The Session-scoped `timelineStore` and its completion notifications are replaced by the -[SessionScope contract](plugins/SessionScope.md) (#2093). Both use the existing state owner; the -split follows §9(6), without changing Session placement or the storage engine. +[SessionStore contract](https://github.com/arcships/dim/pull/2091) (#2018), which keeps the +operations, the request and reply shapes and the notification shape. Both use the existing state +owner; the split follows §9(6), without changing Session placement or the storage engine. SessionTitle and FileAccess use the process repository operations in the [resource owner contract](contracts/resource-owner-operations.md). | Family | Operations | | --- | --- | -| Timeline (`timelineStore`) | Replaced by the [SessionScope contract](plugins/SessionScope.md) (#2093). | -| Timeline completion (`timelineStore`) | Replaced by the [SessionScope contract](plugins/SessionScope.md) (#2093). | +| Timeline (`timelineStore`) | Replaced by the [SessionStore contract](https://github.com/arcships/dim/pull/2091) (#2018); #2091 adds the operations and the completion shape back there. | +| Timeline completion (`timelineStore`) | Replaced by the [SessionStore contract](https://github.com/arcships/dim/pull/2091) (#2018). | | Session rows (`store`) | The repository operations listed in §5.2 | | Worktree association (`store`) | `associateWorktree`; [service faces](service-faces.md) §4.8 | From affab40e4502fbed222549624e2a1954f8512955 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 17:50:23 +0800 Subject: [PATCH 17/19] docs(design): close the second pre-review The Session timelineStore face carries no sessionId: the instance identity supplies it. The operations table renders again, a fault is still recorded after close, the tree rows and the plugin-contract cells match #2092, the adopted allowance is repaired at adoption, and the delivery mapping lists the current instance errors. Refs #2025 --- .../contracts/runtime-owner-operations.md | 6 ++--- docs/design/plugin-contract.md | 4 ++-- docs/design/plugins/ContextFacts.md | 2 ++ docs/design/plugins/ContextProjection.md | 4 +++- docs/design/plugins/FileAccessFacts.md | 6 ++--- docs/design/plugins/RequestSettings.md | 4 ++-- docs/design/plugins/SessionScope.md | 24 ++++++++++++------- docs/design/plugins/SummaryStrategy.md | 2 ++ docs/design/resource-faces.md | 12 ++++++---- docs/design/service-faces.md | 2 ++ 10 files changed, 42 insertions(+), 24 deletions(-) diff --git a/docs/design/contracts/runtime-owner-operations.md b/docs/design/contracts/runtime-owner-operations.md index d670619cda..c654cc541a 100644 --- a/docs/design/contracts/runtime-owner-operations.md +++ b/docs/design/contracts/runtime-owner-operations.md @@ -21,10 +21,10 @@ | Goal → the target line's input owner | `line_owner::(line).submit(...)`; one validated atomic batch for the Goal record and trigger ([ADR 027](https://github.com/arcships/dim/pull/2029)). | | Branch-detail RPC → timelineTree | `line({line})` for the record and `read({line, …})` for the facts; there is no `display` operation. | | History RPC and line-read tools → timelineTree | `read({line, through, …})` at one cutoff, with the complete batches and the fixed head of an ended line; the reply carries the events or the selected fields. | -| Context RPC → target branch | `agentLoop.compact` and `contextUsage.read`. | +| Context RPC → target branch | `line_owner::(line).compact(...)` and `line_owner::(line).read(...)` ([ADR 027](https://github.com/arcships/dim/pull/2029)). | | Goal and Shell admission → timelineTree | `line({line})` returns the matching record or `unknown` ([TimelineTree](https://github.com/arcships/dim/pull/2092)). Goal reads ended history through `read` at the line's fixed head; writes retain the ended/unknown errors. | -| InputQueue and Collaboration approvals → target branch | `line_owner::(line).submit(...)`, `inputQueue.withdraw` after submission checks, and `approval.pending/decide` on the selected branch. | -| PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `contextUsage.read`, `prompt.adoptedConfiguration({}) → adopted configuration or null`. Report's own tree reads are [TimelineTree's](https://github.com/arcships/dim/pull/2092), not this row's. | +| InputQueue and Collaboration approvals → target branch | `line_owner::(line)`: `submit(...)` and `withdraw(...)` after submission checks; `line_owner::(line)`: `pending` and `decide`. | +| PromptSuggestion → ContextUsage; Report and Agent configuration → Prompt | `line_owner::(line).read(...)`, `line_owner::(line).adoptedConfiguration(...)`. Report's own tree reads are [TimelineTree's](https://github.com/arcships/dim/pull/2092), not this row's. | | Prompt and ToolBinding → `branchLifecycle` | `registerOpening(completion) → void`. Opening waits for admitted completions under its existing deadline and propagates their errors. | | Fault producers and Session observers → `sessionScope` | `reportFault(fault) → void`, `failure() → SessionFault or none`, `observeFault(listener) → id`, `release({leaseId}) → boolean`. The listener receives the current failure (none included) and later reports; the calling row's unload releases the observation. The first fault wins until a storage failure supersedes it ([SessionScope](../../../docs/design/plugins/SessionScope.md), #2093). | | Check providers and input admission → SubmitChecks | `register(name, check) → void`; `check({entry, branchId, user?, mode}, cancelled) → proceed{blocks, warnings} or block{message}`. Run in name order through the first block. Interrupted checks write nothing. | diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 1cd8034ff1..8302ab7e75 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -59,7 +59,7 @@ process (root) process parts: storage, catalogs, connections, Ag | --- | --- | --- | --- | | Process (root) | Host start | Host shutdown | — (process parts provide their own) | | Agent (`agent`) | Agents creates an Agent | Agent close, host shutdown | Host-internal | -| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionScope` ([SessionScope](plugins/SessionScope.md)); the branch group is reached by line id, not through a Session service | +| Session (`session`) | An Agent creates or restores a Session | Session close, idle unload | `sessionScope` ([SessionScope](plugins/SessionScope.md)); a Session's line directory is the TimelineTree part, and the branch group is reached by line id | | Branch (`branch`) | TimelineTree creates a branch | The branch ends, or its Session closes | `timeline`, `dispatcher`, `branchLifecycle`, `timelineIdentity` | Visibility follows the tree, as in [principles §2](../architecture/rust-agent/principles.md): @@ -67,7 +67,7 @@ Visibility follows the tree, as in [principles §2](../architecture/rust-agent/p | Direction | How | | --- | --- | | Up (an enclosing instance, the process) | Inject the service by name | -| Down (Session to branch) | `line_owner::(line)`: any branch-group data face by line id ([ADR 027](https://github.com/arcships/dim/pull/2029)); branch creation is `timelineTree.create`. Never by injecting a branch service | +| Down (Session to branch) | `line_owner::(line)`: any branch-group data face by line id ([ADR 027](https://github.com/arcships/dim/pull/2029)), except registration points and lifecycle services; branch creation is `timelineTree.create`. Never by injecting a branch service | | Sideways (sibling branches, other Sessions) | Not visible. Go through a common ancestor's business service, such as `sessions` | The scope roots, the facades and their publication rules are mechanisms. Each Session and branch is diff --git a/docs/design/plugins/ContextFacts.md b/docs/design/plugins/ContextFacts.md index e43a754858..c76aeac33d 100644 --- a/docs/design/plugins/ContextFacts.md +++ b/docs/design/plugins/ContextFacts.md @@ -104,6 +104,8 @@ The four operations hold no resource and wait for nothing; their rows cover only ## Exceptions with reasons +- A profile that does not install this owner has no `contextFacts` name; a part that requires it fails at assembly. Profiles that do not compact therefore omit both `contextFacts` and `summaryStrategy` rather than binding an absent value. + - `algorithm` is absent for a model whose count cannot be composed from contributions: reporting an algorithm it does not have would make `contributions` and `estimate` look available. - `estimate` takes the algorithm as data: a caller that saved contributions in a Timeline fact reads them back after a restart, and the saved algorithm is the only proof that the numbers share one rule. - `not_adopted` covers both a missing snapshot and a snapshot of another model: the caller's next step is the same, adopting the model again. diff --git a/docs/design/plugins/ContextProjection.md b/docs/design/plugins/ContextProjection.md index d1f99d96c8..b80f8d2ffd 100644 --- a/docs/design/plugins/ContextProjection.md +++ b/docs/design/plugins/ContextProjection.md @@ -34,7 +34,9 @@ Callers keep: let streamed = projection .rendered_stream(RenderedStreamRequest { through, batch: 256 }) .await?; -let request = settings.request(streamed.history.iter().map(|entry| entry.message.clone()).collect()); +let request = settings.request( + streamed.history.iter().map(|entry| std::sync::Arc::new(entry.message.clone())).collect(), +); ``` ```rust diff --git a/docs/design/plugins/FileAccessFacts.md b/docs/design/plugins/FileAccessFacts.md index c87e4dbaac..799f74f55f 100644 --- a/docs/design/plugins/FileAccessFacts.md +++ b/docs/design/plugins/FileAccessFacts.md @@ -72,7 +72,7 @@ let roots = access.workspace_roots(WorkspaceRoots { cwd }, cancelled).await?; | Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | -| `check` | The owner resolves the target, reads the owned file and the grants, and answers the facts | A dropped call ends the reads; nothing is decided | An in-flight call ends `closed` | The calling row; the owner holds no resource | +| `check` | The owner answers the facts for the caller's resolved path, reading the owned file and the grants | A dropped call ends the reads; nothing is decided | An in-flight call ends `closed` | The calling row; the owner holds no resource | | `workspaceRoots` | The owner resolves the cwd, returns the workspace and the managed worktree roots | A dropped call ends the read | `closed` | The calling row | ## Exceptions with reasons @@ -145,7 +145,7 @@ pub struct Check { #[derive(serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Facts { +pub struct FileFactsReply { pub workspace: bool, pub system: bool, pub owned: bool, @@ -183,7 +183,7 @@ impl PublicService for FileAccessFacts {} #[rutis::service(name = "fileAccessFacts")] impl FileAccessFacts { - pub async fn check(&self, request: Check, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn check(&self, request: Check, cancelled: CancelledFn) -> Result { /* ... */ } pub async fn workspace_roots( &self, request: WorkspaceRoots, diff --git a/docs/design/plugins/RequestSettings.md b/docs/design/plugins/RequestSettings.md index c3db24d339..f6d315aa35 100644 --- a/docs/design/plugins/RequestSettings.md +++ b/docs/design/plugins/RequestSettings.md @@ -9,7 +9,7 @@ The owner publishes the model settings a turn starts from: the Session's model s The owner publishes: - **The default settings value.** `{providerId, modelId, capabilitySnapshot?, config?, system?, metadata?}` derived once, when the Session is assembled, from the creation record and — when the profile has one — the model catalog. -- **The allowance repair.** The adopted output allowance is bounded by the model's declared output and half the window before the value is published; callers never recompute it. +- **The allowance repair.** The adopted output allowance is bounded by the model's declared output and half the window before the value is published. The same repair runs when Prompt adopts a configuration into `context/configured`, so Loop reads the adopted record and never recomputes it. Callers keep: @@ -69,7 +69,7 @@ None: the operation holds no resource and waits for nothing. ## Exceptions with reasons - `config` may already be the adopted allowance repair: the owner repairs the stored allowance against the declared limits, so a request started from this value cannot exceed the model's capacity. -- The value is fixed at creation: a model change during the run is a Timeline record (`context/configured`), and Loop reads that record; the value is never stale for its one use. +- The value is fixed at creation: a model change during the run is a Timeline record (`context/configured`) that Prompt wrote after repairing the allowance, and Loop reads that record; the value is never stale for its one use. - `metadata` carries the profile's static extensions. The per-request members — session, turn and request id — are Loop's: the aimux request log reads `requestId` from the request in flight, so the value cannot carry it. ## Verification diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index 3e9cc6bfc7..b272d341b9 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -8,7 +8,7 @@ SessionScope is the runtime's Session owner: the creation record and identity, t SessionScope owns: -- **The creation record.** The Session's mount list, working directory, model selection, system prompt, permission preset, collaboration role, interactive flag, language seed and initial title, fixed when the Session is built. Every member is fixed for the Session's whole life; a caller reads the live reply language from `sessionLanguage`, never from this value. +- **The creation record.** The Session's mount list, working directory, model selection, system prompt, permission preset, collaboration role, interactive flag, language seed, initial title and excluded tools, fixed when the Session is built. Every member is fixed for the Session's whole life; a caller reads the live reply language from `sessionLanguage`, never from this value. - **Identity.** The Session id and whether the Session was restored from the store. - **The phase.** Loading, Active, Closing, Closed, monotonic and never replaced by an earlier phase. `activated` and `closing` are the waits on the two transitions. - **Activity leases.** An accepted piece of work holds a lease so an idle release does not end the Session first. Every lease is bound to the calling row and the owner settles it at the row's unload, so no caller frees anything on an error path. `hold` answers an id for accepted work; the id is bound to the calling row and the owner settles it at the row's unload. A lease reports nothing and cancels nothing. @@ -105,7 +105,7 @@ self.nodes.insert(id, branch); SessionScope injects nothing. The assembly gives the owner its creation record and the Session anchor; the trusted host installs the content definitions the Session may mount. SessionScope no longer publishes the Agent's configuration, the Skills or Collaboration factory texts, or the names of the five host ports (`historyRenderer`, `contextModelHost`, `prepareModelHost`, `prepareContextHost`, `compactionStrategyHost`); those names leave the catalog (delivery). -The Session store constructs the Timeline engine and its Session-scope binding; SessionScope installs that binding in the Session instance and never hands it to a process caller. The operations are the engine's (#2018): the Session face publishes the per-line reads and the completion subscriptions, while `query` and `sessionConfig` stay on the process face `store` because an unloaded Session has no Session instance to host them. One engine, one operation set, one spelling per operation. +The Session store constructs the Timeline engine and its Session-scope binding; SessionScope installs that binding in the Session instance and never hands it to a process caller. The operations are the engine's (#2018): the Session face publishes the per-line reads and the completion subscriptions, while `query` and `sessionConfig` stay on the process face `store` because an unloaded Session has no Session instance to host them. On the Session face the Session id is the instance's identity: its requests carry no `sessionId`, and a request that names another Session is `invalid`. One engine, one operation set, one spelling per operation. ### Operations @@ -122,11 +122,11 @@ The Session store constructs the Timeline engine and its Session-scope binding; | `reportFault` | Record the fault that stopped the Session | `{fault}` | `{}` | None | None | | `failure` | The fault in force, if any | `{}` | `{fault?}` | None | None | | `mount` | Create a Session-owned content instance from a definition | `{group, definitionId, instanceData}` | `{instanceId}` | The caller drops the call; an instance it no longer waits for is shut down before the reply | `invalid`, `not_ready`, `cleanup`, `closed` | - -A registered Session extension definition must activate its instance rows; a host-added optional group keeps its optional rows, so a Pending row there is not `not_ready`. | `unmount` | Retire a content instance this Session owns | `{instanceId}` | `{}` | None; the owner completes the release | `unknown` when no live instance has the id; `cleanup`; `closed` | | `openBranch` (Rust-only, `#[rutis::service(skip)]`) | Construct a branch's runtime context for the branch tree | `{branchId, ancestors}` | the branch's runtime context (see Exceptions) | The caller drops the call; a construction the caller abandoned is shut down before the branch becomes visible | `closed`, `build` | +A registered Session extension definition must activate its instance rows; a host-added optional group keeps its optional rows, so a Pending row there is not `not_ready`. + `listener` is a callback by reference: it runs outside the owner's locks and outside the Timeline's commit lock. A lease id is an owner-issued token bound to the calling row; it carries no authority, the owner settles it at the row's unload, and a caller never has to free it on an error path. ### Errors @@ -147,13 +147,21 @@ A registered Session extension definition must activate its instance rows; a hos | Operation | Normal path | Caller cancels or unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | | `hold` | The owner checks the phase, increments the hold count and registers the lease under the calling row | The row's unload releases every lease the row still holds | No new lease is issued once an idle release is decided; an existing lease never delays a close | SessionScope | -| `observeFault` | The owner registers a listener under the calling row, calls it once with the fault in force (none included), then on every later report | The row's unload stops the listener and drops the registration | The listener stays until the generation unloads; a report after close is ignored | SessionScope; the listener's work by the calling row | +| `observeFault` | The owner registers a listener under the calling row, calls it once with the fault in force (none included), then on every later report | The row's unload stops the listener and drops the registration | The listener stays until the generation unloads; a report after close is still written to the record but reaches no new subscriber | SessionScope; the listener's work by the calling row | | `release` | The owner removes the lease or subscription and disposes it | A dropped call leaves the lease in place; the row's unload settles it | An id of an unloaded generation is `closed` | SessionScope | | `mount` | The owner creates the instance in the Session subtree, waits for its required rows, then answers the id | A dropped call shuts the half-made instance down; a definition that never activates is shut down and answers `not_ready` | New mounts are refused; in-flight mounts settle, and every instance is shut down when the Session scope unloads | SessionScope | | `unmount` | The owner shuts the instance down, propagates a shutdown failure as `cleanup`, and forgets the id | A dropped call does not cancel the shutdown | The Session's unload shuts down every remaining instance | SessionScope | | `openBranch` | The owner admits the id, waits for the branch scope and its required parts, and hands the context to the tree | A dropped call settles the half-made branch before it is visible | `closed` once the Session is closing; a Construction in flight settles or ends `closed` | SessionScope creates; TimelineTree holds and closes (Exceptions) | -### A branch's runtime context: the handover +#### Delivery mapping: the current instance errors + +`SessionInstanceError::Create` today covers both a caller's bad definition and a runtime creation failure; the delivery splits it into `invalid` (the group is outside the Session's subtree, the definition is unknown) and `not_ready` (the definition's row failed to activate, with the row and its state). `remove` silently succeeds for an unknown id today; the delivery makes a repeated `unmount` answer `{}` and an id this Session never issued `unknown`. + +### Flows not listed below + +`config`, `identity`, `phase`, `activated`, `closing`, `reportFault` and `failure` hold no resource. A call in flight when the Session closes answers its value or ends: `activated` answers `{active: false}`, `closing` returns, `failure` keeps the last recorded fault, and `reportFault` keeps writing to the record after close. + +## A branch's runtime context: the handover `openBranch` hands one object between two owners. Both cite [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md) for the scope tree, its close rights and the unload order, and [single-tree §Close](../../architecture/rust-agent/single-tree.md#关闭) for what a failed construction settles before its cause is reported. @@ -174,7 +182,7 @@ A registered Session extension definition must activate its instance rows; a hos - `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. - The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. - A fault listener that returns an error stops receiving: the owner drops the registration and the lease, and the fault record is unchanged. -- `identity` carries no version: the id and the restored flag are fixed at creation. +- `identity` carries no version: the id and the restored flag are fixed at creation. `failure` answers `{fault}` with the fault or none, matching the reply column. - A lease is a value, not a handle: it names nothing the caller can use except in `release`, and the owner releases every lease at the row's unload, so a caller that loses the id leaks nothing. `release` only lets an idle release happen sooner. - Content instance ids are the Session's, not the caller's: the Session's close shuts down every instance it mounted, so a part that never unmounts leaves obsolete content published until the Session ends, without breaking the owner. @@ -230,7 +238,7 @@ This contract replaces the Session-scope paragraphs and rows that state these na - `docs/design/resource-faces.md` §5: the `timelineStore` rows and the Session-scope sentence, now pointers to this contract; the engine and its process face remain #2018's. - `docs/design/plugin-contract.md`: the `sessionIdentity`, `sessionLifecycle`, `sessionConfig` and `agentConfig` rows of the named-services table, the `session` row of the scope table, and R2's needed names. -These documents still name the deleted Session services in dependencies; #2025's delivery updates them in the same change: `docs/design/session-typescript.md` (307, 320-322, 329, 373, 405, 470), `docs/design/contracts/session-boundary.md:560`, `docs/design/plugins/ShellInput.md:35`, `docs/design/plugins/Questions.md:50,575`, `docs/design/plugins/SessionTitle.md:75-76,126,408`, `docs/design/plugins/Collaboration.md:47,63`, `docs/design/plugins/Report.md:133`, `docs/design/plugins/Pursuit.md:46,184`, `docs/design/plugins/EventHub.md:399,597`, `docs/design/plugins/EnvironmentClients.md:155`, `docs/design/plugins/CodeMode.md:455` and `docs/design/thin-instances.md:281`. +These documents still name the deleted Session services in dependencies; #2025's delivery updates them in the same change: `docs/design/session-typescript.md` (307, 320-322, 329, 373, 405, 470), `docs/design/contracts/session-boundary.md:560`, `docs/design/contracts/session-access.md:566`, `docs/design/appserver/session-files.md:449`, the design-tree pages `ShellInput.md:35`, `Questions.md:50,575`, `SessionTitle.md:75-76,126,408`, `Collaboration.md:47,63`, `Report.md:133`, `Pursuit.md:46,184`, `EventHub.md:399,597`, `EnvironmentClients.md:155`, `CodeMode.md:455`, `thin-instances.md:281`, and the implementation pages `WorkspaceTools.md`, `Skills.md`, `ToolRegistry.md`, `PromptSources.md`, `PromptSuggestion.md`, `Questions.md`, `ShellInput.md`, `Prompt.md`, `Permission.md`, `Hooks.md`, `BranchTool.md`, `Attachments.md` and `TimelineTree.md`, which list `S:SessionConfig`, `S:SessionIdentity`, `S:SessionLifecycle` or `S:SessionLoader` as injected services. Rule D: no client wire protocol or user-visible behavior changes; every change here is plugin-facing. diff --git a/docs/design/plugins/SummaryStrategy.md b/docs/design/plugins/SummaryStrategy.md index 143bbe57ca..85e25ef3ac 100644 --- a/docs/design/plugins/SummaryStrategy.md +++ b/docs/design/plugins/SummaryStrategy.md @@ -95,6 +95,8 @@ A strategy failure after model work is the `failed` outcome with its diagnostics ## Exceptions with reasons +- A profile that does not compact installs neither this owner nor `contextFacts`; a part that requires `summaryStrategy` fails at assembly instead of reading an absent policy. + - `describe` and `compact` take the model selection as data and ask `contextFacts` for the limits: a model object in the input made the strategy hold another owner's counter, and a number in the input would freeze the capacity the request actually has. - `failed` is an outcome rather than an error: the compaction fact reports the same diagnostics as a completion, and the caller writes that fact either way. - `prior` carries the earlier pass of a re-planned compaction: the caller re-plans when the first pass does not fit, and the second pass must continue the same request budget. diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 7908fa5e30..c4520ff623 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -606,15 +606,17 @@ code the operation already uses, so one code vocabulary serves the local and the The repository and Timeline operations use two names on the daemon that owns the state: process `store` provides the repository operations (§5.2), retaining its existing Timeline `query`. -The Session-scoped `timelineStore` and its completion notifications are replaced by the -[SessionStore contract](https://github.com/arcships/dim/pull/2091) (#2018), which keeps the -operations, the request and reply shapes and the notification shape. Both use the existing state -owner; the split follows §9(6), without changing Session placement or the storage engine. +The Session-scoped `timelineStore` and its completion notifications keep their operations and +notification shape in the [SessionStore contract](https://github.com/arcships/dim/pull/2091) +(#2018); SessionScope only installs the binding in the Session instance. On the Session face the +Session id is the instance's identity, not a request field: a request that names another Session +is `invalid`. Both use the existing state owner; the split follows §9(6), without changing Session +placement or the storage engine. SessionTitle and FileAccess use the process repository operations in the [resource owner contract](contracts/resource-owner-operations.md). | Family | Operations | | --- | --- | -| Timeline (`timelineStore`) | Replaced by the [SessionStore contract](https://github.com/arcships/dim/pull/2091) (#2018); #2091 adds the operations and the completion shape back there. | +| Timeline (`timelineStore`) | The face stays and its owner is SessionStore; only the binding is installed in a Session instance ([SessionStore](https://github.com/arcships/dim/pull/2091), #2018). On the Session face the Session id is the instance's identity: the requests carry no `sessionId`, and a request that names another Session is `invalid`. | | Timeline completion (`timelineStore`) | Replaced by the [SessionStore contract](https://github.com/arcships/dim/pull/2091) (#2018). | | Session rows (`store`) | The repository operations listed in §5.2 | | Worktree association (`store`) | `associateWorktree`; [service faces](service-faces.md) §4.8 | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 9f2678ca56..c506c11ebb 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -299,6 +299,8 @@ loops.stop {sessionId, loopId} -> 记录形状,未结算时另带 {settled: fa ### 4.8 旧主机端口:`agentConfig` 等五个 +`agentConfig`、`skillsConfig` 与 `collaborationConfig` 三个面由 [SessionScope 契约](plugins/SessionScope.md) 取代(#2093):值是各自的安装函数提供的 `session_value`,面从目录移出;下面的形状只记录旧面。 + 这五个端口的内容是配置或一次写入:所有者把操作绑定到端口类型上,`#[rutis::service]` 生成 dispatcher,名字 shared;Rust 调用方直接调同一个方法,不另写适配层。`collaborationSession` 的审批目标读取由 [Collaboration owner](subagent-tool-approval.md#31-data-face) 定义。 ```text From d6ec09b3919c229caaa663e2a558469a95ad5891 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 19:13:27 +0800 Subject: [PATCH 18/19] docs(design): close the sixth-round review Allowance repair runs at the read boundary, including a restored Session replaying context/configured. The snapshot reads and the strategy outcome fields are named as the wire sends them, the projection note gives the real module path, and the architecture index no longer calls the projection Session-scoped. Refs #2025 --- docs/architecture/rust-agent/plugins/README.md | 5 +++-- docs/design/plugins/ContextProjection.md | 4 ++-- docs/design/plugins/RequestSettings.md | 4 ++-- docs/design/plugins/SessionScope.md | 2 +- docs/design/plugins/SummaryStrategy.md | 2 +- docs/design/resource-faces.md | 4 ++-- 6 files changed, 11 insertions(+), 10 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/README.md b/docs/architecture/rust-agent/plugins/README.md index accbb65f70..8c5c43d94e 100644 --- a/docs/architecture/rust-agent/plugins/README.md +++ b/docs/architecture/rust-agent/plugins/README.md @@ -20,8 +20,9 @@ runtime assembly and scripted model hosts: a newly assembled capability needs it entry here. Excluded rows can still appear as providers or consumers in the generated blocks. A service dependency is not necessarily a plugin with the same name. -The Session-scope owner contracts have no page here because their parts are infrastructure or -scripted rows: [SessionScope](../../../design/plugins/SessionScope.md), [Request settings](../../../design/plugins/RequestSettings.md), +The Session and branch owner contracts have no page here: they are owner parts of the Session, +branch and process scopes rather than plugins of the local-execution profile. See the design index +for [SessionScope](../../../design/plugins/SessionScope.md), [Request settings](../../../design/plugins/RequestSettings.md), [Context facts](../../../design/plugins/ContextFacts.md), [Context projection](../../../design/plugins/ContextProjection.md), [Summary strategy](../../../design/plugins/SummaryStrategy.md) and [File access facts](../../../design/plugins/FileAccessFacts.md) (#2025). diff --git a/docs/design/plugins/ContextProjection.md b/docs/design/plugins/ContextProjection.md index b80f8d2ffd..3b51aa16bc 100644 --- a/docs/design/plugins/ContextProjection.md +++ b/docs/design/plugins/ContextProjection.md @@ -106,7 +106,7 @@ else { - A fold at a cutoff returns the events that place context and the compaction in force, with positions that compare across the branch chain. - `renderedStream` releases each page and its reply carries no event list: a fold larger than one page keeps only the current projection. `renderedContext` materializes the events and is the inspection read. -- `snapshot` encodes the checkpoint of a completed compaction; a snapshot of another interpreter or a mismatched anchor is `invalid` or answers none. +- `snapshot` encodes the checkpoint of a completed compaction and answers `invalid` for another interpreter or a cut outside the chain; it never answers none. `snapshotFromCheckpoint` answers none when the anchor does not match. - `context_in` no longer exists; every read is the caller's own branch. - A call in flight when the branch closes ends `closed`. @@ -149,7 +149,7 @@ This contract replaces the `historyRenderer` value; the delivery in #2025 carrie Rule D: no client wire protocol or user-visible behavior changes; the streamed reply keeps the fields the callers use, and the model-visible text is unchanged. -Left to the upper layer: #2102's `PrepareRequest.projection` still names the internal `history::StreamedContext`. The wire types are `contextProjection::StreamedContext`, `contextProjection::Entry` and `contextProjection::History` as defined here; #2102 aligns its import to these names when it rebases on this contract. +Left to the upper layer: #2102's `PrepareRequest.projection` still names the internal `history::StreamedContext`. The wire types are `crate::context_projection::{StreamedContext, Entry, History}` as defined here; #2102 aligns its import to these names when it rebases on this contract. ## Binding appendix diff --git a/docs/design/plugins/RequestSettings.md b/docs/design/plugins/RequestSettings.md index f6d315aa35..eccf141f05 100644 --- a/docs/design/plugins/RequestSettings.md +++ b/docs/design/plugins/RequestSettings.md @@ -9,7 +9,7 @@ The owner publishes the model settings a turn starts from: the Session's model s The owner publishes: - **The default settings value.** `{providerId, modelId, capabilitySnapshot?, config?, system?, metadata?}` derived once, when the Session is assembled, from the creation record and — when the profile has one — the model catalog. -- **The allowance repair.** The adopted output allowance is bounded by the model's declared output and half the window before the value is published. The same repair runs when Prompt adopts a configuration into `context/configured`, so Loop reads the adopted record and never recomputes it. +- **The allowance repair, at the read boundary.** The adopted output allowance is bounded by the model's declared output and half the window at the point where Loop reads the value, including a restored Session that replays an older `context/configured` fact: the same rule runs on the replay path, so an allowance equal to or above the window never reaches the request. Prompt's repair at adoption may run too, but it is not the only place. Callers keep: @@ -69,7 +69,7 @@ None: the operation holds no resource and waits for nothing. ## Exceptions with reasons - `config` may already be the adopted allowance repair: the owner repairs the stored allowance against the declared limits, so a request started from this value cannot exceed the model's capacity. -- The value is fixed at creation: a model change during the run is a Timeline record (`context/configured`) that Prompt wrote after repairing the allowance, and Loop reads that record; the value is never stale for its one use. +- The value is fixed at creation: a model change during the run is a Timeline record (`context/configured`), and Loop reads that record through the same repair; the value is never stale for its one use. - `metadata` carries the profile's static extensions. The per-request members — session, turn and request id — are Loop's: the aimux request log reads `requestId` from the request in flight, so the value cannot carry it. ## Verification diff --git a/docs/design/plugins/SessionScope.md b/docs/design/plugins/SessionScope.md index b272d341b9..321ff2a8cc 100644 --- a/docs/design/plugins/SessionScope.md +++ b/docs/design/plugins/SessionScope.md @@ -179,7 +179,7 @@ A registered Session extension definition must activate its instance rows; a hos - `openBranch` hands out the branch's runtime context: an id would put branch runtime state behind a second set of operations owned by SessionScope, while ADR 002 D1 gives the directory and the close to TimelineTree, and the branch's whole capability machine runs behind that context. Ids, values and callbacks cannot carry it. §7 allows the object only with a lifecycle design both sides cite, and [lifecycle.md §1](../../architecture/rust-agent/lifecycle.md) is that design: the handover table above states who creates, holds and closes it and what either side's close means. - The Session-scoped `timelineStore` binding is assembly infrastructure: the store owns the engine and the operations, SessionScope installs the binding and states the spelling, and a process caller uses `store` (§2018's requirement). -- `config` is the persisted record's serde form: `interactive` is omitted when true because only the native store writes that form. A caller that decodes the value must treat absence as true; the live reply language is `sessionLanguage`, not this record. +- `config` is the creation snapshot, serialized from the persisted record: `interactive` is omitted when true because only the native store writes that form, so a caller that decodes the value treats absence as true. Its `language` is the creation seed; `session.language.update` rewrites the stored record in place and never this value, and the live reply language is `sessionLanguage`. - The failure record keeps only the first fault, and a storage failure supersedes a non-storage one: work that fails after the Session already stopped learns the original cause, not its own. - A fault listener that returns an error stops receiving: the owner drops the registration and the lease, and the fault record is unchanged. - `identity` carries no version: the id and the restored flag are fixed at creation. `failure` answers `{fault}` with the fault or none, matching the reply column. diff --git a/docs/design/plugins/SummaryStrategy.md b/docs/design/plugins/SummaryStrategy.md index 85e25ef3ac..aa158a73d9 100644 --- a/docs/design/plugins/SummaryStrategy.md +++ b/docs/design/plugins/SummaryStrategy.md @@ -221,7 +221,7 @@ pub struct CompactionRequest { } #[derive(serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", tag = "status")] +#[serde(rename_all = "camelCase", tag = "status", rename_all_fields = "camelCase")] pub enum StrategyOutcome { Completed { retain_from: String, diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index c4520ff623..e9ec1ae69a 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -657,7 +657,7 @@ notification {subscriptionId, batchId, branchId, through, result: "committed" | #### Binding shapes and lifecycle -The Timeline methods take one request object. Keys are `{sessionId, branchId}`; +The process store's Timeline engine methods take one request object. Keys are `{sessionId, branchId}`; `head` returns `{sequence}`, `branches {sessionId}` returns `{branches:[{info,sequence}]}`. `readPage {sessionId,branchId,after,limit,through}` returns `{events}`. `limit` is a target event count: the final complete atomic batch may exceed it. `readSegments {sessionId,segments: @@ -669,7 +669,7 @@ it does not introduce a separate wire operation or replace an override with fall `batchEnd {sessionId,branchId,sequence}` validates the boundary and returns `{}`; `batchEndAt` returns `{sequence}` for the containing batch's end through the backend's existing operation, without repeated remote probes. `trace` takes the same position and returns `{trace}`. -`query` takes the scope, query and optional page described in §5.2 and keeps that canonical reply. +`query` takes the scope, query and optional page described in §5.2 and keeps that canonical reply; on the Session-scoped binding, the request carries no `sessionId` because the instance identity supplies it. `createSession {sessionId,config}`, `releaseSession {sessionId}`, `rollbackSession {sessionId}` and `saveSnapshot {sessionId,branchId,snapshot}` return `{}`. `sessionConfig {sessionId}` returns From 4557d0b85a03932f4e9d2a8e335d11f42ea46763 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 19:31:29 +0800 Subject: [PATCH 19/19] docs(design): give the allowance repair one operation requestSettings gains repair({config?}) -> {config?}; Loop's read and a restored Session's replay call the same operation, so the bound cannot drift between the two paths. Refs #2025 --- docs/design/plugins/RequestSettings.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/docs/design/plugins/RequestSettings.md b/docs/design/plugins/RequestSettings.md index eccf141f05..4e9ed4e3af 100644 --- a/docs/design/plugins/RequestSettings.md +++ b/docs/design/plugins/RequestSettings.md @@ -137,12 +137,29 @@ pub struct RequestSettings { pub metadata: Option, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RepairRequest { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RepairReply { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config: Option, +} + impl PublicService for RequestSettings {} #[rutis::service(name = "requestSettings")] impl RequestSettings { pub fn settings(&self) -> RequestSettings { /* ... */ } + /// The one allowance rule: Loop calls it on the configuration it reads, and a + /// restored Session calls it on the replayed record before the first request. + pub fn repair(&self, request: RepairRequest) -> RepairReply { /* ... */ } } ``` -`ModelSelection` and the reply's members are `dim_agent_types` data; `settings` answers the value itself. Errors: this owner has none. +`ModelSelection` and the reply's members are `dim_agent_types` data; `settings` answers the value itself and `repair` answers the bounded configuration. Errors: this owner has none.