From 5d8eb8a78a14c742c6f19e92272de40202eceb20 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 14:29:54 +0800 Subject: [PATCH 01/19] docs(storage): define the session storage owners' target contracts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the target contracts for the four owners of the session storage board under design rules §7: SessionStore, SessionFiles, ManagedWorktrees and SqliteStorage. Each document has the responsibility split, the caller examples, the own contract with operations, errors and flows, the exceptions with reasons, the rule check and the requirements raised to mechanism owners. Refs #2018 Refs #2015 --- docs/design/plugins/ManagedWorktrees.md | 240 +++++++++++++++++ docs/design/plugins/SessionFiles.md | 248 ++++++++++++++++++ docs/design/plugins/SessionStore.md | 335 ++++++++++++++++++++++++ docs/design/plugins/SqliteStorage.md | 217 +++++++++++++++ 4 files changed, 1040 insertions(+) create mode 100644 docs/design/plugins/ManagedWorktrees.md create mode 100644 docs/design/plugins/SessionFiles.md create mode 100644 docs/design/plugins/SessionStore.md create mode 100644 docs/design/plugins/SqliteStorage.md diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md new file mode 100644 index 0000000000..97e75cb18d --- /dev/null +++ b/docs/design/plugins/ManagedWorktrees.md @@ -0,0 +1,240 @@ +# ManagedWorktrees + +Scope: process. Issue: #2018. + +ManagedWorktrees owns the managed worktree root, the task ids under it, the Git worktree and branch a creation makes, and the selection a prune offers. This document is the owner's target contract. The current implementation is described in [Managed worktrees](../worktree-management.md). The Session association and the directory record belong to SessionStore; this owner asks the store for those operations. + +## Use and scope: responsibility split + +ManagedWorktrees owns: + +- **The root.** `$DIMCODE_HOME/worktrees`, its canonical form and the rule that a managed directory is a plain directory under it. +- **Task ids.** Six lowercase base32 characters, unique under the root, allocated before the Session exists. +- **Git.** The worktree and branch a creation makes, the worktree registration, the removal and the prune. +- **The created value.** `{taskId, repository, root, subtree, branch, base}`: what a Session creation adopts or what a discard settles. +- **The preparation table.** Created but not yet adopted worktrees, by task id, for this generation. +- **Selection.** Which recorded directories a prune offers, which stay with a reason, and the re-check a removal repeats. + +Callers keep: + +- **When a Session starts in a new worktree.** `session.create` and `sessions.launch` decide; the caller passes the source workspace and the optional base and branch. +- **Session creation.** Writing the Session rows and the association is the store's `create`. +- **Operator confirmation.** The CLI shows the prune preview and sends the confirmed task ids. +- **Display.** The CLI renders the views and errors. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Make a managed worktree for a Session creation and learn the directory, subtree, branch and base | No: the root, the task id, the Git calls and the rollback are the owner's; a caller composing them would write a second creation path | `create` | +| Settle a created worktree that the Session creation did not adopt | No: the branch and base are the owner's, and the cleanup path must not be cancelled | `discard` | +| List managed worktrees with their branch, HEAD, content state and Session use | No: the view joins Git with the store's records and associations | `list` | +| Preview a prune: which directories are candidates and why the others stay | No: the age, keep and force rules and the re-checks are the owner's | `pruneSelection` | +| Remove one managed worktree | No: the removal needs the store's exclusion for the record and the owner's Git removal; a caller composing the two would hold the exclusion itself | `remove` | +| Remove an unregistered directory left by a failed creation | No: the directory has no record; the owner decides whether it is a plain managed directory and whether its content allows removal | `remove` with `taskId` | + +An operation exists only where its row says No. + +## Caller example + +Agents creates a worktree, writes the Session, and settles the worktree when the Session creation fails. + +```rust +let created = worktrees.create(Create { source, base, branch }, cancelled.clone()).await?; +match store.create(session_request(&created), cancelled.clone()).await { + Ok(()) => (), + Err(error) => { + worktrees.discard(Discard { task_id: created.task_id }, CancellationToken::new()).await?; + return Err(error); + } +} +``` + +The CLI previews a prune and removes the confirmed ids. + +```rust +let preview = worktrees.prune_selection(Prune { older_than_ms: Some(age), keep: None, force }).await?; +for candidate in confirmed(&preview) { + worktrees.remove(Remove { task_id: candidate.task_id, force }).await?; +} +``` + +## Own contract + +### Dependencies + +`store` for the directory records, the Session associations, the stored workspaces and the removal claim; `managementMethods` for the `worktree.*` client methods. Git is the owner's own process resource, started and reaped by this owner. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `create` | Allocate a task id and make a Git worktree and branch for a Session creation | `{source, base?, branch?}` | `{taskId, repository, root, subtree, branch, base}` | Between Git calls and before the branch is created; a cancelled creation removes its empty task directory | `unavailable`, `invalid`, `branch_exists`, `git`, `interrupted` | +| `discard` | Settle a created worktree that the Session creation did not adopt | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `in_use`, `git` | +| `list` | Managed worktrees with Git state and Session use | `{}` | `{worktrees}` | While the views are built | `unavailable`, `storage` | +| `pruneSelection` | Candidates a prune would delete and the kept ones with reasons | `{olderThanMs? , keep?, force}` | `{candidates, kept}` | While the selection is built | `invalid`, `unavailable`, `storage` | +| `remove` | Remove one managed worktree, or an unregistered directory, with its record | `{taskId, force}` | `{removed}` | Before the Git removal; after it starts the removal completes or reports `git` | `invalid`, `not_found`, `in_use`, `git`, `storage` | + +`create` returns a value; `discard` and `remove` take the task id. No object crosses. The preparation table is the owner's generation state: a reload drops it, and `discard` for a task id the generation did not create answers `unknown_preparation`; the directory is then an unregistered directory that `remove` handles. + +`remove` composes the store: `claimWorktree` (the record, the associations and the stored workspaces), the Git removal, then `settleWorktree` (delete the record on success, restore it on failure). The claim id is bound to this owner's calling row, so an unload restores the record. `force` overrides only the content check; the Git removal receives `--force` only then. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `unavailable` | The daemon has no managed root or the source is not a usable Git worktree; the caller refuses the worktree request | +| `invalid` | Fix the request: an unknown task id form, both or neither of older-than and keep, a path that is not a plain managed directory | +| `branch_exists` | The requested branch already exists; choose another branch | +| `not_found` | No recorded or unregistered directory has the task id | +| `in_use` | A Session still uses the directory, or its content is not removable without `force`; the caller reports the blocker | +| `git` | Git refused the operation; the caller reports the message and keeps the directory and the report | +| `interrupted` | The call was stopped; a creation's partial state is cleaned, a removal is retried | +| `unknown_preparation` | The preparation ended with the generation; the directory is unregistered and `remove` handles it | +| `storage` | A record read or write failed; the caller reports the failure and keeps the record | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `create` | Resolve the source and the Git roots, resolve the base, allocate a task id, `git worktree add -b`, canonicalize the root, check the subtree, return the value; the caller adopts it with `store.create` | Each Git call ends `interrupted`; an empty task directory this call made is removed; a created worktree is rolled back by the owner | The call ends `interrupted`; the rollback path runs | New calls are refused; an in-flight creation is rolled back or left as an unregistered directory | Git and the directory by ManagedWorktrees; the record by the store | +| `discard` | Look up the preparation, `claimWorktree`, Git removal, delete the branch, `settleWorktree` | No cancellation; the cleanup is the owner's | The preparation ends with the row; the directory is unregistered | The table drops with the generation; the directory stays unregistered | Directory and branch by ManagedWorktrees; record by the store | +| `list` | Read the records and associations, join Git state per directory, add unregistered directories | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | +| `pruneSelection` | `list`, then apply age, keep and force rules per candidate | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | +| `remove` | Resolve the record or the unregistered directory, `claimWorktree`, Git removal, `settleWorktree` | Before the claim or the Git removal; a started removal completes or reports `git` | The claim ends with the row; the record is restored | The claim drops with the store generation; the record stays for a retry | Directory by ManagedWorktrees; record by the store | + +A process death between `create` and `store.create` leaves an unregistered directory; `list` reports it and `remove` deletes it after the operator names the task id. A process death between the claim and the settle leaves the record; the next `list` reports the directory as missing or no longer registered, and `remove` cleans the record. + +## Exceptions with reasons + +- A branch is kept when `remove` deletes a worktree: committed content must not disappear with the directory. +- `discard` is not cancellable: a cancelled Session creation still has to settle what the owner made. +- Unregistered directories are never pruned: the owner has no record to age, so only an explicit `remove` by task id deletes them. +- Git is the owner's process resource: the owner starts each call, bounds it (10s read, 30s write) and reaps it on cancellation. + +## Verification + +Flow tests on the owner: + +- `create` makes a worktree and branch under the root; a taken task id or branch retries with a new task id; an explicit existing branch answers `branch_exists`; a cancelled creation leaves no created worktree and no empty task directory. +- `discard` removes a created worktree that no Session adopted; a Session association or a stored workspace keeps it and answers `in_use`; `unknown_preparation` after a generation change. +- `remove` deletes a recorded directory and its record; a directory with content refuses without `force`; a missing root deletes the record only; an unregistered directory with content refuses without `force`; a link is refused. +- `pruneSelection` never selects an unregistered, unknown, used or unremovable directory; `keep` treats an unknown use time as oldest; `olderThanMs` never selects an unknown time. +- A claim is restored when the calling row unloads; a settle after the claim ended answers `unknown_claim`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | ManagedWorktrees is one process part. It writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: the root, task ids and Git registrations outlive Sessions. | +| §3 orthogonality | The root and Git are this owner's; records are read through the store's operations. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handoff. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No Session policy in this owner; the caller decides when to create. | +| §4 rule 5 | No batches. | +| §4 rule 6 | No context input. | +| §4 rule 7 | Callers use these operations; no caller invokes Git or reads the root directly. | +| §4 rule 8 | No infrastructure change. | +| §4 rule 9 | No Timeline fact; a worktree is a process fact. | +| §7.2 ids and values | Task ids, paths and policies cross as data; the created value is data; no object crosses. | +| §7.2 one public face | The service is marked on the ManagedWorktrees type under the existing `managedWorktrees` name; the client methods `worktree.*` are registration points, not a second face. | +| §7.2 caller mechanisms | The root, Git, the preparation table and the claim stay inside the owner; callers handle the business errors only. | +| ADR 002 D1 | Process scope. | +| ADR 002 D2 | No wiring plugin; the `worktree.*` rows register methods, they do not own state. | +| ADR 002 D3 | Depends on the store for records; no lower handle. | +| ADR 002 D4 | The root is structural configuration; no business setting. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None new. The store's `claimWorktree` and `settleWorktree` are defined in [SessionStore's contract](SessionStore.md); the `managementMethods` registration point is the existing mechanism. + +## Binding appendix + +The service is marked on the owner type; the wire name stays `managedWorktrees`. `CancelledFn` is the binding's cancellation argument. + +```rust +use dim_agent_capabilities::host::CancelledFn; +use dim_agent_runtime::PublicService; +use rutis::Ctx; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Created { + pub task_id: String, + pub repository: String, + pub root: String, + pub subtree: String, + pub branch: String, + pub base: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Discard { + pub task_id: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Remove { + pub task_id: String, + pub force: bool, +} + +#[derive(Debug, thiserror::Error)] +pub enum WorktreeError { + #[error("{0}")] + Unavailable(String), + #[error("{0}")] + Invalid(String), + #[error("{0}")] + BranchExists(String), + #[error("{0}")] + NotFound(String), + #[error("{0}")] + InUse(String), + #[error("{0}")] + Git(String), + #[error("{0}")] + Interrupted(String), + #[error("{0}")] + UnknownPreparation(String), + #[error("{0}")] + Storage(String), +} + +impl PublicService for ManagedWorktrees {} + +#[rutis::service(name = "managedWorktrees")] +impl ManagedWorktrees { + pub async fn create( + &self, + caller: &Ctx, + request: Create, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn discard( + &self, + caller: &Ctx, + request: Discard, + cancelled: CancelledFn, + ) -> Result<(), WorktreeError> { + // ... + } + + pub async fn remove( + &self, + caller: &Ctx, + request: Remove, + cancelled: CancelledFn, + ) -> Result { + // ... + } +} +``` + +`list` and `pruneSelection` follow the same shape, with the views and the prune selection as reply data. diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md new file mode 100644 index 0000000000..565e2a92e0 --- /dev/null +++ b/docs/design/plugins/SessionFiles.md @@ -0,0 +1,248 @@ +# SessionFiles + +Scope: process. Issue: #2018. + +SessionFiles owns the bytes of Session files and the ownership rows that make a path or a file id belong to a Session. This document is the owner's target contract. The current implementation is described in [Session files](../appserver/session-files.md). The engine's row operations this owner uses are private to the storage crate; the Session store uses this owner when a delete releases files. + +## Use and scope: responsibility split + +SessionFiles owns: + +- **The file namespace.** One immutable file per `fileId` under `.session-files//`, written through FileStorage. +- **The write generation.** One generation per store generation. A write reserves its name, the bytes land, and the ownership row commits only in the same generation that reserved it. +- **The sweep.** Removes files no row owns, rows pending under a dead generation, and directory entries with no row. +- **Ownership rows.** Which Session owns a Session file and which Session owns a registered output path. +- **Path mapping.** An output path is a path; a Session file path is a file id inside the owner's directory. The owner resolves between them. + +Callers keep: + +- **The purpose of the file.** An attachment, an image sent to a model, a tool result, an event payload, a command output path. +- **The name** the caller gives a stored file, within the owner's component rule. +- **The model's content rules.** Image budgets, request materialization and what reaches the model stay with the model provider. +- **The tool result.** What a registration means for the user stays with the tool. +- **The output directory.** WorkspaceTools owns the output path and its policy. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Store produced bytes under a new file id for a Session | No: the reservation, the file write and the ownership commit are one ordered protocol; a caller composing them would drive a half transaction | `put` | +| Import a host file the user or model named as a Session file | No: the source is outside the file namespace and the size limit must stop the copy before it lands | `import` | +| Read a Session file for a model request or a UI | No: the caller cannot read the owner's directory or the file id's row | `read` | +| Record a command output path as owned by the Session | No: ownership is the owner's row and the path must stay inside the Session's output directory | `register` | +| Answer whether a path or file id belongs to the Session | No: the answer composes two ownership tables and the file directory mapping | `owns` | +| List every path the Session owns, for deletion or for a grant | No: the caller has no row access | `ownedPaths` | + +An operation exists only where its row says No. + +## Caller example + +WorkspaceTools registers a command output path. + +```rust +files.register(Register { session_id, path }, cancelled).await?; +``` + +ImageUnderstanding and the model provider read a file for one request. + +```rust +let stored = files.read(ReadFile { session_id, file_id }, cancelled.clone()).await?; +``` + +Attachments import a host file the user chose. + +```rust +let stored = files.import(Import { session_id, name, source }, cancelled).await?; +``` + +## Own contract + +### Dependencies + +`fsHost` for the owner's directory, file creation, atomic replacement, import, listing and removal; the operations used are the ones in [FileStorage's contract](FileStorage.md). The engine's file-ownership rows are private to the storage crate and are not a service. The owner does not depend on `store`: the store depends on this owner when a delete releases files. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, bytes}` | `{fileId, size}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, size}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `read` | Read one Session file whole, within the owner's limit | `{sessionId, fileId}` | `{bytes}` | While the file is read; nothing changes | `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `register` | Record an output path as owned by the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `storage` | +| `owns` | Whether a path or file id belongs to the Session | `{sessionId, path}` | `{owned}` | While the path is resolved | `node_unavailable`, `cancelled`, `storage` | +| `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `node_unavailable`, `storage` | + +`bytes` is the file content as data; the owner's limit is 16 MiB. `read` answers the whole file within that limit: the limit is the owner's, so callers do not page. A `fileId` outside the Session, or a name that is not one component, is `invalid`. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | Fix the input: a name that is not one component, a relative or non-file import source, a path outside the Session's output directory | +| `too_large` | Treat the file as not storable; store a smaller representation or refuse the attachment | +| `not_found` | The Session has no such file, or the Session no longer exists; the caller refuses the request | +| `node_unavailable` | The Session's resource node cannot be reached; retry later or report the node as unavailable | +| `cancelled` | Nothing was committed; the caller stops | +| `closed` | This generation is unloading; call the replacement generation | +| `storage` | The store or the file system failed; the caller reports the failure and keeps its own copy | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `put` | Reserve the file under the generation, write the bytes through FileStorage, commit the ownership row while the generation and the Session still exist | The reservation and the written bytes are abandoned; the sweep removes them; no owned row | The write completes under the owner's task, or the reservation expires with the generation; the sweep removes unowned bytes | Admission stops; admitted writes finish; a new generation sweeps the old one's pending rows | FileSystem by FileStorage; rows and sweep by SessionFiles | +| `import` | Open the source, check size, copy through FileStorage into a temporary file, commit ownership | The temporary file is removed; no owned row | The copy completes or is abandoned; the sweep removes what no row owns | As `put` | Source and temporary file by FileStorage; rows by SessionFiles | +| `read` | Resolve the file id under the generation's directory, read the bytes within the limit | The read stops; nothing changes | The read stops | Pending reads end `closed` | FileStorage | +| `register` | Check the Session and the output directory, insert the ownership row | None | The row stays; a later Session delete removes it | Rows stay for the next generation | SessionFiles | +| `owns` | Resolve the path, check the output row, else map the file directory and the file id row | The resolution stops | Nothing to release | Pending calls end `closed` | SessionFiles | +| `ownedPaths` | Read both ownership rows, map file ids to the directory | None | Nothing to release | Rows stay | SessionFiles | + +A Session delete releases this owner's rows before the sweep runs; the sweep deletes bytes no row owns. Files another Session owns are never removed by one Session's delete. + +## Exceptions with reasons + +- The file directory is below the database directory: a Session's files are removed with the store that owns their rows, and the delete's last-owner guard is scoped to one database (ADR 013). +- The generation is the store's generation: a stale writer cannot commit into a Session that a newer store generation created. +- `read` answers the whole file within the owner's 16 MiB limit instead of paging: every caller needs the whole file, and a page protocol would push the read id's lifetime to callers. +- The ownership rows live in the engine's database but belong to this owner: the engine executes the transaction, SessionFiles decides when it commits. + +## Verification + +Flow tests on the owner: + +- `put` reserves, writes and commits; a cancelled put leaves no owned row and the sweep removes the bytes; a second put with the same name gets a new file id. +- `import` refuses a directory, a non-regular file and a source over the limit without landing anything. +- `read` answers `not_found` for another Session's file id and for an unknown id; a file over the limit is never stored. +- `register` refuses a path outside the output directory; `owns` answers true for a registered output and for a Session file path, and false for another Session's file. +- A Session delete releases the rows; the sweep removes the bytes; a file still owned by another Session survives. +- A generation close stops admission; a new generation sweeps pending rows and directory entries without rows. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | SessionFiles is one process part. It writes no Timeline fact and is not a Capability. | +| §2 scopes | Process: the bytes and rows outlive Sessions; callers are process or Session parts. | +| §3 orthogonality | The file namespace and the ownership rows are this owner's; other owners read them through the operations. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handoff. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No Session or model policy. | +| §4 rule 5 | No batches. | +| §4 rule 6 | File content reaches the model only through the model provider's request; SessionFiles returns bytes to the owner that asked. | +| §4 rule 7 | Callers use these operations; no caller reads a generation or a directory entry. | +| §4 rule 8 | No infrastructure change; requirements below. | +| §4 rule 9 | No Timeline fact. | +| §7.2 ids and values | File ids, names and bytes cross as data; a `fileId` is the resource id. | +| §7.2 one public face | The service is marked on the file owner's type under the existing `sessionFiles` name; the `SessionFiles` wrapper type and the `SessionFilesService` trait do not exist beside it. | +| §7.2 caller mechanisms | The reservation, the generation and the sweep stay inside the owner; callers handle the business errors only. | +| ADR 002 D1 | Process scope: the namespace and the rows outlive Sessions. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | The owner depends on `fsHost`; callers depend on `sessionFiles`. | +| ADR 002 D4 | The 16 MiB limit is the owner's; no business setting. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. **FileStorage (#2016): the operations this owner calls.** `root_path`, `create_directory`, `write` with the read-only permission, `import` with `max_bytes` and the read-only permission, `list`, `remove`, `read`. [FileStorage's contract](https://github.com/arcships/dim/pull/2080) defines all of them; this contract raises no new need. +2. **Service type placement (#2015): a process owner in the app server.** The owner type is in `dim-app-server`, where the engine and the rows are; callers in plugin crates cannot depend on the app server. The request and reply types are plain data in `dim-agent-capabilities::host`, and callers outside the crate call the operations by the `sessionFiles` name. If the maintainers decide every process face must be annotated on a type plugin crates can name, the type moves to a shared crate; a comment on #2015 states the requirement. + +## Binding appendix + +The service is marked on the file owner's type; the wire name stays `sessionFiles`. The `SessionFiles` wrapper and `SessionFilesService` no longer exist. `CancelledFn` is the binding's cancellation argument. + +```rust +use dim_agent_capabilities::host::CancelledFn; +use dim_agent_runtime::PublicService; +use rutis::Ctx; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredFile { + pub file_id: String, + pub size: u64, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FileBytes { + pub bytes: String, // base64 text +} + +#[derive(Debug, thiserror::Error)] +pub enum SessionFileError { + #[error("{0}")] + Invalid(String), + #[error("{0} is over the Session file limit")] + TooLarge(String), + #[error("no such file: {0}")] + NotFound(String), + #[error("the resource node is unavailable: {0}")] + NodeUnavailable(String), + #[error("the call was cancelled")] + Cancelled, + #[error("the file service is unloading")] + Closed, + #[error("{0}")] + Storage(String), +} + +impl PublicService for SessionFiles {} + +#[rutis::service(name = "sessionFiles")] +impl SessionFiles { + pub async fn put( + &self, + caller: &Ctx, + request: Put, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn import( + &self, + caller: &Ctx, + request: Import, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn read( + &self, + caller: &Ctx, + request: ReadFile, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn register( + &self, + caller: &Ctx, + request: Register, + cancelled: CancelledFn, + ) -> Result<(), SessionFileError> { + // ... + } + + pub async fn owns( + &self, + caller: &Ctx, + request: Owns, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn owned_paths( + &self, + caller: &Ctx, + request: OfSession, + cancelled: CancelledFn, + ) -> Result { + // ... + } +} +``` + +`SessionFiles` is the current `files::SessionFiles` owner type; the wrapper named `SessionFiles` in `dim-agent-capabilities` is deleted, not renamed. Every operation takes one request object, one reply object and the caller's `Ctx`; only the operations that wait take `CancelledFn`. diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md new file mode 100644 index 0000000000..60e53ebccd --- /dev/null +++ b/docs/design/plugins/SessionStore.md @@ -0,0 +1,335 @@ +# SessionStore + +Scope: process. Issue: #2018. + +SessionStore owns the stored Session: its rows, its grants, its reply language, its title revision, its worktree records, the exclusion that keeps those records consistent with Session creation, and the Timeline storage engine those rows are read through. This document is the owner's target contract. The current implementation is described in [Session rows §5.2](../resource-faces.md#52-session-rows) and [Native storage format](../appserver/native-storage-format.md). The Session-scoped `timelineStore` face is published by SessionScope and is not covered here; the requirement this contract raises for it is at the end. + +## Use and scope: responsibility split + +SessionStore owns: + +- **The Session row set.** `agent_sessions`, `session_owners`, the main branch record, the catalog row and the Timeline rows that make a stored Session. Creation writes them in one transaction; deletion removes them in the owner's order. +- **Session grants.** The stored path, kind and mode set, with the rule that a read grant never downgrades a write grant. +- **The stored reply language.** One member of the stored configuration record. +- **Title revisions.** The revision counter and the stored title value, one writer at a time, announced after commit. +- **Worktree records.** A recorded directory, its last-use time and the Session associations that point into it. +- **The Session exclusion.** One lock that keeps creation, fork, deletion, association and worktree removal from observing each other's partial state. +- **The Timeline storage engine.** The admitted batch queue, the grouped commit, paging, snapshots and release, executed over the Session rows. `timelineStore` publishes the same engine per Session; the Session face belongs to SessionScope. + +Callers keep: + +- **Admission and lifecycle.** Who may create, when a Session closes before deletion, which protocol version a creation uses and which features it may carry. +- **Fork policy.** The source role, the cut and the rest point, the context boundary and the removal of `initialTitle` from the configuration text the caller supplies. +- **Grant meaning.** Which path a user allowed, and how a path is resolved and presented. +- **Title text.** SessionTitle decides the text, the operator's length rule and when to write. +- **Worktree policy.** ManagedWorktrees decides the root, task ids, Git calls, what a prune selects and whether an operator confirmed it. +- **Catalog enrichment.** Agents adds live sequence and closed state to the stored page. +- **Business errors above this owner.** A caller maps a stored-state refusal to its own business error. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Create an admitted Session and its optional worktree association | No: the rows, the owner row, the main branch, the catalog row and the association are one transaction; a partial write would publish a Session without its rows or an association without its Session | `create` | +| Close a Session, then remove its output directories and rows | No: output removal, visible rows and Timeline rows must run under the Session exclusion and in this order; a caller composing them could delete a row a concurrent creation still names | `delete` | +| Copy a source Session's rows at a cut with the source's exact configuration text | No: the copy is bounded transactions; parsing and re-serializing the text would change bytes | `fork` | +| Read a stored Session's creation origin and leader link for an attach reply | No: the caller has no row access | `creationRecord` | +| Read the Agent that owns a stored Session before its delete notice | No: the caller has no row access | `owner` | +| Ask whether an id has stored rows without loading a Session | No: the check spans five tables | `hasRecords` | +| Read a stored Session's configuration without loading the Session | No: the caller has no row access and must not parse a stored record | `sessionConfig` | +| Read the configuration text a fork copies | No: the text must be copied byte for byte | `sessionConfigText` | +| List stored Sessions as one page, filtered and ordered by the storage contract | No: the page is a consistent read over the catalog row, the Session row and the title | `catalog` | +| Read an unloaded Session's history | No: the caller has no Timeline row access | `query` | +| Read the Session's grants | No: the caller has no row access | `grants` | +| Add or remove one grant | No: the upsert rule that keeps a write grant is the owner's invariant | `addGrant`, `removeGrant` | +| Write the reply language into the stored configuration | No: the caller must not rewrite the stored record | `setLanguage` | +| Read the title and its revision | No: the caller has no row access | `title` | +| Write a title under its expected revision and announce the commit | No: the revision check, the single writer and the post-commit notice are the owner's | `setTitle` | +| Record a verified worktree directory and the Session's subtree | No: the directory record, the association and the last-use time are one commit | `associateWorktree` | +| List recorded worktree directories or their Session associations, or learn which stored Sessions have a workspace under a root | No: the caller has no row access | `worktrees`, `worktreeUsages`, `sessionsUnder` | +| Remove one recorded worktree together with its directory | No: the association and workspace checks, the physical removal and the record deletion must not interleave with a Session creation that would point into the removed root | `claimWorktree`, `settleWorktree` | + +An operation exists only where its row says No. + +## Caller example + +Agents creates a Session; admission, protocol checks and the worktree creation happened before the call. + +```rust +// `prepared` is the value ManagedWorktrees.create returned. +store.create(Create { + id, config, agent_id, protocol_version, leader: None, origin, worktree: prepared, +}, cancelled).await?; +``` + +Agents forks and deletes; both mistakes are the caller's to fix, and a concurrent deletion is not an error the caller retries. + +```rust +let source_text = store.sessionConfigText(ForkSource { id: source }, cancelled.clone()).await?; +store.fork(Fork { source, id: fork, at, config_text: source_text.config_text }, cancelled).await?; +let removed = store.delete(Delete { id }, cancelled).await?; +``` + +SessionTitle reads the revision, writes one revision later and announces the commit inside the owner. + +```rust +let current = store.title(TitleRead { id }, cancelled.clone()).await?; +// A conflict means another writer committed a revision first; the title text is recomputed. +let next = store.setTitle(SetTitle { id, expected_revision: current.revision, title }, cancelled).await?; +``` + +ManagedWorktrees removes a directory: the claim holds the exclusion, Git removes the root, the settle deletes or restores the record. + +```rust +let claim = store.claimWorktree(Directory { repository, root }, cancelled.clone()).await?; +match git_remove(&root, force, cancelled).await { + Ok(()) => store.settleWorktree(Settle { claim: claim.claim_id, removed: true }, cancelled).await?, + Err(error) => { + store.settleWorktree(Settle { claim: claim.claim_id, removed: false }, CancellationToken::new()).await?; + return Err(error); + } +} +``` + +## Own contract + +### Dependencies + +The engine's data face `sqliteStorage` for every row read and write and for the Timeline batches. The file owner `sessionFiles` for the Session file steps a delete releases. Neither dependency crosses back into SessionStore. The assembly provides both; deployment chooses the instance. + +### Operations + +Every operation takes one request object and answers one reply object. Writes are one transaction or one ordered settlement and are not cancelled once they start: a dropped future does not undo committed rows. Reads take the caller's cancellation token where the read can wait on a long page or a long history. + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `create` | Write one admitted Session and its optional worktree association | `{id, config, agentId, protocolVersion, leader?, origin, worktree?}` | `{}` | Before the transaction starts; a dropped future does not undo a commit | `invalid`, `workspace_missing`, `storage` | +| `delete` | Remove a closed Session's output, visible rows and Timeline rows | `{id}` | `{hadRows}` | Before the first step; after the first commit the steps run to their end | `storage` | +| `fork` | Copy a source's rows at a cut with the supplied configuration text | `{source, id, at, configText}` | `{}` | Before the first transaction | `invalid`, `storage` | +| `creationRecord` | One Session's origin and leader link | `{id}` | `{origin, leader?}` | None | `not_found`, `storage` | +| `owner` | The Agent that owns a stored Session | `{id}` | `{agentId?}` | None | `storage` | +| `hasRecords` | Whether an id has any stored row | `{id}` | `{exists}` | None | `storage` | +| `sessionConfig` | A stored Session's decoded configuration | `{id}` | `{config?}` | None | `not_found`, `storage` | +| `sessionConfigText` | A stored Session's configuration text, byte for byte | `{id}` | `{configText?}` | None | `not_found`, `storage` | +| `catalog` | One stored Session page | `{request, agent?, version, hosts, closed}` | the stored page | While the page is read | `invalid`, `cancelled`, `storage` | +| `query` | One consistent history read for an unloaded Session | `{scope, query, page?}` | the query result | While the page is read | `storage`, `cancelled` | +| `grants` | The Session's grant set | `{id}` | `{grants}` | None | `storage` | +| `addGrant` | Add one grant, never downgrading a write grant | `{id, path, kind, mode}` | `{}` | None | `not_found`, `invalid`, `storage` | +| `removeGrant` | Remove one grant; an absent grant counts as removed | `{id, path}` | `{}` | None | `storage` | +| `setLanguage` | Write the reply language into the stored configuration | `{id, language?}` | `{}` | None | `not_found`, `invalid`, `storage` | +| `title` | The title and its committed revision | `{id}` | `{revision, title?}` | None | `not_found`, `storage` | +| `setTitle` | Commit a title as the next revision and announce it | `{id, expectedRevision, title?}` | `{revision}` | The reply may be dropped; the admitted write is not cancelled | `not_found`, `conflict`, `storage` | +| `associateWorktree` | Record a verified directory and the Session's subtree in one commit | `{id, repository, root, subtree}` | `{}` | None | `not_found`, `invalid`, `storage` | +| `worktrees` | Recorded directories, with their last use when known | `{}` | `{directories}` | None | `storage` | +| `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `storage` | +| `sessionsUnder` | Stored Sessions whose workspace is a root or lies under it | `{root}` | `{sessionIds}` | None | `invalid`, `storage` | +| `claimWorktree` | Claim one recorded directory for removal under the Session exclusion; the claim id is bound to the calling row | `{repository, root}` | `{claim}` | Before the claim is written | `not_found`, `in_use`, `invalid`, `storage` | +| `settleWorktree` | End a claim: delete the record when the directory is gone, restore it otherwise | `{claim, removed}` | `{}` | None; the owner completes the settlement | `unknown_claim`, `storage` | + +`worktree` in `create` and `associateWorktree` is `{repository, root, subtree}`: absolute UTF-8 paths, `subtree` inside `root`. The caller passes paths it already resolved; the owner re-checks that each is absolute, UTF-8 and, for an association, that the root still is a directory. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | Fix the request: an id that is not one path component, a relative or non-UTF-8 path, a subtree outside the root, an unknown language code, an invalid catalog cursor | +| `workspace_missing` | The creation's `cwd` no longer is a directory; the caller reports the failed creation and discards the worktree | +| `not_found` | No stored Session has the id; the caller decides whether that is a business error or an answer | +| `conflict` | Another title write committed first; re-read `title` and decide | +| `in_use` | A Session association or a stored workspace still names the directory; delete that Session or refuse the removal | +| `unknown_claim` | The claim ended (the calling row unloaded, the owner reloaded, or another settlement ran); the directory state must be inspected before a retry | +| `cancelled` | The caller stopped the read; nothing changed | +| `closed` | This generation is unloading; call the replacement generation | +| `storage` | The store failed; the caller reports the failure and keeps the Session or worktree for a retry | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `create` | Validate the id and the workspace, take the exclusion, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller's row cannot use a Session it did not learn the id of, and a retry is a new id | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | +| `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove visible and Timeline rows, schedule the file sweep | Before the first commit: every row stays. After: the steps run to their end | The work continues under the owner's task; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | +| `fork` | Take the exclusion, copy in bounded transactions, write the target row with the supplied text, commit | Before the first copy | The copy continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | +| `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `sessionConfigText`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | +| `catalog`, `query` | One consistent read under the caller's token | The read stops; no partial page | Nothing to release | Pending reads end `cancelled` | SessionStore | +| `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | +| `setTitle` | Admit the write under the owner's admission, run it as the owner's task, commit, announce, answer the revision | Dropping the reply never cancels the admitted write | The admitted write completes and announces | Close stops admission, waits for every admitted write | SessionStore | +| `claimWorktree` | Check associations and stored workspaces, mark the record claimed under the exclusion, bind the claim to the calling row | Before the mark | The owner restores the record and ends the claim | Claims are generation state: a reload drops them and restores the records | SessionStore | +| `settleWorktree` | End the claim; `removed` deletes the record, otherwise the record stays | None; the owner completes | Nothing to release | Pending settlements end `closed` | SessionStore; the directory by ManagedWorktrees | + +## Exceptions with reasons + +- `create` and `fork` take the caller's already-validated configuration and the fork text: validating the protocol, the collaboration role and the cut belongs to the Session lifecycle owner, and re-serializing the text would change bytes. +- `delete` does not close the Session, remove its Agent admission slot or remove the worktree: closing is Agents', and a managed worktree is removed by ManagedWorktrees under `claimWorktree`. +- `setTitle` hands the write over at admission: the reply may be lost, so the caller re-reads rather than assumes failure. +- `claimWorktree` and `settleWorktree` are two operations because the physical removal is ManagedWorktrees' resource: the claim is the store's exclusion state, not a handle; the id is bound to the calling row, so an unload restores the record instead of leaving it claimed. +- `owner` answers the Agent id for a delete notice; the Agent directory's own records are not returned here. + +## Verification + +Flow tests on the owner: + +- `create` writes the Session, the owner, the main branch, the catalog row and the worktree association together; a failed association writes nothing. +- `delete` removes output first, then the rows; a failure before the first commit leaves every row; a concurrent creation cannot associate with a directory whose record is claimed. +- `fork` copies the supplied text unchanged and never parses it. +- `addGrant` on a missing Session answers `not_found`; `removeGrant` on an absent grant answers success; a read grant never downgrades a write grant. +- `setTitle` with a stale revision answers `conflict`; a dropped reply still commits and announces; close waits for the admitted write. +- `claimWorktree` answers `in_use` while an association or a stored workspace remains; a claimed directory refuses creation and association; an unloaded caller restores the record; `settleWorktree` with `removed: false` keeps the record. +- A call in flight when the generation closes ends `closed`; claims do not survive the generation. + +Material uncertainty: the claim's lifetime when the daemon process dies between claim and settle is recorded only in memory; the record survives, the directory state is Git's, and a later `worktrees`/`remove` reconciles the pair. Review checks that no caller treats `unknown_claim` as success. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | SessionStore is one process part. It writes no Timeline fact and folds no state; it is not a Capability. | +| §2 scopes | Process: the Session rows outlive Sessions and are shared across them. Callers are process or Session parts. | +| §3 orthogonality | The Session rows and records are SessionStore's; other owners' rows are read through their own faces, not here. | +| §4 rule 1 | No command event: creation and deletion write no Timeline fact of their own. | +| §4 rule 2 | No handoff: the row set and the records stay with SessionStore. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | Core and assembly carry no Session policy; the contract has no protocol or feature rule. | +| §4 rule 5 | Deletion and fork keep their bounded transactions and their order. | +| §4 rule 6 | No context input. | +| §4 rule 7 | Callers use these operations; no caller reads a row, a writer generation or a lock. | +| §4 rule 8 | No infrastructure change; requirements are listed below. | +| §4 rule 9 | The store publishes no Timeline fact of its own; the attached worktree stays a process fact. | +| §7.2 ids and values | Requests and replies are data; the worktree value and the claim id cross, no object does. | +| §7.2 one public face | The service is marked on the SessionStore type under the existing `store` name; `Store`, `SessionMetadata` and `WorktreeAssociations` do not exist beside it. | +| §7.2 caller mechanisms | The exclusion, the title admission and the claim lifetime stay inside the owner; callers handle business errors only. | +| ADR 002 D1 | Process scope: the Session row set and its records outlive a Session. | +| ADR 002 D2 | No wiring plugin: one service on the owner type. | +| ADR 002 D3 | Dependencies point to the engine and the file owner; no caller holds a lower handle. | +| ADR 002 D4 | No business configuration. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. **SessionScope (#2025): one spelling for the Timeline reads.** `store.query` and `store.sessionConfig` read the same engine as the Session-scoped `timelineStore`'s `query` and `sessionConfig`. The engine has one operation set; publish it once. The process read must stay reachable for an unloaded Session, so the contract asks SessionScope to state which face owns which operation and to remove the duplicate name. Probe: `store.query` and `timelineStore.query` return the same result for the same scope and through; a caller outside a Session uses the process operation. +2. **SessionScope (#2025): the `timelineStore` binding.** SessionStore constructs the engine and the Session-scope binding; the binding is assembly infrastructure. The contract assumes SessionScope owns the binding's installation and does not hand the binding to a process caller; a comment on #2025 states the requirement. + +## Binding appendix + +The service is marked on the `SessionStore` type; the wire name stays `store`. `Store` the wrapper, `SessionMetadata` and `WorktreeAssociations` no longer exist. `caller: &Ctx` is rutis's caller parameter: the dispatch fills it from the calling row, so a claim id binds to the row without a request field. `CancelledFn` is the binding's cancellation argument. + +```rust +use dim_agent_capabilities::host::CancelledFn; +use dim_agent_runtime::{PublicService, SessionConfig}; +use dim_agent_types::grant::{GrantKind, GrantMode, SessionGrant}; +use rutis::Ctx; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Worktree { + pub repository: String, + pub root: String, + pub subtree: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Directory { + pub repository: String, + pub root: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Claim { + pub claim: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Settle { + pub claim: String, + pub removed: bool, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Usage { + pub session_id: String, + pub subtree: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DirectoryRecord { + pub repository: String, + pub root: String, + pub last_used_at_ms: Option, +} + +#[derive(Debug, thiserror::Error)] +pub enum StoreError { + #[error("{0}")] + Invalid(String), + #[error("the Session workspace no longer exists: {0}")] + WorkspaceMissing(String), + #[error("no stored Session {0}")] + NotFound(String), + #[error("the title revision changed")] + Conflict, + #[error("{0} is in use")] + InUse(String), + #[error("the claim ended before settlement")] + UnknownClaim, + #[error("the call was cancelled")] + Cancelled, + #[error("the store is unloading")] + Closed, + #[error("{0}")] + Storage(String), +} + +impl PublicService for SessionStore {} + +#[rutis::service(name = "store")] +impl SessionStore { + pub async fn create( + &self, + caller: &Ctx, + request: Create, + cancelled: CancelledFn, + ) -> Result<(), StoreError> { + // ... + } + + pub async fn delete( + &self, + caller: &Ctx, + request: Delete, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn fork( + &self, + caller: &Ctx, + request: Fork, + cancelled: CancelledFn, + ) -> Result<(), StoreError> { + // ... + } + + pub async fn claim_worktree( + &self, + caller: &Ctx, + request: Directory, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn settle_worktree( + &self, + caller: &Ctx, + request: Settle, + cancelled: CancelledFn, + ) -> Result<(), StoreError> { + // ... + } +} +``` + +The remaining operations follow the same shape: one request object, one reply object, the caller's `Ctx` where the operation is bound to the calling row, and `CancelledFn` only where the operation waits on a read. diff --git a/docs/design/plugins/SqliteStorage.md b/docs/design/plugins/SqliteStorage.md new file mode 100644 index 0000000000..c247461c0b --- /dev/null +++ b/docs/design/plugins/SqliteStorage.md @@ -0,0 +1,217 @@ +# SqliteStorage + +Scope: process. Issue: #2018. + +SqliteStorage owns the database file, the lease that admits one process to it, the format version and its upgrades, the writer and the read connections, and the transactions other owners' records are read and written in. This document is the owner's target contract. The current implementation is described in [Native storage format](../appserver/native-storage-format.md) and [Resource owner operations](../contracts/resource-owner-operations.md). + +## Use and scope: responsibility split + +SqliteStorage owns: + +- **The file and its lease.** `` and `.lock`; one process opens the store, upgrades it and holds the lock until close; an offline tool takes the same lock. +- **The format.** The version row, the schema, the ordered upgrades and the refusal of an unsupported format. +- **The connections.** One writer connection with its queue, a read pool, the WAL checkpoint and the close drain. +- **Transactions and reads.** One commit or one consistent read per call; the engine does not interpret the rows. +- **Offline operations.** Backup, restore and vacuum, each holding the same lease and refusing while a daemon owns the store. +- **The capacity value.** Database bytes, WAL bytes and reclaimable bytes. + +The stored form of each group of rows belongs to a data owner: the Timeline batches and positions to the Session store's engine, the Agent records to the Agent directory, the Settings documents to Settings, the Provider selection and preferences to Provider. Each group's request and reply shape is that owner's persistence contract; this contract names the transactions and keeps their boundaries. + +Callers keep: + +- **The meaning of their rows.** Admission, versions, business conflicts and error mapping. +- **When to read or write.** The Session lifecycle, the Agent directory's startup repair, the Settings document's validation, the Provider's edit preconditions. +- **Their own lifecycle.** The engine never closes a caller's owner or decides a caller's business. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Admit and commit a Timeline batch round | No: one grouped transaction, the writer queue and the per-Session fallback are the engine's | `commitTimelineRound` and the Timeline operations | +| Read a Timeline position, session configuration or branch set | No: the caller cannot read the file | `head`, `batchEnd`, `batchEndAt`, `branches`, `sessionConfig`, `createSession` | +| Load, save or delete Agent records and their relations | No: the records are rows with one writer and one transaction | the Agent record group | +| Read, import and replace Settings documents | No: the version check and the document row are one transaction | the Settings group | +| Read and write Provider selection and preferences | No: the scope version and the selected model are one transaction | the Provider group | +| Report the store's own bytes | No: only the process holding the file knows them | `storageReport` | +| Read and write Session file ownership rows | No: they belong to SessionFiles | not on this face: SessionFiles' private row operations | + +Every row above is No because the rows share one file, one writer and one close; the operations exist so callers do not hold the connection, the transaction or the file. + +## Caller example + +Agents loads its records and repairs unfinished ones at startup. + +```rust +let agents = storage.agents(Empty {}).await?; +let owners = storage.owners(Empty {}).await?; +let repair = storage.unfinishedOwned(Empty {}).await?; +``` + +Settings replaces a document under its expected version. + +```rust +let next = storage.replace_user(ReplaceUser { + source, expected_version, decision, +}).await?; +``` + +SessionStore writes one Session creation through the engine's transaction. + +```rust +storage.create_session(CreateSession { session_id, config }).await?; +``` + +## Own contract + +### Dependencies + +None. The assembly provides the store; deployment chooses its instance. Offline tools take the same file lease through the owner's functions, not through the service. + +### Operations + +Every operation takes one request object and answers one reply object. A transaction is not cancelled once it starts; a long batch round takes the caller's cancellation token and cancels before its commit. The engine's errors are per operation; the caller maps them to its business errors. + +| Group | Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | --- | +| Timeline | `createSession` | Prepare the stored Session record and the main branch | `{sessionId, config}` | `{}` | None | `storage` | +| Timeline | `sessionConfig`, `branches`, `head` | One stored read | `{sessionId}`, `{sessionId}`, `{key}` | `{config}`, `{branches}`, `{sequence}` | None | `storage` | +| Timeline | `batchEnd`, `batchEndAt` | Validate a boundary or return the containing batch's end | `{key, sequence}` | `{}` or `{sequence}` | None | `storage` | +| Timeline | `commitTimelineRound` | Admit and commit one ordered round of batches grouped by Session | `{batches}` | `{sessions:[{sessionId, result}]}` | Before the commit | `cancelled`, `storage` | +| Agent records | `agents`, `owners`, `members`, `ledMembers`, `ownedAgents`, `memberSessions`, `agentOwner`, `unfinishedOwned` | One consistent read of the directory's records | `{}`, or one id | the existing record shapes | None | `storage` | +| Agent records | `save`, `delete` | Write one Agent record or remove it | `{id, profile, default, owner?}`, `{id}` | `{}` | None | `storage` | +| Settings | `readUser` | One stored document and its version, or none | `{source}` | `{version, document}?` | None | `storage` | +| Settings | `importUserIfAbsent` | Insert a validated document and its provenance if absent; return the winning row | `{source, document, importedRevision}` | `{version, document}` | None | `storage` | +| Settings | `replaceUser` | Replace a document under its expected version | `{source, expectedVersion, decision}` | `{version}` | None | `missing`, `conflict`, `overflow`, `rejected`, `storage` | +| Provider | `readSelection`, `readPreferences` | One stored selection or preference | `{scope}`, `{providerId, modelId}` | the stored value or none | None | `storage` | +| Provider | `writeSelection` | Write the selected model under the scope's expected version | `{scope, expectedVersion, selection}` | the committed selection and version | None | `conflict`, `storage` | +| Capacity | `storageReport` | The store's own file bytes, WAL bytes and reclaimable bytes | `{}` | `{databaseBytes, walBytes, reclaimableBytes}` | None | `storage` | + +The file-ownership row operations (`reserveFile`, `commitFile`, `abandonFile`, `ownsFile`, `ownsOutput`, `ownedPaths`, `registerOutput`) are `pub(crate)` operations of SessionFiles, not this face. The `storage.report` client method registers through `managementMethods` and calls `storageReport`; the registration point is not a second operation. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `storage` | The transaction or read failed; the caller reports its own failure and retries the business step when that is safe | +| `cancelled` | The round stopped before its commit; nothing was written by this round | +| `missing` | The document or record does not exist; the caller decides whether to create it | +| `conflict` | Another writer committed at a different version; re-read and decide | +| `overflow` | The version or the scope exceeded its bound; the caller reports it as a storage failure | +| `rejected` | A protected field was changed; the caller keeps the user's document and reports the field | + +The engine does not answer `not_found`: a missing row is the data owner's business answer, expressed by that owner's operation. + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| Open, upgrade, verify | Open the file, take the lease, read and write the format, run the ordered upgrades in one transaction, start the writer and the read pool | Not applicable: assembly admits the daemon once | Not applicable | A failed open leaves the previous format, or the startup note names the newer store | File and lease by SqliteStorage; the process exits | +| `commitTimelineRound` | Admit the round, encode grouped by Session, commit one transaction per group, answer one outcome per distinct Session | Before the commit; nothing is written | The admitted round completes; the reply may be lost | Admission stops; the admitted round ends before close | Rows by SqliteStorage; publication by the Session store | +| Other writes | One transaction | None after it starts | The transaction completes; the reply may be lost | Admitted writes end before close | SqliteStorage | +| Reads | One consistent read on a pooled connection | None; the read is bounded | Nothing to release | Pending reads end `closed` | SqliteStorage | +| `storageReport` | Read the file sizes and the free-page count | None | Nothing to release | Pending calls end `closed` | SqliteStorage | +| Close | Refuse new work, wait for the running calls, close the readers, checkpoint, close the writer, release the lease | Not applicable | In-flight calls finish | The next process opens after the lease is free | SqliteStorage | +| Offline backup, restore, vacuum | Take the same lease, operate on the file, release | Not applicable; the tool runs alone | Not applicable | Refused while a daemon holds the lease | The offline tool and SqliteStorage share the lease | + +## Exceptions with reasons + +- Offline tools (`dim-migration`, backup, restore, vacuum) open the file under the same lease and write rows in the published format: an import or a repair runs while no daemon may own the store, and the format is the contract both sides implement. The lease is the exclusion; the format version is the gate. +- `storageReport` is a client method and a service operation: the management method is a registration point (ADR 002), and the service operation is the same read for plugins. +- The engine's operations are named after their data owners' records because those owners define the shapes; the engine owns the stored form and the transaction, and adds no business rule. + +## Verification + +Flow tests on the owner: + +- Opening a newer format refuses and leaves the file unchanged; an upgrade is one transaction; a second process fails to open while the lease is held. +- `commitTimelineRound` commits one outcome per distinct Session, keeps the input order and answers an outcome for a failed group without dropping the others. +- `replaceUser` on a stale version answers `conflict`; a protected-field change answers `rejected` without writing; `importUserIfAbsent` returns the winning row. +- `writeSelection` on a stale scope answers `conflict`; `readPreferences` answers none for an absent preference. +- `storageReport` answers the file, WAL and free-page values; the client method returns the same values. +- Closing drains the running calls, checkpoints and releases the lease; an offline tool cannot open while the daemon owns it. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | SqliteStorage is one process part. It writes no Timeline fact of its own and is not a Capability. | +| §2 scopes | Process: the file, the lease and the transactions are shared across Sessions. | +| §3 orthogonality | Every transaction belongs to one data owner's records; the engine interprets none. | +| §4 rule 1 | No command event. | +| §4 rule 2 | No handoff. | +| §4 rule 3 | No before callback. | +| §4 rule 4 | No business rule. | +| §4 rule 5 | The grouped round keeps its commit and fallback order. | +| §4 rule 6 | No context input. | +| §4 rule 7 | Callers use these operations; no caller holds a connection or a transaction. | +| §4 rule 8 | No infrastructure change; requirements below. | +| §4 rule 9 | The engine publishes no Timeline fact; the round is the Session store's publication path. | +| §7.2 ids and values | Requests and replies are data; no connection, statement or transaction crosses. | +| §7.2 one public face | The service is marked on the SqliteStorage type under the existing `sqliteStorage` name; the hand-written dispatch adapter beside it is replaced. | +| §7.2 caller mechanisms | The writer queue, the read pool, the WAL and the drain stay inside the owner. | +| ADR 002 D1 | Process scope. | +| ADR 002 D2 | No wiring plugin. | +| ADR 002 D3 | No dependencies; other owners depend on the engine. | +| ADR 002 D4 | The path and the format are structural configuration; no business setting. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +1. **Settings (#2017), Provider (#2019), Agent directory (#2020): your group's contract.** The operations in the Settings, Provider and Agent record groups are your persistence contracts, executed by this engine. Your contracts own their request, reply and error shapes; this contract keeps the transactions and does not reinterpret them. A comment on each sub-issue states the split. +2. **SessionScope (#2025): the Timeline operations have one face.** The engine owns the Timeline operations; the Session-scoped `timelineStore` publishes the same engine per Session. `store.query` and `store.sessionConfig` read the same engine from the process side. The engine has one operation set; SessionScope's contract states which face owns which operation and removes the duplicate name. + +## Binding appendix + +The service is marked on the `SqliteStorage` type; the wire name stays `sqliteStorage`. The hand-written adapter type is deleted. `CancelledFn` is the binding's cancellation argument, used only by `commitTimelineRound`. + +```rust +use dim_agent_capabilities::host::CancelledFn; +use dim_agent_runtime::PublicService; +use rutis::Ctx; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Capacity { + pub database_bytes: u64, + pub wal_bytes: u64, + pub reclaimable_bytes: u64, +} + +#[derive(Debug, thiserror::Error)] +pub enum StorageError { + #[error("{0}")] + Storage(String), + #[error("the round was cancelled")] + Cancelled, + #[error("{0}")] + Missing(String), + #[error("{0}")] + Conflict(String), + #[error("{0}")] + Overflow(String), + #[error("{0}: {1}")] + Rejected(String, String), +} + +impl PublicService for SqliteStorage {} + +#[rutis::service(name = "sqliteStorage")] +impl SqliteStorage { + pub async fn storage_report( + &self, + caller: &Ctx, + request: Empty, + ) -> Result { + // ... + } + + pub async fn commit_timeline_round( + &self, + caller: &Ctx, + request: Round, + cancelled: CancelledFn, + ) -> Result { + // ... + } +} +``` + +Every operation takes one request object, one reply object and the caller's `Ctx`; only `commitTimelineRound` waits and takes `CancelledFn`. From 817e4c18c39f47653a1a49c6da9c8783cdbf97fc Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 14:44:57 +0800 Subject: [PATCH 02/19] docs(storage): serialize title writes and settle worktree removal by callback SessionStore owns title write order: the caller supplies the title, the owner serializes the write, answers the committed revision and publishes the notice. The expected revision leaves the request, the caller example, the operation, the errors and the flows. Worktree removal becomes one removeWorktree operation with the caller's removal callback: the store holds the Session exclusion, checks the association and workspace state, runs the caller's Git step and deletes or keeps the record by its result. The claim id and the two-step claim/settle protocol leave SessionStore and ManagedWorktrees. Refs #2018 Refs #2015 --- docs/design/plugins/ManagedWorktrees.md | 20 ++--- docs/design/plugins/SessionStore.md | 107 +++++++++++------------- 2 files changed, 59 insertions(+), 68 deletions(-) diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md index 97e75cb18d..898fd98b30 100644 --- a/docs/design/plugins/ManagedWorktrees.md +++ b/docs/design/plugins/ManagedWorktrees.md @@ -28,7 +28,7 @@ Callers keep: | Settle a created worktree that the Session creation did not adopt | No: the branch and base are the owner's, and the cleanup path must not be cancelled | `discard` | | List managed worktrees with their branch, HEAD, content state and Session use | No: the view joins Git with the store's records and associations | `list` | | Preview a prune: which directories are candidates and why the others stay | No: the age, keep and force rules and the re-checks are the owner's | `pruneSelection` | -| Remove one managed worktree | No: the removal needs the store's exclusion for the record and the owner's Git removal; a caller composing the two would hold the exclusion itself | `remove` | +| Remove one managed worktree | No: the removal needs the store's exclusion for the record and this owner's Git removal; the store's operation takes the Git step as the caller's own callback, so no lock or claim crosses | `remove` | | Remove an unregistered directory left by a failed creation | No: the directory has no record; the owner decides whether it is a plain managed directory and whether its content allows removal | `remove` with `taskId` | An operation exists only where its row says No. @@ -61,7 +61,7 @@ for candidate in confirmed(&preview) { ### Dependencies -`store` for the directory records, the Session associations, the stored workspaces and the removal claim; `managementMethods` for the `worktree.*` client methods. Git is the owner's own process resource, started and reaped by this owner. +`store` for the directory records, the Session associations, the stored workspaces and `removeWorktree`, which runs this owner's Git step under the store's exclusion; `managementMethods` for the `worktree.*` client methods. Git is the owner's own process resource, started and reaped by this owner. ### Operations @@ -75,7 +75,7 @@ for candidate in confirmed(&preview) { `create` returns a value; `discard` and `remove` take the task id. No object crosses. The preparation table is the owner's generation state: a reload drops it, and `discard` for a task id the generation did not create answers `unknown_preparation`; the directory is then an unregistered directory that `remove` handles. -`remove` composes the store: `claimWorktree` (the record, the associations and the stored workspaces), the Git removal, then `settleWorktree` (delete the record on success, restore it on failure). The claim id is bound to this owner's calling row, so an unload restores the record. `force` overrides only the content check; the Git removal receives `--force` only then. +`remove` composes the store's `removeWorktree`: the store checks the record, the associations and the stored workspaces under its exclusion and calls this owner's Git removal as a callback; the record is deleted when the callback succeeds and kept when it refuses or fails. No claim id or lock crosses. `force` overrides only the content check; the Git removal receives `--force` only then. ### Errors @@ -96,12 +96,12 @@ for candidate in confirmed(&preview) { | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `create` | Resolve the source and the Git roots, resolve the base, allocate a task id, `git worktree add -b`, canonicalize the root, check the subtree, return the value; the caller adopts it with `store.create` | Each Git call ends `interrupted`; an empty task directory this call made is removed; a created worktree is rolled back by the owner | The call ends `interrupted`; the rollback path runs | New calls are refused; an in-flight creation is rolled back or left as an unregistered directory | Git and the directory by ManagedWorktrees; the record by the store | -| `discard` | Look up the preparation, `claimWorktree`, Git removal, delete the branch, `settleWorktree` | No cancellation; the cleanup is the owner's | The preparation ends with the row; the directory is unregistered | The table drops with the generation; the directory stays unregistered | Directory and branch by ManagedWorktrees; record by the store | +| `discard` | Look up the preparation, `store.removeWorktree(directory, remove)`, delete the branch; the record may be absent | No cancellation; the cleanup is the owner's | The preparation ends with the row; the directory is unregistered | The table drops with the generation; the directory stays unregistered | Directory and branch by ManagedWorktrees; record by the store | | `list` | Read the records and associations, join Git state per directory, add unregistered directories | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | | `pruneSelection` | `list`, then apply age, keep and force rules per candidate | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | -| `remove` | Resolve the record or the unregistered directory, `claimWorktree`, Git removal, `settleWorktree` | Before the claim or the Git removal; a started removal completes or reports `git` | The claim ends with the row; the record is restored | The claim drops with the store generation; the record stays for a retry | Directory by ManagedWorktrees; record by the store | +| `remove` | Resolve the record or the unregistered directory, then `store.removeWorktree(directory, remove)`: the store checks and holds the exclusion, this owner removes the Git worktree, the store deletes or keeps the record | Before the Git removal; a started removal completes or reports `git`; the store keeps the record | The callback ends with the row; the store keeps the record | An in-flight removal ends; the store keeps the record unless the Git step succeeded | Directory by ManagedWorktrees; record by the store | -A process death between `create` and `store.create` leaves an unregistered directory; `list` reports it and `remove` deletes it after the operator names the task id. A process death between the claim and the settle leaves the record; the next `list` reports the directory as missing or no longer registered, and `remove` cleans the record. +A process death between `create` and `store.create` leaves an unregistered directory; `list` reports it and `remove` deletes it after the operator names the task id. A process death during the removal step leaves the record; the next `list` reports the directory as missing or no longer registered, and `remove` cleans the record. ## Exceptions with reasons @@ -118,7 +118,7 @@ Flow tests on the owner: - `discard` removes a created worktree that no Session adopted; a Session association or a stored workspace keeps it and answers `in_use`; `unknown_preparation` after a generation change. - `remove` deletes a recorded directory and its record; a directory with content refuses without `force`; a missing root deletes the record only; an unregistered directory with content refuses without `force`; a link is refused. - `pruneSelection` never selects an unregistered, unknown, used or unremovable directory; `keep` treats an unknown use time as oldest; `olderThanMs` never selects an unknown time. -- A claim is restored when the calling row unloads; a settle after the claim ended answers `unknown_claim`. +- A failed or cancelled Git removal keeps the record; a row unload or owner close keeps the record; a successful removal deletes it. ## Rule check @@ -136,9 +136,9 @@ Flow tests on the owner: | §4 rule 7 | Callers use these operations; no caller invokes Git or reads the root directly. | | §4 rule 8 | No infrastructure change. | | §4 rule 9 | No Timeline fact; a worktree is a process fact. | -| §7.2 ids and values | Task ids, paths and policies cross as data; the created value is data; no object crosses. | +| §7.2 ids and values | Task ids, paths and policies cross as data; the created value is data; the removal step crosses as a callback by reference; no object or claim id crosses. | | §7.2 one public face | The service is marked on the ManagedWorktrees type under the existing `managedWorktrees` name; the client methods `worktree.*` are registration points, not a second face. | -| §7.2 caller mechanisms | The root, Git, the preparation table and the claim stay inside the owner; callers handle the business errors only. | +| §7.2 caller mechanisms | The root, Git, the preparation table and the record settlement through the store's operation stay inside the owners; callers handle the business errors only. | | ADR 002 D1 | Process scope. | | ADR 002 D2 | No wiring plugin; the `worktree.*` rows register methods, they do not own state. | | ADR 002 D3 | Depends on the store for records; no lower handle. | @@ -147,7 +147,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -None new. The store's `claimWorktree` and `settleWorktree` are defined in [SessionStore's contract](SessionStore.md); the `managementMethods` registration point is the existing mechanism. +None new. The store's `removeWorktree` is defined in [SessionStore's contract](SessionStore.md); the `managementMethods` registration point is the existing mechanism. ## Binding appendix diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 60e53ebccd..044be36384 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -42,10 +42,10 @@ Callers keep: | Add or remove one grant | No: the upsert rule that keeps a write grant is the owner's invariant | `addGrant`, `removeGrant` | | Write the reply language into the stored configuration | No: the caller must not rewrite the stored record | `setLanguage` | | Read the title and its revision | No: the caller has no row access | `title` | -| Write a title under its expected revision and announce the commit | No: the revision check, the single writer and the post-commit notice are the owner's | `setTitle` | +| Write a title and announce the commit | No: title writes are serialized inside the owner and the committed notice is published after the commit; a caller cannot order writers or publish that notice | `setTitle` | | Record a verified worktree directory and the Session's subtree | No: the directory record, the association and the last-use time are one commit | `associateWorktree` | | List recorded worktree directories or their Session associations, or learn which stored Sessions have a workspace under a root | No: the caller has no row access | `worktrees`, `worktreeUsages`, `sessionsUnder` | -| Remove one recorded worktree together with its directory | No: the association and workspace checks, the physical removal and the record deletion must not interleave with a Session creation that would point into the removed root | `claimWorktree`, `settleWorktree` | +| Remove one recorded worktree together with its directory | No: the association and workspace checks, the caller's own removal step and the record deletion must not interleave with a Session creation that would point into the removed root | `removeWorktree` with a removal callback | An operation exists only where its row says No. @@ -68,25 +68,23 @@ store.fork(Fork { source, id: fork, at, config_text: source_text.config_text }, let removed = store.delete(Delete { id }, cancelled).await?; ``` -SessionTitle reads the revision, writes one revision later and announces the commit inside the owner. +SessionTitle reads the current title, decides the text and writes it; the owner serializes the write and announces the committed revision. ```rust let current = store.title(TitleRead { id }, cancelled.clone()).await?; -// A conflict means another writer committed a revision first; the title text is recomputed. -let next = store.setTitle(SetTitle { id, expected_revision: current.revision, title }, cancelled).await?; +// The text is the caller's business; the owner serializes the write and answers the committed revision. +let next = store.setTitle(SetTitle { id, title: Some(title_for(¤t)) }, cancelled).await?; ``` -ManagedWorktrees removes a directory: the claim holds the exclusion, Git removes the root, the settle deletes or restores the record. +ManagedWorktrees removes a directory: the owner holds the exclusion while the caller's Git step removes the root, and deletes or keeps the record by that step's result. ```rust -let claim = store.claimWorktree(Directory { repository, root }, cancelled.clone()).await?; -match git_remove(&root, force, cancelled).await { - Ok(()) => store.settleWorktree(Settle { claim: claim.claim_id, removed: true }, cancelled).await?, - Err(error) => { - store.settleWorktree(Settle { claim: claim.claim_id, removed: false }, CancellationToken::new()).await?; - return Err(error); - } -} +// The owner holds the Session exclusion and settles the record by this step's result. +let remove: RemoveFn = Arc::new(move |root: String| { + let cancelled = cancelled.clone(); + Box::pin(async move { git_remove(&root, force, &cancelled).await }) +}); +store.removeWorktree(Directory { repository, root }, remove, cancelled.clone()).await?; ``` ## Own contract @@ -116,13 +114,12 @@ Every operation takes one request object and answers one reply object. Writes ar | `removeGrant` | Remove one grant; an absent grant counts as removed | `{id, path}` | `{}` | None | `storage` | | `setLanguage` | Write the reply language into the stored configuration | `{id, language?}` | `{}` | None | `not_found`, `invalid`, `storage` | | `title` | The title and its committed revision | `{id}` | `{revision, title?}` | None | `not_found`, `storage` | -| `setTitle` | Commit a title as the next revision and announce it | `{id, expectedRevision, title?}` | `{revision}` | The reply may be dropped; the admitted write is not cancelled | `not_found`, `conflict`, `storage` | +| `setTitle` | Commit a title and announce it; the owner serializes writes | `{id, title?}` | `{revision}` | The reply may be dropped; the admitted write is not cancelled | `not_found`, `storage` | | `associateWorktree` | Record a verified directory and the Session's subtree in one commit | `{id, repository, root, subtree}` | `{}` | None | `not_found`, `invalid`, `storage` | | `worktrees` | Recorded directories, with their last use when known | `{}` | `{directories}` | None | `storage` | | `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `storage` | | `sessionsUnder` | Stored Sessions whose workspace is a root or lies under it | `{root}` | `{sessionIds}` | None | `invalid`, `storage` | -| `claimWorktree` | Claim one recorded directory for removal under the Session exclusion; the claim id is bound to the calling row | `{repository, root}` | `{claim}` | Before the claim is written | `not_found`, `in_use`, `invalid`, `storage` | -| `settleWorktree` | End a claim: delete the record when the directory is gone, restore it otherwise | `{claim, removed}` | `{}` | None; the owner completes the settlement | `unknown_claim`, `storage` | +| `removeWorktree` | Remove one recorded directory under the Session exclusion, with the caller's own removal step | `{repository, root}` + `remove` | `{removed}` | The caller's step ends; the record stays | `invalid`, `in_use`, `rejected`, `storage` | `worktree` in `create` and `associateWorktree` is `{repository, root, subtree}`: absolute UTF-8 paths, `subtree` inside `root`. The caller passes paths it already resolved; the owner re-checks that each is absolute, UTF-8 and, for an association, that the root still is a directory. @@ -133,9 +130,8 @@ Every operation takes one request object and answers one reply object. Writes ar | `invalid` | Fix the request: an id that is not one path component, a relative or non-UTF-8 path, a subtree outside the root, an unknown language code, an invalid catalog cursor | | `workspace_missing` | The creation's `cwd` no longer is a directory; the caller reports the failed creation and discards the worktree | | `not_found` | No stored Session has the id; the caller decides whether that is a business error or an answer | -| `conflict` | Another title write committed first; re-read `title` and decide | | `in_use` | A Session association or a stored workspace still names the directory; delete that Session or refuse the removal | -| `unknown_claim` | The claim ended (the calling row unloaded, the owner reloaded, or another settlement ran); the directory state must be inspected before a retry | +| `rejected` | The removal step refused or failed with its own `code` and `message`; the record stays and the caller acts on that code | | `cancelled` | The caller stopped the read; nothing changed | | `closed` | This generation is unloading; call the replacement generation | | `storage` | The store failed; the caller reports the failure and keeps the Session or worktree for a retry | @@ -144,22 +140,21 @@ Every operation takes one request object and answers one reply object. Writes ar | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `create` | Validate the id and the workspace, take the exclusion, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller's row cannot use a Session it did not learn the id of, and a retry is a new id | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | +| `create` | Validate the id and the workspace, take the exclusion, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller keeps the id it supplied and decides whether to publish or delete the Session | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | | `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove visible and Timeline rows, schedule the file sweep | Before the first commit: every row stays. After: the steps run to their end | The work continues under the owner's task; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | | `fork` | Take the exclusion, copy in bounded transactions, write the target row with the supplied text, commit | Before the first copy | The copy continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | | `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `sessionConfigText`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | | `catalog`, `query` | One consistent read under the caller's token | The read stops; no partial page | Nothing to release | Pending reads end `cancelled` | SessionStore | | `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | -| `setTitle` | Admit the write under the owner's admission, run it as the owner's task, commit, announce, answer the revision | Dropping the reply never cancels the admitted write | The admitted write completes and announces | Close stops admission, waits for every admitted write | SessionStore | -| `claimWorktree` | Check associations and stored workspaces, mark the record claimed under the exclusion, bind the claim to the calling row | Before the mark | The owner restores the record and ends the claim | Claims are generation state: a reload drops them and restores the records | SessionStore | -| `settleWorktree` | End the claim; `removed` deletes the record, otherwise the record stays | None; the owner completes | Nothing to release | Pending settlements end `closed` | SessionStore; the directory by ManagedWorktrees | +| `setTitle` | Admit the write behind earlier admitted writes, run it as the owner's task, commit, announce, answer the revision | Dropping the reply never cancels the admitted write | The admitted write completes and announces | Close stops admission, waits for every admitted write | SessionStore | +| `removeWorktree` | Validate the paths, take the exclusion, check associations and stored workspaces, call `remove`, delete the record on success, release | The removal step ends `cancelled`; the record stays | The callback ends; the record stays; the exclusion releases | New calls are refused `closed`; an in-flight removal ends, and the record stays unless the step succeeded | Directory by the caller; record by SessionStore | ## Exceptions with reasons - `create` and `fork` take the caller's already-validated configuration and the fork text: validating the protocol, the collaboration role and the cut belongs to the Session lifecycle owner, and re-serializing the text would change bytes. -- `delete` does not close the Session, remove its Agent admission slot or remove the worktree: closing is Agents', and a managed worktree is removed by ManagedWorktrees under `claimWorktree`. +- `delete` does not close the Session, remove its Agent admission slot or remove the worktree: closing is Agents', and a managed worktree is removed by ManagedWorktrees under `removeWorktree`. - `setTitle` hands the write over at admission: the reply may be lost, so the caller re-reads rather than assumes failure. -- `claimWorktree` and `settleWorktree` are two operations because the physical removal is ManagedWorktrees' resource: the claim is the store's exclusion state, not a handle; the id is bound to the calling row, so an unload restores the record instead of leaving it claimed. +- `removeWorktree` runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. - `owner` answers the Agent id for a delete notice; the Agent directory's own records are not returned here. ## Verification @@ -167,14 +162,14 @@ Every operation takes one request object and answers one reply object. Writes ar Flow tests on the owner: - `create` writes the Session, the owner, the main branch, the catalog row and the worktree association together; a failed association writes nothing. -- `delete` removes output first, then the rows; a failure before the first commit leaves every row; a concurrent creation cannot associate with a directory whose record is claimed. +- `delete` removes output first, then the rows; a failure before the first commit leaves every row; a concurrent creation waits for an in-flight removal and then either sees the surviving directory or fails on the missing workspace. - `fork` copies the supplied text unchanged and never parses it. - `addGrant` on a missing Session answers `not_found`; `removeGrant` on an absent grant answers success; a read grant never downgrades a write grant. -- `setTitle` with a stale revision answers `conflict`; a dropped reply still commits and announces; close waits for the admitted write. -- `claimWorktree` answers `in_use` while an association or a stored workspace remains; a claimed directory refuses creation and association; an unloaded caller restores the record; `settleWorktree` with `removed: false` keeps the record. -- A call in flight when the generation closes ends `closed`; claims do not survive the generation. +- Two concurrent `setTitle` calls commit in admission order and each announces its revision; a dropped reply still commits and announces; close waits for the admitted write. +- `removeWorktree` answers `in_use` while an association or a stored workspace remains; a failed or cancelled removal keeps the record; a successful removal deletes it; a concurrent creation waits for the removal and then either associates with the surviving directory or fails on the missing workspace. +- A call in flight when the generation closes ends `closed`; a dropped callback keeps the record. -Material uncertainty: the claim's lifetime when the daemon process dies between claim and settle is recorded only in memory; the record survives, the directory state is Git's, and a later `worktrees`/`remove` reconciles the pair. Review checks that no caller treats `unknown_claim` as success. +Material uncertainty: a process death during the caller's removal step leaves the record; the directory state is Git's, and a later `worktrees`/`remove` reconciles the pair. Review checks that no caller treats `rejected` as success. ## Rule check @@ -192,9 +187,9 @@ Material uncertainty: the claim's lifetime when the daemon process dies between | §4 rule 7 | Callers use these operations; no caller reads a row, a writer generation or a lock. | | §4 rule 8 | No infrastructure change; requirements are listed below. | | §4 rule 9 | The store publishes no Timeline fact of its own; the attached worktree stays a process fact. | -| §7.2 ids and values | Requests and replies are data; the worktree value and the claim id cross, no object does. | +| §7.2 ids and values | Requests and replies are data; the worktree value crosses, and the removal step crosses as a callback by reference. No object crosses. | | §7.2 one public face | The service is marked on the SessionStore type under the existing `store` name; `Store`, `SessionMetadata` and `WorktreeAssociations` do not exist beside it. | -| §7.2 caller mechanisms | The exclusion, the title admission and the claim lifetime stay inside the owner; callers handle business errors only. | +| §7.2 caller mechanisms | The exclusion, the title admission and the record settlement stay inside the owner; callers handle business errors only. | | ADR 002 D1 | Process scope: the Session row set and its records outlive a Session. | | ADR 002 D2 | No wiring plugin: one service on the owner type. | | ADR 002 D3 | Dependencies point to the engine and the file owner; no caller holds a lower handle. | @@ -208,7 +203,7 @@ Material uncertainty: the claim's lifetime when the daemon process dies between ## Binding appendix -The service is marked on the `SessionStore` type; the wire name stays `store`. `Store` the wrapper, `SessionMetadata` and `WorktreeAssociations` no longer exist. `caller: &Ctx` is rutis's caller parameter: the dispatch fills it from the calling row, so a claim id binds to the row without a request field. `CancelledFn` is the binding's cancellation argument. +The service is marked on the `SessionStore` type; the wire name stays `store`. `Store` the wrapper, `SessionMetadata` and `WorktreeAssociations` no longer exist. `caller: &Ctx` is rutis's caller parameter: the dispatch fills it from the calling row, so no caller sends or names a row. `CancelledFn` is the binding's cancellation argument. ```rust use dim_agent_capabilities::host::CancelledFn; @@ -226,24 +221,30 @@ pub struct Worktree { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Directory { - pub repository: String, - pub root: String, +pub struct Removed { + pub removed: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Claim { - pub claim: String, +pub struct Directory { + pub repository: String, + pub root: String, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Settle { - pub claim: String, - pub removed: bool, +/// The caller's own refusal or failure, carried unchanged. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, thiserror::Error)] +#[error("{code}: {message}")] +pub struct Rejected { + pub code: String, + pub message: String, } +/// The caller's own removal step: it removes the checked directory and reports success, or refuses with its own code and message. +pub type RemoveFn = Arc< + dyn Fn(String) -> rutis::host::BoxFuture<'static, Result<(), Rejected>> + Send + Sync, +>; + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Usage { @@ -267,12 +268,10 @@ pub enum StoreError { WorkspaceMissing(String), #[error("no stored Session {0}")] NotFound(String), - #[error("the title revision changed")] - Conflict, #[error("{0} is in use")] InUse(String), - #[error("the claim ended before settlement")] - UnknownClaim, + #[error("{code}: {message}")] + Rejected { code: String, message: String }, #[error("the call was cancelled")] Cancelled, #[error("the store is unloading")] @@ -312,21 +311,13 @@ impl SessionStore { // ... } - pub async fn claim_worktree( + pub async fn remove_worktree( &self, caller: &Ctx, request: Directory, + remove: RemoveFn, cancelled: CancelledFn, - ) -> Result { - // ... - } - - pub async fn settle_worktree( - &self, - caller: &Ctx, - request: Settle, - cancelled: CancelledFn, - ) -> Result<(), StoreError> { + ) -> Result { // ... } } From 26f10f7d7d43fcd6cd45c32b1a40cf9ee5a142fd Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 15:04:41 +0800 Subject: [PATCH 03/19] docs(storage): decide titles through a change callback setTitle takes the caller's change instead of a title plus an expected revision: the change receives the current title, its source and revision, and returns the next title or its own refusal. SessionStore serializes the decision, commits the returned title, announces it and answers the new revision. The conflict error leaves the contract; a refused change keeps the title. The title read now carries the source. Refs #2018 Refs #2015 --- docs/design/plugins/SessionStore.md | 64 +++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 044be36384..0fa7a8af88 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -42,7 +42,7 @@ Callers keep: | Add or remove one grant | No: the upsert rule that keeps a write grant is the owner's invariant | `addGrant`, `removeGrant` | | Write the reply language into the stored configuration | No: the caller must not rewrite the stored record | `setLanguage` | | Read the title and its revision | No: the caller has no row access | `title` | -| Write a title and announce the commit | No: title writes are serialized inside the owner and the committed notice is published after the commit; a caller cannot order writers or publish that notice | `setTitle` | +| Write a title and announce the commit | No: the write is serialized inside the owner, the decision reads the current title and revision under that serialization, and the committed notice is published after the commit | `setTitle` with a change callback | | Record a verified worktree directory and the Session's subtree | No: the directory record, the association and the last-use time are one commit | `associateWorktree` | | List recorded worktree directories or their Session associations, or learn which stored Sessions have a workspace under a root | No: the caller has no row access | `worktrees`, `worktreeUsages`, `sessionsUnder` | | Remove one recorded worktree together with its directory | No: the association and workspace checks, the caller's own removal step and the record deletion must not interleave with a Session creation that would point into the removed root | `removeWorktree` with a removal callback | @@ -68,12 +68,14 @@ store.fork(Fork { source, id: fork, at, config_text: source_text.config_text }, let removed = store.delete(Delete { id }, cancelled).await?; ``` -SessionTitle reads the current title, decides the text and writes it; the owner serializes the write and announces the committed revision. +SessionTitle decides the next title from the current one; the owner serializes the decision and announces the committed revision. ```rust -let current = store.title(TitleRead { id }, cancelled.clone()).await?; -// The text is the caller's business; the owner serializes the write and answers the committed revision. -let next = store.setTitle(SetTitle { id, title: Some(title_for(¤t)) }, cancelled).await?; +let change: ChangeFn = Arc::new(move |current: TitleState| { + let next = decide(current.revision, current.title.as_ref(), &text); // business rules + Box::pin(async move { Ok(next) }) +}); +let next = store.setTitle(SetTitle { id }, change, cancelled).await?; ``` ManagedWorktrees removes a directory: the owner holds the exclusion while the caller's Git step removes the root, and deletes or keeps the record by that step's result. @@ -113,8 +115,8 @@ Every operation takes one request object and answers one reply object. Writes ar | `addGrant` | Add one grant, never downgrading a write grant | `{id, path, kind, mode}` | `{}` | None | `not_found`, `invalid`, `storage` | | `removeGrant` | Remove one grant; an absent grant counts as removed | `{id, path}` | `{}` | None | `storage` | | `setLanguage` | Write the reply language into the stored configuration | `{id, language?}` | `{}` | None | `not_found`, `invalid`, `storage` | -| `title` | The title and its committed revision | `{id}` | `{revision, title?}` | None | `not_found`, `storage` | -| `setTitle` | Commit a title and announce it; the owner serializes writes | `{id, title?}` | `{revision}` | The reply may be dropped; the admitted write is not cancelled | `not_found`, `storage` | +| `title` | The title, its source and its committed revision | `{id}` | `{revision, title?: {text, source}}` | None | `not_found`, `storage` | +| `setTitle` | Commit the title the caller's change returns and announce it; the owner serializes writes | `{id}` + `change` | `{revision}` | The reply may be dropped; the admitted write is not cancelled | `not_found`, `rejected`, `storage` | | `associateWorktree` | Record a verified directory and the Session's subtree in one commit | `{id, repository, root, subtree}` | `{}` | None | `not_found`, `invalid`, `storage` | | `worktrees` | Recorded directories, with their last use when known | `{}` | `{directories}` | None | `storage` | | `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `storage` | @@ -131,7 +133,7 @@ Every operation takes one request object and answers one reply object. Writes ar | `workspace_missing` | The creation's `cwd` no longer is a directory; the caller reports the failed creation and discards the worktree | | `not_found` | No stored Session has the id; the caller decides whether that is a business error or an answer | | `in_use` | A Session association or a stored workspace still names the directory; delete that Session or refuse the removal | -| `rejected` | The removal step refused or failed with its own `code` and `message`; the record stays and the caller acts on that code | +| `rejected` | The caller's change or removal step refused with its own `code` and `message`; the title or the record is unchanged and the caller acts on that code | | `cancelled` | The caller stopped the read; nothing changed | | `closed` | This generation is unloading; call the replacement generation | | `storage` | The store failed; the caller reports the failure and keeps the Session or worktree for a retry | @@ -146,14 +148,14 @@ Every operation takes one request object and answers one reply object. Writes ar | `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `sessionConfigText`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | | `catalog`, `query` | One consistent read under the caller's token | The read stops; no partial page | Nothing to release | Pending reads end `cancelled` | SessionStore | | `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | -| `setTitle` | Admit the write behind earlier admitted writes, run it as the owner's task, commit, announce, answer the revision | Dropping the reply never cancels the admitted write | The admitted write completes and announces | Close stops admission, waits for every admitted write | SessionStore | +| `setTitle` | Admit the write behind earlier admitted writes, read the current title, call `change` under the serialization, write the returned title as revision + 1, commit, announce, answer the revision | Dropping the reply never cancels the admitted write; a change that refuses leaves the title unchanged | The change callback is revoked before it returns; the admitted write fails and the title stays | Close stops admission, waits for every admitted write | SessionStore; the change computes only | | `removeWorktree` | Validate the paths, take the exclusion, check associations and stored workspaces, call `remove`, delete the record on success, release | The removal step ends `cancelled`; the record stays | The callback ends; the record stays; the exclusion releases | New calls are refused `closed`; an in-flight removal ends, and the record stays unless the step succeeded | Directory by the caller; record by SessionStore | ## Exceptions with reasons - `create` and `fork` take the caller's already-validated configuration and the fork text: validating the protocol, the collaboration role and the cut belongs to the Session lifecycle owner, and re-serializing the text would change bytes. - `delete` does not close the Session, remove its Agent admission slot or remove the worktree: closing is Agents', and a managed worktree is removed by ManagedWorktrees under `removeWorktree`. -- `setTitle` hands the write over at admission: the reply may be lost, so the caller re-reads rather than assumes failure. +- `setTitle` runs the caller's change under the owner's serialization: the change only computes the next title from the current title and revision, and returns its own refusal; the reply may be lost, so the caller re-reads rather than assumes failure. - `removeWorktree` runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. - `owner` answers the Agent id for a delete notice; the Agent directory's own records are not returned here. @@ -165,7 +167,7 @@ Flow tests on the owner: - `delete` removes output first, then the rows; a failure before the first commit leaves every row; a concurrent creation waits for an in-flight removal and then either sees the surviving directory or fails on the missing workspace. - `fork` copies the supplied text unchanged and never parses it. - `addGrant` on a missing Session answers `not_found`; `removeGrant` on an absent grant answers success; a read grant never downgrades a write grant. -- Two concurrent `setTitle` calls commit in admission order and each announces its revision; a dropped reply still commits and announces; close waits for the admitted write. +- The change receives the current title, its source and revision; a change that returns `Rejected` leaves the title and revision unchanged; concurrent changes commit in admission order and each announces its revision; a dropped reply still commits and announces; close waits for the admitted write. - `removeWorktree` answers `in_use` while an association or a stored workspace remains; a failed or cancelled removal keeps the record; a successful removal deletes it; a concurrent creation waits for the removal and then either associates with the surviving directory or fails on the missing workspace. - A call in flight when the generation closes ends `closed`; a dropped callback keeps the record. @@ -187,7 +189,7 @@ Material uncertainty: a process death during the caller's removal step leaves th | §4 rule 7 | Callers use these operations; no caller reads a row, a writer generation or a lock. | | §4 rule 8 | No infrastructure change; requirements are listed below. | | §4 rule 9 | The store publishes no Timeline fact of its own; the attached worktree stays a process fact. | -| §7.2 ids and values | Requests and replies are data; the worktree value crosses, and the removal step crosses as a callback by reference. No object crosses. | +| §7.2 ids and values | Requests and replies are data; the title change and the worktree removal step cross as callbacks by reference. No object crosses. | | §7.2 one public face | The service is marked on the SessionStore type under the existing `store` name; `Store`, `SessionMetadata` and `WorktreeAssociations` do not exist beside it. | | §7.2 caller mechanisms | The exclusion, the title admission and the record settlement stay inside the owner; callers handle business errors only. | | ADR 002 D1 | Process scope: the Session row set and its records outlive a Session. | @@ -219,6 +221,34 @@ pub struct Worktree { pub subtree: String, } +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Title { + pub text: String, + pub source: TitleSource, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TitleSource { + Auto, + Manual, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TitleState { + pub revision: u64, + pub title: Option, +} + +/// The caller's decision: the current title and revision in, the next title (none clears) or its own refusal out. +pub type ChangeFn = Arc< + dyn Fn(TitleState) -> rutis::host::BoxFuture<'static, Result<Option<Title>, Rejected>> + + Send + + Sync, +>; + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Removed { @@ -311,6 +341,16 @@ impl SessionStore { // ... } + pub async fn set_title( + &self, + caller: &Ctx, + request: SetTitle, + change: ChangeFn, + cancelled: CancelledFn, + ) -> Result<TitleReply, StoreError> { + // ... + } + pub async fn remove_worktree( &self, caller: &Ctx, From 415aa6df340413ba5cf99e18221dc017e6012395 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Mon, 23 Nov 2026 15:17:55 +0800 Subject: [PATCH 04/19] docs(storage): align the storage contracts with their callers SessionStore: query serves loaded and unloaded Sessions; the store owns the Timeline operations and the timelineStore face, bound by SessionScope at the Session instance. SessionFiles: put answers the path a read tool opens; write replaces an existing file under the same id and path; remove deletes one Session file. SqliteStorage: Settings gains a change operation under the row's exclusion beside the user path's compare-and-set; the Provider group carries the record projections, candidate and page queries, source activation and adoption, edit commits and legacy import. Refs #2018 Refs #2015 --- docs/design/plugins/SessionFiles.md | 29 +++++++++++++++++++++++++++- docs/design/plugins/SessionStore.md | 9 ++++----- docs/design/plugins/SqliteStorage.md | 29 ++++++++++++++++++++-------- 3 files changed, 53 insertions(+), 14 deletions(-) diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md index 565e2a92e0..ed4c115c70 100644 --- a/docs/design/plugins/SessionFiles.md +++ b/docs/design/plugins/SessionFiles.md @@ -26,9 +26,11 @@ Callers keep: | --- | --- | --- | | Store produced bytes under a new file id for a Session | No: the reservation, the file write and the ownership commit are one ordered protocol; a caller composing them would drive a half transaction | `put` | | Import a host file the user or model named as a Session file | No: the source is outside the file namespace and the size limit must stop the copy before it lands | `import` | +| Replace the bytes of an existing Session file under the same id and path | No: the id, the path and the ownership row are the owner's; a replace must keep the read tool's path valid | `write` | | Read a Session file for a model request or a UI | No: the caller cannot read the owner's directory or the file id's row | `read` | | Record a command output path as owned by the Session | No: ownership is the owner's row and the path must stay inside the Session's output directory | `register` | | Answer whether a path or file id belongs to the Session | No: the answer composes two ownership tables and the file directory mapping | `owns` | +| Remove a Session file and its ownership row | No: the directory entry and the row are the owner's | `remove` | | List every path the Session owns, for deletion or for a grant | No: the caller has no row access | `ownedPaths` | An operation exists only where its row says No. @@ -63,9 +65,11 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, bytes}` | `{fileId, size}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, bytes}` | `{fileId, path, size}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, size}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, bytes}` | `{fileId, path, size}` | Before the replacement; the old bytes stay | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `read` | Read one Session file whole, within the owner's limit | `{sessionId, fileId}` | `{bytes}` | While the file is read; nothing changes | `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `remove` | Remove one Session file and its ownership row; a file the Session does not own answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal | `not_found`, `node_unavailable`, `storage` | | `register` | Record an output path as owned by the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `storage` | | `owns` | Whether a path or file id belongs to the Session | `{sessionId, path}` | `{owned}` | While the path is resolved | `node_unavailable`, `cancelled`, `storage` | | `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `node_unavailable`, `storage` | @@ -90,7 +94,9 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | --- | --- | --- | --- | --- | --- | | `put` | Reserve the file under the generation, write the bytes through FileStorage, commit the ownership row while the generation and the Session still exist | The reservation and the written bytes are abandoned; the sweep removes them; no owned row | The write completes under the owner's task, or the reservation expires with the generation; the sweep removes unowned bytes | Admission stops; admitted writes finish; a new generation sweeps the old one's pending rows | FileSystem by FileStorage; rows and sweep by SessionFiles | | `import` | Open the source, check size, copy through FileStorage into a temporary file, commit ownership | The temporary file is removed; no owned row | The copy completes or is abandoned; the sweep removes what no row owns | As `put` | Source and temporary file by FileStorage; rows by SessionFiles | +| `write` | Resolve the file id, write the new bytes through FileStorage under the same path, keep the row | Before the replacement: the old bytes stay | The write completes or is abandoned | As `put` | File and path by FileStorage; row by SessionFiles | | `read` | Resolve the file id under the generation's directory, read the bytes within the limit | The read stops; nothing changes | The read stops | Pending reads end `closed` | FileStorage | +| `remove` | Resolve the file id, remove the directory entry through FileStorage, delete the row | None | The call ends | Rows stay for the next generation | File and row by SessionFiles | | `register` | Check the Session and the output directory, insert the ownership row | None | The row stays; a later Session delete removes it | Rows stay for the next generation | SessionFiles | | `owns` | Resolve the path, check the output row, else map the file directory and the file id row | The resolution stops | Nothing to release | Pending calls end `closed` | SessionFiles | | `ownedPaths` | Read both ownership rows, map file ids to the directory | None | Nothing to release | Rows stay | SessionFiles | @@ -110,6 +116,8 @@ Flow tests on the owner: - `put` reserves, writes and commits; a cancelled put leaves no owned row and the sweep removes the bytes; a second put with the same name gets a new file id. - `import` refuses a directory, a non-regular file and a source over the limit without landing anything. +- `write` keeps the file id and path and replaces the bytes; an unknown id answers `not_found`; the old bytes survive a cancelled write. +- `remove` answers success for a file the Session does not own, deletes the file and the row for an owned one, and never removes another Session's file. - `read` answers `not_found` for another Session's file id and for an unknown id; a file over the limit is never stored. - `register` refuses a path outside the output directory; `owns` answers true for a registered output and for a Session file path, and false for another Session's file. - A Session delete releases the rows; the sweep removes the bytes; a file still owned by another Session survives. @@ -158,6 +166,7 @@ use rutis::Ctx; #[serde(rename_all = "camelCase")] pub struct StoredFile { pub file_id: String, + pub path: String, pub size: u64, } @@ -207,6 +216,15 @@ impl SessionFiles { // ... } + pub async fn write( + &self, + caller: &Ctx, + request: WriteFile, + cancelled: CancelledFn, + ) -> Result<StoredFile, SessionFileError> { + // ... + } + pub async fn read( &self, caller: &Ctx, @@ -216,6 +234,15 @@ impl SessionFiles { // ... } + pub async fn remove( + &self, + caller: &Ctx, + request: RemoveFile, + cancelled: CancelledFn, + ) -> Result<(), SessionFileError> { + // ... + } + pub async fn register( &self, caller: &Ctx, diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 0fa7a8af88..55f3ea6082 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -2,7 +2,7 @@ Scope: process. Issue: #2018. -SessionStore owns the stored Session: its rows, its grants, its reply language, its title revision, its worktree records, the exclusion that keeps those records consistent with Session creation, and the Timeline storage engine those rows are read through. This document is the owner's target contract. The current implementation is described in [Session rows §5.2](../resource-faces.md#52-session-rows) and [Native storage format](../appserver/native-storage-format.md). The Session-scoped `timelineStore` face is published by SessionScope and is not covered here; the requirement this contract raises for it is at the end. +SessionStore owns the stored Session: its rows, its grants, its reply language, its title revision, its worktree records, the exclusion that keeps those records consistent with Session creation, and the Timeline storage engine those rows are read through. This document is the owner's target contract. The current implementation is described in [Session rows §5.2](../resource-faces.md#52-session-rows) and [Native storage format](../appserver/native-storage-format.md). The Session-scoped `timelineStore` face carries this owner's Timeline operations; SessionScope binds that face at the Session instance ([#2093](https://github.com/arcships/dim/pull/2093)). ## Use and scope: responsibility split @@ -37,7 +37,7 @@ Callers keep: | Read a stored Session's configuration without loading the Session | No: the caller has no row access and must not parse a stored record | `sessionConfig` | | Read the configuration text a fork copies | No: the text must be copied byte for byte | `sessionConfigText` | | List stored Sessions as one page, filtered and ordered by the storage contract | No: the page is a consistent read over the catalog row, the Session row and the title | `catalog` | -| Read an unloaded Session's history | No: the caller has no Timeline row access | `query` | +| Read a Session's stored history, loaded or not | No: the caller has no Timeline row access | `query` | | Read the Session's grants | No: the caller has no row access | `grants` | | Add or remove one grant | No: the upsert rule that keeps a write grant is the owner's invariant | `addGrant`, `removeGrant` | | Write the reply language into the stored configuration | No: the caller must not rewrite the stored record | `setLanguage` | @@ -110,7 +110,7 @@ Every operation takes one request object and answers one reply object. Writes ar | `sessionConfig` | A stored Session's decoded configuration | `{id}` | `{config?}` | None | `not_found`, `storage` | | `sessionConfigText` | A stored Session's configuration text, byte for byte | `{id}` | `{configText?}` | None | `not_found`, `storage` | | `catalog` | One stored Session page | `{request, agent?, version, hosts, closed}` | the stored page | While the page is read | `invalid`, `cancelled`, `storage` | -| `query` | One consistent history read for an unloaded Session | `{scope, query, page?}` | the query result | While the page is read | `storage`, `cancelled` | +| `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not) | `{scope, query, page?}` | the query result | While the page is read | `storage`, `cancelled` | | `grants` | The Session's grant set | `{id}` | `{grants}` | None | `storage` | | `addGrant` | Add one grant, never downgrading a write grant | `{id, path, kind, mode}` | `{}` | None | `not_found`, `invalid`, `storage` | | `removeGrant` | Remove one grant; an absent grant counts as removed | `{id, path}` | `{}` | None | `storage` | @@ -200,8 +200,7 @@ Material uncertainty: a process death during the caller's removal step leaves th ## Requirements raised to mechanism owners -1. **SessionScope (#2025): one spelling for the Timeline reads.** `store.query` and `store.sessionConfig` read the same engine as the Session-scoped `timelineStore`'s `query` and `sessionConfig`. The engine has one operation set; publish it once. The process read must stay reachable for an unloaded Session, so the contract asks SessionScope to state which face owns which operation and to remove the duplicate name. Probe: `store.query` and `timelineStore.query` return the same result for the same scope and through; a caller outside a Session uses the process operation. -2. **SessionScope (#2025): the `timelineStore` binding.** SessionStore constructs the engine and the Session-scope binding; the binding is assembly infrastructure. The contract assumes SessionScope owns the binding's installation and does not hand the binding to a process caller; a comment on #2025 states the requirement. +1. **SessionScope (#2025): `timelineStore` ownership aligned.** This owner owns the Timeline operations and the `timelineStore` face; SessionScope binds that face at the Session instance. The face does not carry `createSession`, `releaseSession`, `rollbackSession` or `append`; those belong to the store's own creation and commit paths. The process `store.query` and `store.sessionConfig` are the same engine's reads for callers outside a Session (loaded or not) and keep one implementation. A comment on #2025 records the alignment. ## Binding appendix diff --git a/docs/design/plugins/SqliteStorage.md b/docs/design/plugins/SqliteStorage.md index c247461c0b..3b576bc792 100644 --- a/docs/design/plugins/SqliteStorage.md +++ b/docs/design/plugins/SqliteStorage.md @@ -15,7 +15,7 @@ SqliteStorage owns: - **Offline operations.** Backup, restore and vacuum, each holding the same lease and refusing while a daemon owns the store. - **The capacity value.** Database bytes, WAL bytes and reclaimable bytes. -The stored form of each group of rows belongs to a data owner: the Timeline batches and positions to the Session store's engine, the Agent records to the Agent directory, the Settings documents to Settings, the Provider selection and preferences to Provider. Each group's request and reply shape is that owner's persistence contract; this contract names the transactions and keeps their boundaries. +The stored form of each group of rows belongs to a data owner: the Timeline batches and positions to the Session store's engine, the Agent records to the Agent directory, the Settings documents to Settings, the Provider records to Provider. Each group's operations and request and reply shapes are defined here; the data owner composes them and owns the business meaning. Callers keep: @@ -28,8 +28,8 @@ Callers keep: | Admit and commit a Timeline batch round | No: one grouped transaction, the writer queue and the per-Session fallback are the engine's | `commitTimelineRound` and the Timeline operations | | Read a Timeline position, session configuration or branch set | No: the caller cannot read the file | `head`, `batchEnd`, `batchEndAt`, `branches`, `sessionConfig`, `createSession` | | Load, save or delete Agent records and their relations | No: the records are rows with one writer and one transaction | the Agent record group | -| Read, import and replace Settings documents | No: the version check and the document row are one transaction | the Settings group | -| Read and write Provider selection and preferences | No: the scope version and the selected model are one transaction | the Provider group | +| Read, import, change and replace Settings documents | No: the change must run under the row's exclusion, and the version check and the write are one transaction | the Settings group | +| Read and commit Provider records, selections and preferences | No: each read, activation, adoption and edit is one transaction with its own precondition | the Provider group | | Report the store's own bytes | No: only the process holding the file knows them | `storageReport` | | Read and write Session file ownership rows | No: they belong to SessionFiles | not on this face: SessionFiles' private row operations | @@ -45,7 +45,7 @@ let owners = storage.owners(Empty {}).await?; let repair = storage.unfinishedOwned(Empty {}).await?; ``` -Settings replaces a document under its expected version. +Settings applies a change to a stored document under the row's exclusion. ```rust let next = storage.replace_user(ReplaceUser { @@ -79,7 +79,17 @@ Every operation takes one request object and answers one reply object. A transac | Agent records | `save`, `delete` | Write one Agent record or remove it | `{id, profile, default, owner?}`, `{id}` | `{}` | None | `storage` | | Settings | `readUser` | One stored document and its version, or none | `{source}` | `{version, document}?` | None | `storage` | | Settings | `importUserIfAbsent` | Insert a validated document and its provenance if absent; return the winning row | `{source, document, importedRevision}` | `{version, document}` | None | `storage` | -| Settings | `replaceUser` | Replace a document under its expected version | `{source, expectedVersion, decision}` | `{version}` | None | `missing`, `conflict`, `overflow`, `rejected`, `storage` | +| Settings | `changeUser` | Apply the caller's change to a stored document under the row's exclusion | `{source}` + `change` | `{version, document}` | Before the write; the change's future is dropped | `rejected`, `storage` | +| Settings | `replaceUser` | Replace a document under its expected version (the user path's compare-and-set) | `{source, expectedVersion, decision}` | `{version}` | None | `missing`, `conflict`, `overflow`, `rejected`, `storage` | +| Provider | `readProviderRecord` | One stored projection of a Provider record (header, all, mutable, one model, selected models) | `{providerId, projection}` | `{record}?` | None | `storage` | +| Provider | `providerCandidates` | Candidate lookup by criteria | `{criteria}` | `{candidates}` | None | `storage` | +| Provider | `listProviders` | Provider list with its filter and order | `{filter}` | `{providers}` | None | `storage` | +| Provider | `queryProviderModels` | One model page with its ordering and limit | `{page}` | `{models, next?}` | None | `storage` | +| Provider | `providerManagementPage` | One management window | `{page}` | the page | None | `storage` | +| Provider | `activateSource` | Activate one source revision with its bundle facts | `{revision, baseFacts}` | `{}` | None | `missing`, `conflict`, `storage` | +| Provider | `adoptProvider` | Adopt one provider's source at a revision | `{providerId, revision, baseFacts}` | `{}` | None | `missing`, `conflict`, `storage` | +| Provider | `commitProviderEdit` | One edit family under its own precondition, answering the committed projection | `{providerId, edit}` | `{version, projection}` | None | `missing`, `conflict`, `storage` | +| Provider | `importProviderLegacy` | Import one legacy batch and answer the item results | `{batch}` | `{items}` | None | `storage` | | Provider | `readSelection`, `readPreferences` | One stored selection or preference | `{scope}`, `{providerId, modelId}` | the stored value or none | None | `storage` | | Provider | `writeSelection` | Write the selected model under the scope's expected version | `{scope, expectedVersion, selection}` | the committed selection and version | None | `conflict`, `storage` | | Capacity | `storageReport` | The store's own file bytes, WAL bytes and reclaimable bytes | `{}` | `{databaseBytes, walBytes, reclaimableBytes}` | None | `storage` | @@ -95,7 +105,7 @@ The file-ownership row operations (`reserveFile`, `commitFile`, `abandonFile`, ` | `missing` | The document or record does not exist; the caller decides whether to create it | | `conflict` | Another writer committed at a different version; re-read and decide | | `overflow` | The version or the scope exceeded its bound; the caller reports it as a storage failure | -| `rejected` | A protected field was changed; the caller keeps the user's document and reports the field | +| `rejected` | The caller's change refused with its own `code` and `message`, or a protected field was changed; the caller keeps the user's document and acts on that code | The engine does not answer `not_found`: a missing row is the data owner's business answer, expressed by that owner's operation. @@ -105,6 +115,7 @@ The engine does not answer `not_found`: a missing row is the data owner's busine | --- | --- | --- | --- | --- | --- | | Open, upgrade, verify | Open the file, take the lease, read and write the format, run the ordered upgrades in one transaction, start the writer and the read pool | Not applicable: assembly admits the daemon once | Not applicable | A failed open leaves the previous format, or the startup note names the newer store | File and lease by SqliteStorage; the process exits | | `commitTimelineRound` | Admit the round, encode grouped by Session, commit one transaction per group, answer one outcome per distinct Session | Before the commit; nothing is written | The admitted round completes; the reply may be lost | Admission stops; the admitted round ends before close | Rows by SqliteStorage; publication by the Session store | +| `changeUser` | Take the source's exclusion, read the current document, call `change`, write the returned document as the next version, release | Before the write: the change's future is dropped, the document is unchanged, `cancelled` | The change's future ends; the same release applies | In-flight changes finish or end `closed`; the generation releases its exclusions | Exclusion by SqliteStorage; the change's future by the calling row | | Other writes | One transaction | None after it starts | The transaction completes; the reply may be lost | Admitted writes end before close | SqliteStorage | | Reads | One consistent read on a pooled connection | None; the read is bounded | Nothing to release | Pending reads end `closed` | SqliteStorage | | `storageReport` | Read the file sizes and the free-page count | None | Nothing to release | Pending calls end `closed` | SqliteStorage | @@ -123,7 +134,9 @@ Flow tests on the owner: - Opening a newer format refuses and leaves the file unchanged; an upgrade is one transaction; a second process fails to open while the lease is held. - `commitTimelineRound` commits one outcome per distinct Session, keeps the input order and answers an outcome for a failed group without dropping the others. +- `changeUser` calls the change under the source's exclusion; a change that returns `Rejected` leaves the document and version unchanged; a committed change answers the next version. - `replaceUser` on a stale version answers `conflict`; a protected-field change answers `rejected` without writing; `importUserIfAbsent` returns the winning row. +- Provider records: a projection read returns only its fields; a stale activation or edit answers `conflict`; a commit answers the committed projection; a legacy import answers one item result per entry. - `writeSelection` on a stale scope answers `conflict`; `readPreferences` answers none for an absent preference. - `storageReport` answers the file, WAL and free-page values; the client method returns the same values. - Closing drains the running calls, checkpoints and releases the lease; an offline tool cannot open while the daemon owns it. @@ -155,8 +168,8 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -1. **Settings (#2017), Provider (#2019), Agent directory (#2020): your group's contract.** The operations in the Settings, Provider and Agent record groups are your persistence contracts, executed by this engine. Your contracts own their request, reply and error shapes; this contract keeps the transactions and does not reinterpret them. A comment on each sub-issue states the split. -2. **SessionScope (#2025): the Timeline operations have one face.** The engine owns the Timeline operations; the Session-scoped `timelineStore` publishes the same engine per Session. `store.query` and `store.sessionConfig` read the same engine from the process side. The engine has one operation set; SessionScope's contract states which face owns which operation and removes the duplicate name. +1. **Settings (#2017), Provider (#2019), Agent directory (#2020): these groups are defined here.** The Settings, Provider and Agent record operations and their request, reply and error shapes are the ones above; the engine executes them and adds no business rule. The Settings change and the Provider edit families carry their callers' decisions as data or callbacks; the data owner composes the operations and owns the business meaning. Comments on the three sub-issues state the split. +2. **SessionScope (#2025): `timelineStore` ownership.** The Session store owns the Timeline operations and the `timelineStore` face; SessionScope binds that face at the Session instance. The face does not carry `createSession`, `releaseSession`, `rollbackSession` or `append`; those belong to the store's creation and commit paths. The process `store.query` and `store.sessionConfig` are the same engine's reads for callers outside a Session. ## Binding appendix From 2d8ad14dea401feb7e446bd67f1f16146d6a1116 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Mon, 23 Nov 2026 19:28:39 +0800 Subject: [PATCH 05/19] docs(storage): remove the engine's proxy queries and fold fork text into the fork SqliteStorage's public face is the capacity read and the offline operations. The Settings, Provider, Agent record and Timeline transactions are crate-private implementations of their data owners; the engine no longer answers their reads or writes under sqliteStorage. SessionStore.fork reads the source configuration text itself and takes the target text from a caller callback that runs under the fork's exclusion; the source text cannot change between the read and the copy. sessionConfigText is removed. Refs #2018 Refs #2015 --- docs/design/plugins/SessionStore.md | 32 +++--- docs/design/plugins/SqliteStorage.md | 146 ++++++++------------------- 2 files changed, 64 insertions(+), 114 deletions(-) diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 55f3ea6082..bdd674a4be 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -30,12 +30,11 @@ Callers keep: | --- | --- | --- | | Create an admitted Session and its optional worktree association | No: the rows, the owner row, the main branch, the catalog row and the association are one transaction; a partial write would publish a Session without its rows or an association without its Session | `create` | | Close a Session, then remove its output directories and rows | No: output removal, visible rows and Timeline rows must run under the Session exclusion and in this order; a caller composing them could delete a row a concurrent creation still names | `delete` | -| Copy a source Session's rows at a cut with the source's exact configuration text | No: the copy is bounded transactions; parsing and re-serializing the text would change bytes | `fork` | +| Copy a source Session's rows at a cut, deciding the target text from the source's exact text | No: the source text must be read and the target text written in one transaction, and the lifecycle owner's decision must run under the fork's exclusion | `fork` with a text callback | | Read a stored Session's creation origin and leader link for an attach reply | No: the caller has no row access | `creationRecord` | | Read the Agent that owns a stored Session before its delete notice | No: the caller has no row access | `owner` | | Ask whether an id has stored rows without loading a Session | No: the check spans five tables | `hasRecords` | | Read a stored Session's configuration without loading the Session | No: the caller has no row access and must not parse a stored record | `sessionConfig` | -| Read the configuration text a fork copies | No: the text must be copied byte for byte | `sessionConfigText` | | List stored Sessions as one page, filtered and ordered by the storage contract | No: the page is a consistent read over the catalog row, the Session row and the title | `catalog` | | Read a Session's stored history, loaded or not | No: the caller has no Timeline row access | `query` | | Read the Session's grants | No: the caller has no row access | `grants` | @@ -63,8 +62,12 @@ store.create(Create { Agents forks and deletes; both mistakes are the caller's to fix, and a concurrent deletion is not an error the caller retries. ```rust -let source_text = store.sessionConfigText(ForkSource { id: source }, cancelled.clone()).await?; -store.fork(Fork { source, id: fork, at, config_text: source_text.config_text }, cancelled).await?; +// The source text arrives in the callback; the initialTitle decision runs under the fork's exclusion. +let text: TextFn = Arc::new(move |source: String| { + let next = strip_initial_title(&source); // lifecycle owner's decision + Box::pin(async move { Ok(next) }) +}); +store.fork(Fork { source, id: fork, at }, text, cancelled).await?; let removed = store.delete(Delete { id }, cancelled).await?; ``` @@ -93,7 +96,7 @@ store.removeWorktree(Directory { repository, root }, remove, cancelled.clone()). ### Dependencies -The engine's data face `sqliteStorage` for every row read and write and for the Timeline batches. The file owner `sessionFiles` for the Session file steps a delete releases. Neither dependency crosses back into SessionStore. The assembly provides both; deployment chooses the instance. +The engine's crate-private operations for every row read and write and for the Timeline batches; `sqliteStorage` is not a service face. The file owner `sessionFiles` for the Session file steps a delete releases. Neither dependency crosses back into SessionStore. The assembly provides both; deployment chooses the instance. ### Operations @@ -103,12 +106,11 @@ Every operation takes one request object and answers one reply object. Writes ar | --- | --- | --- | --- | --- | --- | | `create` | Write one admitted Session and its optional worktree association | `{id, config, agentId, protocolVersion, leader?, origin, worktree?}` | `{}` | Before the transaction starts; a dropped future does not undo a commit | `invalid`, `workspace_missing`, `storage` | | `delete` | Remove a closed Session's output, visible rows and Timeline rows | `{id}` | `{hadRows}` | Before the first step; after the first commit the steps run to their end | `storage` | -| `fork` | Copy a source's rows at a cut with the supplied configuration text | `{source, id, at, configText}` | `{}` | Before the first transaction | `invalid`, `storage` | +| `fork` | Copy a source's rows at a cut, with the target text decided from the source text under the fork's exclusion | `{source, id, at}` + `text` | `{}` | Before the first transaction; the callback's future is dropped | `invalid`, `rejected`, `storage` | | `creationRecord` | One Session's origin and leader link | `{id}` | `{origin, leader?}` | None | `not_found`, `storage` | | `owner` | The Agent that owns a stored Session | `{id}` | `{agentId?}` | None | `storage` | | `hasRecords` | Whether an id has any stored row | `{id}` | `{exists}` | None | `storage` | | `sessionConfig` | A stored Session's decoded configuration | `{id}` | `{config?}` | None | `not_found`, `storage` | -| `sessionConfigText` | A stored Session's configuration text, byte for byte | `{id}` | `{configText?}` | None | `not_found`, `storage` | | `catalog` | One stored Session page | `{request, agent?, version, hosts, closed}` | the stored page | While the page is read | `invalid`, `cancelled`, `storage` | | `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not) | `{scope, query, page?}` | the query result | While the page is read | `storage`, `cancelled` | | `grants` | The Session's grant set | `{id}` | `{grants}` | None | `storage` | @@ -133,7 +135,7 @@ Every operation takes one request object and answers one reply object. Writes ar | `workspace_missing` | The creation's `cwd` no longer is a directory; the caller reports the failed creation and discards the worktree | | `not_found` | No stored Session has the id; the caller decides whether that is a business error or an answer | | `in_use` | A Session association or a stored workspace still names the directory; delete that Session or refuse the removal | -| `rejected` | The caller's change or removal step refused with its own `code` and `message`; the title or the record is unchanged and the caller acts on that code | +| `rejected` | The caller's change, text or removal step refused with its own `code` and `message`; nothing was written and the caller acts on that code | | `cancelled` | The caller stopped the read; nothing changed | | `closed` | This generation is unloading; call the replacement generation | | `storage` | The store failed; the caller reports the failure and keeps the Session or worktree for a retry | @@ -144,8 +146,8 @@ Every operation takes one request object and answers one reply object. Writes ar | --- | --- | --- | --- | --- | --- | | `create` | Validate the id and the workspace, take the exclusion, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller keeps the id it supplied and decides whether to publish or delete the Session | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | | `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove visible and Timeline rows, schedule the file sweep | Before the first commit: every row stays. After: the steps run to their end | The work continues under the owner's task; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | -| `fork` | Take the exclusion, copy in bounded transactions, write the target row with the supplied text, commit | Before the first copy | The copy continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | -| `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `sessionConfigText`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | +| `fork` | Take the exclusion, read the source text, call `text`, copy in bounded transactions with the returned text, write the target row, commit | Before the first copy; a refused text step copies nothing | The copy continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | +| `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | | `catalog`, `query` | One consistent read under the caller's token | The read stops; no partial page | Nothing to release | Pending reads end `cancelled` | SessionStore | | `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | | `setTitle` | Admit the write behind earlier admitted writes, read the current title, call `change` under the serialization, write the returned title as revision + 1, commit, announce, answer the revision | Dropping the reply never cancels the admitted write; a change that refuses leaves the title unchanged | The change callback is revoked before it returns; the admitted write fails and the title stays | Close stops admission, waits for every admitted write | SessionStore; the change computes only | @@ -153,7 +155,7 @@ Every operation takes one request object and answers one reply object. Writes ar ## Exceptions with reasons -- `create` and `fork` take the caller's already-validated configuration and the fork text: validating the protocol, the collaboration role and the cut belongs to the Session lifecycle owner, and re-serializing the text would change bytes. +- `create` takes the caller's already-validated configuration; `fork` reads the source text itself and calls the caller's text step under the fork's exclusion, so the lifecycle owner's `initialTitle` decision cannot race the copy and the copied bytes stay the source's text. - `delete` does not close the Session, remove its Agent admission slot or remove the worktree: closing is Agents', and a managed worktree is removed by ManagedWorktrees under `removeWorktree`. - `setTitle` runs the caller's change under the owner's serialization: the change only computes the next title from the current title and revision, and returns its own refusal; the reply may be lost, so the caller re-reads rather than assumes failure. - `removeWorktree` runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. @@ -165,7 +167,7 @@ Flow tests on the owner: - `create` writes the Session, the owner, the main branch, the catalog row and the worktree association together; a failed association writes nothing. - `delete` removes output first, then the rows; a failure before the first commit leaves every row; a concurrent creation waits for an in-flight removal and then either sees the surviving directory or fails on the missing workspace. -- `fork` copies the supplied text unchanged and never parses it. +- `fork` calls the text step with the source text, copies the returned text unchanged, and a refused step copies nothing. - `addGrant` on a missing Session answers `not_found`; `removeGrant` on an absent grant answers success; a read grant never downgrades a write grant. - The change receives the current title, its source and revision; a change that returns `Rejected` leaves the title and revision unchanged; concurrent changes commit in admission order and each announces its revision; a dropped reply still commits and announces; close waits for the admitted write. - `removeWorktree` answers `in_use` while an association or a stored workspace remains; a failed or cancelled removal keeps the record; a successful removal deletes it; a concurrent creation waits for the removal and then either associates with the surviving directory or fails on the missing workspace. @@ -241,6 +243,11 @@ pub struct TitleState { pub title: Option<Title>, } +/// The caller's fork decision: the source's exact configuration text in, the target's text or its own refusal out. +pub type TextFn = Arc< + dyn Fn(String) -> rutis::host::BoxFuture<'static, Result<String, Rejected>> + Send + Sync, +>; + /// The caller's decision: the current title and revision in, the next title (none clears) or its own refusal out. pub type ChangeFn = Arc< dyn Fn(TitleState) -> rutis::host::BoxFuture<'static, Result<Option<Title>, Rejected>> @@ -335,6 +342,7 @@ impl SessionStore { &self, caller: &Ctx, request: Fork, + text: TextFn, cancelled: CancelledFn, ) -> Result<(), StoreError> { // ... diff --git a/docs/design/plugins/SqliteStorage.md b/docs/design/plugins/SqliteStorage.md index 3b576bc792..92bf384d86 100644 --- a/docs/design/plugins/SqliteStorage.md +++ b/docs/design/plugins/SqliteStorage.md @@ -2,7 +2,7 @@ Scope: process. Issue: #2018. -SqliteStorage owns the database file, the lease that admits one process to it, the format version and its upgrades, the writer and the read connections, and the transactions other owners' records are read and written in. This document is the owner's target contract. The current implementation is described in [Native storage format](../appserver/native-storage-format.md) and [Resource owner operations](../contracts/resource-owner-operations.md). +SqliteStorage owns the database file, the lease that admits one process to it, the format version and its upgrades, the writer and the read connections, and the transactions the data owners' rows are read and written in. This document is the owner's target contract. The current implementation is described in [Native storage format](../appserver/native-storage-format.md) and [Resource owner operations](../contracts/resource-owner-operations.md). ## Use and scope: responsibility split @@ -11,11 +11,11 @@ SqliteStorage owns: - **The file and its lease.** `<db>` and `<db>.lock`; one process opens the store, upgrades it and holds the lock until close; an offline tool takes the same lock. - **The format.** The version row, the schema, the ordered upgrades and the refusal of an unsupported format. - **The connections.** One writer connection with its queue, a read pool, the WAL checkpoint and the close drain. -- **Transactions and reads.** One commit or one consistent read per call; the engine does not interpret the rows. +- **Transactions and reads.** One commit or one consistent read per call; the engine does not interpret the rows. These operations are the engine's private implementation for the data owners; they are not a service face. - **Offline operations.** Backup, restore and vacuum, each holding the same lease and refusing while a daemon owns the store. -- **The capacity value.** Database bytes, WAL bytes and reclaimable bytes. +- **The capacity value.** Database bytes, WAL bytes and reclaimable bytes, read through `storageReport`. -The stored form of each group of rows belongs to a data owner: the Timeline batches and positions to the Session store's engine, the Agent records to the Agent directory, the Settings documents to Settings, the Provider records to Provider. Each group's operations and request and reply shapes are defined here; the data owner composes them and owns the business meaning. +The rows belong to their data owners, and their operations live on those owners' faces: the Session rows and the Timeline batches to [SessionStore](SessionStore.md), the Agent records to Agents and Collaboration ([#2098](https://github.com/arcships/dim/pull/2098)), the Settings documents to Settings ([#2094](https://github.com/arcships/dim/pull/2094)), the Provider records to Provider ([#2096](https://github.com/arcships/dim/pull/2096)). The engine executes each owner's transactions and returns the stored form; it answers no business read or write on its public face and is not in the catalog for those rows. Callers keep: @@ -23,123 +23,81 @@ Callers keep: - **When to read or write.** The Session lifecycle, the Agent directory's startup repair, the Settings document's validation, the Provider's edit preconditions. - **Their own lifecycle.** The engine never closes a caller's owner or decides a caller's business. -| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| Requirement (public callers) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| Admit and commit a Timeline batch round | No: one grouped transaction, the writer queue and the per-Session fallback are the engine's | `commitTimelineRound` and the Timeline operations | -| Read a Timeline position, session configuration or branch set | No: the caller cannot read the file | `head`, `batchEnd`, `batchEndAt`, `branches`, `sessionConfig`, `createSession` | -| Load, save or delete Agent records and their relations | No: the records are rows with one writer and one transaction | the Agent record group | -| Read, import, change and replace Settings documents | No: the change must run under the row's exclusion, and the version check and the write are one transaction | the Settings group | -| Read and commit Provider records, selections and preferences | No: each read, activation, adoption and edit is one transaction with its own precondition | the Provider group | | Report the store's own bytes | No: only the process holding the file knows them | `storageReport` | -| Read and write Session file ownership rows | No: they belong to SessionFiles | not on this face: SessionFiles' private row operations | +| Back up, restore or vacuum the store while no daemon owns it | No: the operation needs the file lease and the format check | `backup`, `restore`, `vacuum` | +| Bind the daemon's endpoints after the database lock is held | No operation: the dependency orders loading | the `sqliteStorage` key in `injects` | -Every row above is No because the rows share one file, one writer and one close; the operations exist so callers do not hold the connection, the transaction or the file. +The transaction operations the data owners use are not on this face: Settings, Provider, Agents, Collaboration and SessionStore call them as crate-private operations of the engine, and each owner's contract owns the request, reply and error shapes. A caller that needs different data asks the row's owner, not the engine. ## Caller example -Agents loads its records and repairs unfinished ones at startup. +The client method `storage.report` reads the capacity value; the management row registers the method and calls the same operation. ```rust -let agents = storage.agents(Empty {}).await?; -let owners = storage.owners(Empty {}).await?; -let repair = storage.unfinishedOwned(Empty {}).await?; +let report = storage.storageReport(Empty {}).await?; +// { database_bytes, wal_bytes, reclaimable_bytes } ``` -Settings applies a change to a stored document under the row's exclusion. +The daemon's CLI runs an offline backup or vacuum while no daemon owns the file. ```rust -let next = storage.replace_user(ReplaceUser { - source, expected_version, decision, -}).await?; -``` - -SessionStore writes one Session creation through the engine's transaction. - -```rust -storage.create_session(CreateSession { session_id, config }).await?; +storage::backup_store(database.into(), destination.into())?; ``` ## Own contract ### Dependencies -None. The assembly provides the store; deployment chooses its instance. Offline tools take the same file lease through the owner's functions, not through the service. +None. The assembly provides the store; deployment chooses its instance. Offline tools take the same file lease through the owner's functions, not through the service. The data owners are the engine's crate-private users, not service callers. ### Operations -Every operation takes one request object and answers one reply object. A transaction is not cancelled once it starts; a long batch round takes the caller's cancellation token and cancels before its commit. The engine's errors are per operation; the caller maps them to its business errors. - -| Group | Operation | Intent | Request | Reply | Cancellation | Errors | -| --- | --- | --- | --- | --- | --- | --- | -| Timeline | `createSession` | Prepare the stored Session record and the main branch | `{sessionId, config}` | `{}` | None | `storage` | -| Timeline | `sessionConfig`, `branches`, `head` | One stored read | `{sessionId}`, `{sessionId}`, `{key}` | `{config}`, `{branches}`, `{sequence}` | None | `storage` | -| Timeline | `batchEnd`, `batchEndAt` | Validate a boundary or return the containing batch's end | `{key, sequence}` | `{}` or `{sequence}` | None | `storage` | -| Timeline | `commitTimelineRound` | Admit and commit one ordered round of batches grouped by Session | `{batches}` | `{sessions:[{sessionId, result}]}` | Before the commit | `cancelled`, `storage` | -| Agent records | `agents`, `owners`, `members`, `ledMembers`, `ownedAgents`, `memberSessions`, `agentOwner`, `unfinishedOwned` | One consistent read of the directory's records | `{}`, or one id | the existing record shapes | None | `storage` | -| Agent records | `save`, `delete` | Write one Agent record or remove it | `{id, profile, default, owner?}`, `{id}` | `{}` | None | `storage` | -| Settings | `readUser` | One stored document and its version, or none | `{source}` | `{version, document}?` | None | `storage` | -| Settings | `importUserIfAbsent` | Insert a validated document and its provenance if absent; return the winning row | `{source, document, importedRevision}` | `{version, document}` | None | `storage` | -| Settings | `changeUser` | Apply the caller's change to a stored document under the row's exclusion | `{source}` + `change` | `{version, document}` | Before the write; the change's future is dropped | `rejected`, `storage` | -| Settings | `replaceUser` | Replace a document under its expected version (the user path's compare-and-set) | `{source, expectedVersion, decision}` | `{version}` | None | `missing`, `conflict`, `overflow`, `rejected`, `storage` | -| Provider | `readProviderRecord` | One stored projection of a Provider record (header, all, mutable, one model, selected models) | `{providerId, projection}` | `{record}?` | None | `storage` | -| Provider | `providerCandidates` | Candidate lookup by criteria | `{criteria}` | `{candidates}` | None | `storage` | -| Provider | `listProviders` | Provider list with its filter and order | `{filter}` | `{providers}` | None | `storage` | -| Provider | `queryProviderModels` | One model page with its ordering and limit | `{page}` | `{models, next?}` | None | `storage` | -| Provider | `providerManagementPage` | One management window | `{page}` | the page | None | `storage` | -| Provider | `activateSource` | Activate one source revision with its bundle facts | `{revision, baseFacts}` | `{}` | None | `missing`, `conflict`, `storage` | -| Provider | `adoptProvider` | Adopt one provider's source at a revision | `{providerId, revision, baseFacts}` | `{}` | None | `missing`, `conflict`, `storage` | -| Provider | `commitProviderEdit` | One edit family under its own precondition, answering the committed projection | `{providerId, edit}` | `{version, projection}` | None | `missing`, `conflict`, `storage` | -| Provider | `importProviderLegacy` | Import one legacy batch and answer the item results | `{batch}` | `{items}` | None | `storage` | -| Provider | `readSelection`, `readPreferences` | One stored selection or preference | `{scope}`, `{providerId, modelId}` | the stored value or none | None | `storage` | -| Provider | `writeSelection` | Write the selected model under the scope's expected version | `{scope, expectedVersion, selection}` | the committed selection and version | None | `conflict`, `storage` | -| Capacity | `storageReport` | The store's own file bytes, WAL bytes and reclaimable bytes | `{}` | `{databaseBytes, walBytes, reclaimableBytes}` | None | `storage` | - -The file-ownership row operations (`reserveFile`, `commitFile`, `abandonFile`, `ownsFile`, `ownsOutput`, `ownedPaths`, `registerOutput`) are `pub(crate)` operations of SessionFiles, not this face. The `storage.report` client method registers through `managementMethods` and calls `storageReport`; the registration point is not a second operation. +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `storageReport` | The store's own file bytes, WAL bytes and reclaimable bytes | `{}` | `{databaseBytes, walBytes, reclaimableBytes}` | None | `storage` | +| `backup` | Copy a closed store and its sidecar files into an archive | the database path and the destination | `{}` | None; the tool runs alone | `owned`, `storage` | +| `restore` | Replace a store from an archive produced by `backup` | the archive and the destination | `{}` | None; the tool runs alone | `owned`, `format`, `storage` | +| `vacuum` | Remove the content rows no stored reference reaches and reclaim the file's free pages | the database path | the removed rows, content bytes and sizes | None; the tool runs alone | `owned`, `format`, `storage` | + +`storage.report` is the client method registered through `managementMethods`; the registration point calls `storageReport` and is not a second operation. The transaction operations the data owners use are private to the storage crate and are listed in their owners' contracts. ### Errors | Kind | What the caller does next | | --- | --- | -| `storage` | The transaction or read failed; the caller reports its own failure and retries the business step when that is safe | -| `cancelled` | The round stopped before its commit; nothing was written by this round | -| `missing` | The document or record does not exist; the caller decides whether to create it | -| `conflict` | Another writer committed at a different version; re-read and decide | -| `overflow` | The version or the scope exceeded its bound; the caller reports it as a storage failure | -| `rejected` | The caller's change refused with its own `code` and `message`, or a protected field was changed; the caller keeps the user's document and acts on that code | +| `storage` | The read or the offline operation failed; the caller reports its own failure | +| `owned` | Another process holds the file's lease; wait for it to exit and retry the offline operation | +| `format` | The file is not the current format; open it with the daemon that upgrades it, or with a matching version | -The engine does not answer `not_found`: a missing row is the data owner's business answer, expressed by that owner's operation. +The engine answers no business error: a missing row, a stale version or a refused change is the data owner's, expressed by that owner's operation. ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | Open, upgrade, verify | Open the file, take the lease, read and write the format, run the ordered upgrades in one transaction, start the writer and the read pool | Not applicable: assembly admits the daemon once | Not applicable | A failed open leaves the previous format, or the startup note names the newer store | File and lease by SqliteStorage; the process exits | -| `commitTimelineRound` | Admit the round, encode grouped by Session, commit one transaction per group, answer one outcome per distinct Session | Before the commit; nothing is written | The admitted round completes; the reply may be lost | Admission stops; the admitted round ends before close | Rows by SqliteStorage; publication by the Session store | -| `changeUser` | Take the source's exclusion, read the current document, call `change`, write the returned document as the next version, release | Before the write: the change's future is dropped, the document is unchanged, `cancelled` | The change's future ends; the same release applies | In-flight changes finish or end `closed`; the generation releases its exclusions | Exclusion by SqliteStorage; the change's future by the calling row | -| Other writes | One transaction | None after it starts | The transaction completes; the reply may be lost | Admitted writes end before close | SqliteStorage | -| Reads | One consistent read on a pooled connection | None; the read is bounded | Nothing to release | Pending reads end `closed` | SqliteStorage | | `storageReport` | Read the file sizes and the free-page count | None | Nothing to release | Pending calls end `closed` | SqliteStorage | +| `backup`, `restore`, `vacuum` | Take the same lease, operate on the file, release | Not applicable; the tool runs alone | Not applicable | Refused while a daemon holds the lease | The offline tool and SqliteStorage share the lease | | Close | Refuse new work, wait for the running calls, close the readers, checkpoint, close the writer, release the lease | Not applicable | In-flight calls finish | The next process opens after the lease is free | SqliteStorage | -| Offline backup, restore, vacuum | Take the same lease, operate on the file, release | Not applicable; the tool runs alone | Not applicable | Refused while a daemon holds the lease | The offline tool and SqliteStorage share the lease | +| Private transactions | The data owner's call runs on the writer or a pooled reader, under the open store's drain | The owner's operation decides its own cancellation | The writer completes or rolls back the transaction | The admitted calls end before close | SqliteStorage; the owner's contract owns the operation | ## Exceptions with reasons - Offline tools (`dim-migration`, backup, restore, vacuum) open the file under the same lease and write rows in the published format: an import or a repair runs while no daemon may own the store, and the format is the contract both sides implement. The lease is the exclusion; the format version is the gate. - `storageReport` is a client method and a service operation: the management method is a registration point (ADR 002), and the service operation is the same read for plugins. -- The engine's operations are named after their data owners' records because those owners define the shapes; the engine owns the stored form and the transaction, and adds no business rule. +- The data owners' transaction operations are crate-private: each owner's contract defines its request, reply and errors, and the engine executes them without interpreting the rows. Publishing them again under `sqliteStorage` would answer the owners' business on the engine's face. ## Verification Flow tests on the owner: - Opening a newer format refuses and leaves the file unchanged; an upgrade is one transaction; a second process fails to open while the lease is held. -- `commitTimelineRound` commits one outcome per distinct Session, keeps the input order and answers an outcome for a failed group without dropping the others. -- `changeUser` calls the change under the source's exclusion; a change that returns `Rejected` leaves the document and version unchanged; a committed change answers the next version. -- `replaceUser` on a stale version answers `conflict`; a protected-field change answers `rejected` without writing; `importUserIfAbsent` returns the winning row. -- Provider records: a projection read returns only its fields; a stale activation or edit answers `conflict`; a commit answers the committed projection; a legacy import answers one item result per entry. -- `writeSelection` on a stale scope answers `conflict`; `readPreferences` answers none for an absent preference. - `storageReport` answers the file, WAL and free-page values; the client method returns the same values. -- Closing drains the running calls, checkpoints and releases the lease; an offline tool cannot open while the daemon owns it. +- Closing drains the running owner calls, checkpoints and releases the lease; an offline tool cannot open while the daemon owns it. +- A backup round-trips through restore; vacuum refuses a store a daemon owns and a store whose format differs. +- The data owners' transactions are tested by their owners' flow tests; the engine's tests cover their commit, rollback and drain, not their business answers. ## Rule check @@ -147,36 +105,35 @@ Flow tests on the owner: | --- | --- | | §1 parts and Capabilities | SqliteStorage is one process part. It writes no Timeline fact of its own and is not a Capability. | | §2 scopes | Process: the file, the lease and the transactions are shared across Sessions. | -| §3 orthogonality | Every transaction belongs to one data owner's records; the engine interprets none. | +| §3 orthogonality | Every transaction belongs to one data owner's rows; the engine interprets none. | | §4 rule 1 | No command event. | | §4 rule 2 | No handoff. | | §4 rule 3 | No before callback. | | §4 rule 4 | No business rule. | -| §4 rule 5 | The grouped round keeps its commit and fallback order. | +| §4 rule 5 | The grouped round keeps its commit and fallback order; the round's operation is the Session store's. | | §4 rule 6 | No context input. | -| §4 rule 7 | Callers use these operations; no caller holds a connection or a transaction. | +| §4 rule 7 | The data owners use the engine's private operations; no caller holds a connection or a transaction. | | §4 rule 8 | No infrastructure change; requirements below. | | §4 rule 9 | The engine publishes no Timeline fact; the round is the Session store's publication path. | | §7.2 ids and values | Requests and replies are data; no connection, statement or transaction crosses. | -| §7.2 one public face | The service is marked on the SqliteStorage type under the existing `sqliteStorage` name; the hand-written dispatch adapter beside it is replaced. | -| §7.2 caller mechanisms | The writer queue, the read pool, the WAL and the drain stay inside the owner. | +| §7.2 one public face | The service is marked on the SqliteStorage type under the existing `sqliteStorage` name, with the capacity read only; the hand-written dispatch adapter beside it is replaced. | +| §7.2 no proxy query | The engine does not answer the data owners' business reads or writes on its face; each row's owner answers them. | | ADR 002 D1 | Process scope. | | ADR 002 D2 | No wiring plugin. | -| ADR 002 D3 | No dependencies; other owners depend on the engine. | +| ADR 002 D3 | No public dependencies; the data owners use the engine privately. | | ADR 002 D4 | The path and the format are structural configuration; no business setting. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | ## Requirements raised to mechanism owners -1. **Settings (#2017), Provider (#2019), Agent directory (#2020): these groups are defined here.** The Settings, Provider and Agent record operations and their request, reply and error shapes are the ones above; the engine executes them and adds no business rule. The Settings change and the Provider edit families carry their callers' decisions as data or callbacks; the data owner composes the operations and owns the business meaning. Comments on the three sub-issues state the split. +1. **Settings (#2094), Provider (#2096), Agents and Collaboration (#2098): your operations own the rows.** The Settings document operations, the Provider record operations and the Agent record operations are defined and answered by their owners' contracts. The engine is their crate-private implementation: it executes the transactions and returns the stored form, and no longer publishes these operations under `sqliteStorage`. A comment on each sub-issue records the split. 2. **SessionScope (#2025): `timelineStore` ownership.** The Session store owns the Timeline operations and the `timelineStore` face; SessionScope binds that face at the Session instance. The face does not carry `createSession`, `releaseSession`, `rollbackSession` or `append`; those belong to the store's creation and commit paths. The process `store.query` and `store.sessionConfig` are the same engine's reads for callers outside a Session. ## Binding appendix -The service is marked on the `SqliteStorage` type; the wire name stays `sqliteStorage`. The hand-written adapter type is deleted. `CancelledFn` is the binding's cancellation argument, used only by `commitTimelineRound`. +The service is marked on the `SqliteStorage` type; the wire name stays `sqliteStorage`. The hand-written adapter type is deleted. Only the capacity read is a service operation; the offline functions stay the owner's Rust functions, and the data owners' transactions are crate-private. ```rust -use dim_agent_capabilities::host::CancelledFn; use dim_agent_runtime::PublicService; use rutis::Ctx; @@ -192,16 +149,10 @@ pub struct Capacity { pub enum StorageError { #[error("{0}")] Storage(String), - #[error("the round was cancelled")] - Cancelled, - #[error("{0}")] - Missing(String), + #[error("another process owns the database")] + Owned, #[error("{0}")] - Conflict(String), - #[error("{0}")] - Overflow(String), - #[error("{0}: {1}")] - Rejected(String, String), + Format(String), } impl PublicService for SqliteStorage {} @@ -215,16 +166,7 @@ impl SqliteStorage { ) -> Result<Capacity, StorageError> { // ... } - - pub async fn commit_timeline_round( - &self, - caller: &Ctx, - request: Round, - cancelled: CancelledFn, - ) -> Result<RoundReply, StorageError> { - // ... - } } ``` -Every operation takes one request object, one reply object and the caller's `Ctx`; only `commitTimelineRound` waits and takes `CancelledFn`. +`backup_store`, `restore_store` and `vacuum_store` remain the owner's functions with the signatures the CLI and the migration tool use; they take the same lease and are not service operations. From 50ac5316fe35b7a6a7f1a12a2e6f2a39896e5a0f Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Mon, 23 Nov 2026 21:35:44 +0800 Subject: [PATCH 06/19] docs(storage): address the storage contract review SessionFiles: read pages by offset with the 64 KiB bound, import and put keep {fileId, path, bytes}, register leaves the output root with the caller, remove is idempotent, and the binding appendix defines its request, reply and error types. SessionStore: create validates the workspace inside the exclusion, every flow's ending is in the error list, setTitle is a plain fn that admits the write and returns the wait future, and the binding errors carry their codes. ManagedWorktrees: discard takes no cancellation, list and prune answer closed, the leftover branch rule is stated, and the appendix types are defined. SqliteStorage: the public face is storageReport and the offline operations; restore is excluded by its destination rule, not a lease. The named design documents now point at the contracts: resource faces, service faces, resource owner operations, session files, session title metadata, SessionTitle and Attachments. Refs #2018 Refs #2015 --- docs/design/appserver/session-files.md | 38 +-- .../appserver/session-title-metadata.md | 41 ++-- .../contracts/resource-owner-operations.md | 88 +------ docs/design/plugins/Attachments.md | 4 +- docs/design/plugins/ManagedWorktrees.md | 89 ++++--- docs/design/plugins/README.md | 6 +- docs/design/plugins/SessionFiles.md | 231 ++++++++++++------ docs/design/plugins/SessionStore.md | 175 ++++++++----- docs/design/plugins/SessionTitle.md | 16 +- docs/design/plugins/SqliteStorage.md | 46 ++-- docs/design/resource-faces.md | 178 ++------------ docs/design/service-faces.md | 12 +- 12 files changed, 439 insertions(+), 485 deletions(-) diff --git a/docs/design/appserver/session-files.md b/docs/design/appserver/session-files.md index 38532937c9..968bfb4174 100644 --- a/docs/design/appserver/session-files.md +++ b/docs/design/appserver/session-files.md @@ -410,43 +410,13 @@ like `session_file_owners`, so output stays readable after the source is deleted ### 9.1 Language-neutral (ADR 002 D5) -`sessionFiles`, process scope, no instance key, provided by SessionStore. - -| Method | Mode | Request | Reply | -| --- | --- | --- | --- | -| `put` | async | `{sessionId: string, name: string, content: string}`, where `content` is the bytes in base64 | `{fileId: string, path: string, bytes: u64}` | -| `import` | async | `{sessionId: string, name: string, source: string}`; authorized absolute local source path | `{fileId: string, path: string, bytes: u64}` | -| `read` | async | `{sessionId: string, fileId: string, offset: u64}` | `{data: string, eof: bool}`; base64 of at most 64 KiB, `eof` exactly when empty | -| `register` | async | `{sessionId: string, path: string}` (ADR 013) | `{}`; a missing Session is `not_found` | -| `owns` | async | `{sessionId: string, path: string}` | `{owned: bool}` | -| `owned_paths` | async | `{sessionId: string}` | `{paths: string[]}`, a Session file's directory and each output path | - -`sessionFiles` is a data face: its catalog entry is shared and SessionStore publishes -the same `SessionFiles` binding at its Rust type key and `host_key("sessionFiles")`. -Native calls invoke the owner directly; wire calls decode and invoke the same operations. - -`import` applies the same Session, name, 16 MiB, pending/owned transaction, -permissions and cancellation rules as `put`. FileStorage pins the source while -copying with a 64 KiB buffer; source growth or truncation fails before publication. -The caller authorizes source-path access. `read` resolves only immutable files -owned by the supplied Session, returning `not_found` for a foreign file ID. -Offsets at or beyond EOF return an empty chunk. Dropping a wire call cancels it. - -- `path` is absolute on the Session's resource node, the way `read` resolves it for the Session. - `bytes` is the stored length. -- `register`, `owns` and `owned_paths` are ADR 013's ownership interface. `register` resolves the - path and records it before the caller hands it to the model; `owns` answers from both ownership - tables, and ADR 014 reads it as the session-owned fact for writes. -- Cancellation is a protocol action: the caller drops the call or sends the bridge's cancel - request. It takes effect up to txn 2. After that the file is committed and the reply stands. -- Errors are data, `{code, message}` (§10). -- SessionStore offers no operation that changes, renames or removes one file. Sharing and - release happen only inside S5c's fork and delete transactions, which are SessionStore's own - Rust steps, not service methods. +Superseded by [the SessionFiles contract](../plugins/SessionFiles.md). The operations, the +offset paging, the import reply, the output-path registration and the file removal are defined +there; this document keeps the storage layout, the flows and the error codes above. ### 9.2 How Attachments uses it -Attachments ([A.2](../plugins/Attachments.md#a2-attachmentput)) declares `S:SessionIdentity` and +Attachments ([A.2](../plugins/Attachments.md#a2-attachmentput)) declares its Session identity and the process service `sessionFiles` in its `Deps`: an enclosing-scope dependency on a core part (D3). A SessionStore reload reloads Attachments, which its rule check already accepts. For `attachment.put` it calls `put(sessionId = its own Session, name, content = the text's UTF-8 diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index 540bd28dd9..d1174e48ba 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -1,6 +1,6 @@ # SessionStore title metadata -The [target repository binding](../contracts/resource-owner-operations.md) moves SessionTitle and rename callers to `store.readMetadata` and `store.setTitle`. Remove the `sessionMetadata` catalog entry when switching its consumers. References to that binding below describe the pre-migration implementation. +The [SessionStore contract](../plugins/SessionStore.md) supersedes the title interface: `store.title` reads the title with its source and revision, and `store.setTitle(id, change)` takes the caller's change, serializes the write, commits the returned title and announces it. The revision is the owner's; the interface has no `expectedRevision`. The data, notice, list and sequence paragraphs below describe the stored title and remain in force. Status: Implemented in roadmap item S5b ([#60](https://github.com/arcships/dim/issues/60), [#96](https://github.com/arcships/dim/pull/96)), after C6 ([#49](https://github.com/arcships/dim/issues/49), @@ -13,21 +13,22 @@ fields. Consumer: SessionTitle. ## 1. Summary -SessionStore keeps one title per Session with a per-Session revision. The title changes only through `setTitle`, a -revision-checked write. After each committed change SessionStore announces the new title on the Session's broadcast +SessionStore keeps one title per Session with a per-Session revision. The title changes only through `setTitle`, whose +change decides the next title under the owner's serialization. After each committed change SessionStore announces the new title on the Session's broadcast channel ([C6](session-notices.md)), and Rpc shows the title in protocol v3 Session lists. - **Data.** A revision counter (0 means never written) and either no title or a title `{text, source}` with source `auto` or `manual`. Clearing keeps the counter, so a revision never repeats. -- **Write.** `setTitle {sessionId, expectedRevision, title | null}` commits revision `expectedRevision + 1` or fails - `conflict`, `not_found` or `storage`. The call is the handover: SessionStore admits the write when called, unless it - is closing, and settles it itself; dropping the call only loses the reply. +- **Write.** `setTitle {id}` plus a change callback that receives the current `{revision, title}` and returns the next + title or its own refusal. SessionStore serializes the write, commits the returned title as the next revision and + answers it; failures are `rejected`, `not_found` or `storage`. The call is the handover: SessionStore admits the + write when called, unless it is closing, and settles it itself; dropping the call only loses the reply. - **Notice.** After each commit, `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}`, in commit order. - **Lists.** Protocol v3 `session.summaries` entries carry `title`, `titleSource` and `titleRevision`. -- **Binding.** The process service `sessionMetadata` (`read`, `setTitle`), provided by SessionStore, reaches - TypeScript through the existing service catalog, like `sessions` and `settings`. +- **Binding.** The process service `store` (`title`, `setTitle`), provided by SessionStore, reaches TypeScript through + the existing service catalog. - **Lifecycle.** A delete removes the title in S5c's delete transaction; a fork does not copy it (SessionTitle A7); a restart keeps it. Reading or writing a title never loads the Session. - **Format.** Native store v16: one new table, upgraded in place from v15, and from v13 through v15's step. @@ -57,19 +58,19 @@ protocol version. | Part | Scope | Change | | --- | --- | --- | -| SessionStore ([timeline.rs](../../../crates/dim-app-server/src/storage/timeline.rs), [metadata.rs](../../../crates/dim-app-server/src/storage/metadata.rs)) | Process | `metadata` and `set_title`, the title writer, the `sessionMetadata` service; delete and creation rollback remove the title row; the catalog query reads it | +| SessionStore ([timeline.rs](../../../crates/dim-app-server/src/storage/timeline.rs), [metadata.rs](../../../crates/dim-app-server/src/storage/metadata.rs)) | Process | `title` and `set_title`, the title writer and the `store` face; delete and creation rollback remove the title row; the catalog query reads it | | SqliteStorage ([sqlite.rs](../../../crates/dim-app-server/src/storage/sqlite.rs)) | Process | v16 schema and its upgrade step | | Rpc ([protocol.rs](../../../crates/dim-app-server/src/protocol.rs), [connection.rs](../../../crates/dim-app-server/src/connection.rs)) | Process | The v3 list fields | -| Service catalog ([lib.rs](../../../crates/dim-app-server/src/lib.rs)) | Process | `register_shared("sessionMetadata")`, one line, as S2 did for `sessions` | +| Service catalog ([lib.rs](../../../crates/dim-app-server/src/lib.rs)) | Process | the `store` face, registered once for Rust and the wire | | Session broadcast, Rpc notice forwarding | Session, process | Unchanged (C6) | ## 3. Data and revisions | Item | Meaning | | --- | --- | -| `revision` | Per-Session counter of committed `setTitle` writes. 0 means never written. Each committed write sets it to `expectedRevision + 1`: a new title, the same text again, a source change or a clear | +| `revision` | Per-Session counter of committed `setTitle` writes. 0 means never written. Each committed write adds one: a new title, the same text again, a source change or a clear | | `title` | `{text, source}` or none | -| `source` | `auto` (SessionTitle's generation) or `manual` (`session.rename`). SessionStore stores the source it is given and attaches no rule to it. "A manual title always wins" is SessionTitle's rule, enforced through the revision check ([SessionTitle §4](../plugins/SessionTitle.md#4-timing-and-conflicts)) | +| `source` | `auto` (SessionTitle's generation) or `manual` (`session.rename`). SessionStore stores the source it is given and attaches no rule to it. "A manual title always wins" is SessionTitle's rule, decided inside its change ([SessionTitle §4](../plugins/SessionTitle.md#4-timing-and-conflicts)) | - **A clear keeps the counter.** `title: null` leaves the Session's row with no title and the new revision. Were the row deleted, the counter would restart at 0, and a generation that read revision 0 before a rename and a clear @@ -84,29 +85,29 @@ protocol version. ### 4.1 Language-neutral (ADR 002 D5) -`sessionMetadata`, process scope, control node only, no instance key, provided by SessionStore. +The `store` face, process scope, control node only, no instance key, provided by SessionStore. | Method | Mode | Request | Reply value | Errors | | --- | --- | --- | --- | --- | -| `read` | async | `{sessionId}` | `{revision, title: {text, source} \| null}` | `not_found`, `storage` | -| `setTitle` | async | `{sessionId, expectedRevision, title: {text, source: "auto" \| "manual"} \| null}` | `{revision}`: the committed revision | `conflict`, `not_found`, `storage` | +| `title` | async | `{sessionId}` | `{revision, title: {text, source} \| null}` | `not_found`, `storage` | +| `setTitle` | async | `{sessionId}` plus the change callback | `{revision}`: the committed revision | `rejected`, `not_found`, `storage` | - Replies use one envelope, `{ok: true, value}` or `{ok: false, error: {code, message}}`, as `settings` does. - Neither method loads the Session. `read` reads committed state and does not wait for the title writer (§5). -- `title` is required in `setTitle`; `null` clears. A request without `title` is rejected rather than read as a - clear, so a caller's omission never erases a user's title. +- The change returns the next title or `null` to clear; the owner stores what the change returns. A caller's change + decides the manual-title rule and the clear, so an omission never erases a user's title. - A malformed call (unknown method, not exactly one request object, an unknown field, a wrong type or a missing field) is a bridge error, as for `settings`: it is a caller's programming error, not an outcome of the write. | Code | When | State after | | --- | --- | --- | | `not_found` | The store holds no record of the Session: never created, deleted, or rolled back. A stored Session that is closed or not loaded is found | Unchanged | -| `conflict` | `expectedRevision` is not the current revision | Unchanged, no notice. Read again | +| `rejected` | The change refused with its own `code` and `message`; the manual-title rule is the change's | Unchanged, no notice. Act on the change's code | | `storage` | The transaction failed, or the call arrived after SessionStore started closing (§6) | Unchanged, no notice | ### 4.2 Rust -Rust consumers inject `SessionMetadataService`, the typed binding of `sessionMetadata`, and call +Rust consumers inject the `store` owner and call `title`/`set_title`. The pre-migration binding was `SessionMetadataService`, the typed binding of `sessionMetadata`, and call `read` and `set_title`. The binding is the existing dispatcher, published at both its typed key and `host_key("sessionMetadata")`; both routes delegate directly to the same SessionStore owner. The existing `SessionMetadata` reply type is unchanged. @@ -151,7 +152,7 @@ This settles the boundary that SessionTitle §0 left to S5b. | Before the call | The caller's own work. Cancelling it before the call writes nothing | | The call | The handover is SessionStore receiving the call: before it returns, `setTitle` admits the write and starts it as SessionStore's own task, or, once SessionStore is closing, fails `storage` without writing. In Rust `set_title` is a plain function that does this and returns a future of the reply. That future only awaits the task, so dropping it detaches the reply, never the write. The named service calls it inside `invoke`, so a JavaScript call is handed over once the host receives it | | After the call | SessionStore settles the write itself: it commits and announces, or fails and writes nothing. Dropping the call, unloading the calling row or losing the reply neither cancels nor undoes it. `setTitle` has no cancel action | -| Lost reply | The caller reads with `read`. It does not repeat the write blindly: a repeat at the old revision fails `conflict`, and one at the new revision would be a second change ([SessionTitle Appendix C](../plugins/SessionTitle.md#appendix-c-errors-and-recovery)) | +| Lost reply | The caller reads with `title`. It does not repeat the write blindly: a second change would commit another revision ([SessionTitle Appendix C](../plugins/SessionTitle.md#appendix-c-errors-and-recovery)) | | SessionStore unload | Its disposer first stops admission: from then on a call fails `storage` at once and writes nothing. It then waits until every admitted write, the one in its turn and those waiting for theirs, has committed and announced or failed. Only then does it close Session files and the Timeline writer, and SqliteStorage, which unloads after SessionStore, closes the connection. The notices follow C6 delivery: once the Session is no longer loaded, nobody listens and they are dropped. Nothing is retried after a reload | Rejected: a cancel action that works until the transaction starts. It would only move the uncertainty, since a caller diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index ce4052095c..721560de84 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -27,93 +27,9 @@ The OS path, pinned reader and input reader above use a path value, an existing and a callback respectively. Existing local media submission/import, legacy node paths, result settlement and result paging keep the [Modality contract](../plugins/Modality.md). -## Persistent Agents → sqliteStorage +## Persistent Agents and native storage -| Caller in Agents | Repository API; IDs and records are data | -| --- | --- | -| Load the directory and Session ownership | agents({}) → AgentRecord[]; owners({}) → SessionOwner[]. Keep ordered results, invalid-profile rows, ownership errors and validation of the unique default. | -| Install/forget a persisted Agent | save({id,profile,default,owner?}) and delete({id}) → void. | -| Look up delegation and decide if removal is permitted | members({}) → ordered Session/leader pairs; ledMembers({leader}), ownedAgents({owner}), memberSessions({agent}) → ordered IDs; agentOwner({agent}) → owning Session ID or null. | -| Startup repair | unfinishedOwned({}) → {incomplete,orphaned}. Preserve the existing single query and the two distinct cleanup paths. | - -## Native storage - -SessionStore, persistent Agents, Provider and native Settings call the same process face, `sqliteStorage`. -The SQLite plugin owns reads, transactions and writer shutdown. Each consumer owns its -own unload. Session rows use `store`; volatile Agents and file-profile Settings use their existing backends. - -### SessionStore → sqliteStorage - -SessionStore publishes `store`, `sessionFiles` and the Session-scoped `timelineStore`. -Its native backend calls the existing process face `sqliteStorage` with data. SQLite -owns SQL, read connections, database transactions, writer shutdown and the database lock. -SessionStore owns Session admission, the ownership lock, file I/O, change notices and -draining its admitted work before unloading. - -| Caller → owner | API | Transaction owner and boundary | -| --- | --- | --- | -| Agents, Session catalog, grants and worktree clients → store → sqliteStorage | Reuse the store request/reply shapes for `createOwnedSession, fork, owner, creationRecord, hasRecords, sessionConfig, sessionConfigText, catalog, addGrant, removeGrant, grants, setSessionLanguage, associateWorktree, worktreeDirectories, worktreeUsages, sessionsUnderWorkspace, removeWorktreeDirectory`. | SQLite creates the Session, main branch, ownership and optional worktree association in one transaction. Fork uses bounded copy transactions on its own connection; only the final transaction inserts the Session row and makes the fork visible. Association commits the directory and Session link together. | -| Session deletion and worktree removal → store | `store.delete` uses `sqliteStorage.hasRecords, removableOutputDirectories, touchWorktreeDirectories, rollbackSession`. `store.removeWorktree` uses the existing association/workspace checks and directory deletion; `store.removeUnregisteredDirectory` uses the existing directory-record and workspace checks and the caller's deletion. | SessionStore holds its ownership lock across the checks and the registration of the resolved path in an in-memory set, then releases it for the caller's deletion, including a recursive `--force` deletion with no time limit. Until the same removal task clears the registration, Session creation, fork, worktree association, directory-record deletion or another removal at, under or above that path are refused instead of waiting for it; dropping the caller stops neither the deletion nor the registration. SQLite owns each database step. File deletion and Git removal run outside SQL transactions and outside the ownership lock. | -| SessionTitle and Session rename → store → sqliteStorage | `readMetadata(sessionId)`, `setTitle(existing title request)`; existing metadata replies. FileAccess → `store.associateWorktree` with the existing association record. | SQLite checks the title revision and commits the write. SessionStore serializes title writes and publishes the committed notice before admitting the next one. | -| Timeline clients → timelineStore; SessionStore → sqliteStorage | Bind existing `createSession, rollbackSession, releaseSession, sessionConfig, branches, head, batchEnd, batchEndAt, readPage, readSegments, query, trace, saveSnapshot, latestSnapshot` requests at the native boundary. `commitTimelineRound({batches: Append[]}) → {sessions: [{sessionId, result}]}` accepts ordered batches grouped by Session. | SessionStore admits appends synchronously, groups the existing writer round, and serves commit subscriptions and release/drain. SQLite owns encoding, the grouped transaction, per-Session fallback on failure and writer memo settlement. One accepted round produces the existing ordered batch outcomes after commit. Release or unload drops generation-local reader/writer state after drain. | -| Session file put/import and read → sessionFiles → sqliteStorage | `reserveFile(sessionId,fileId,generation)`, `commitFile(sessionId,fileId,generation)`, `abandonFile(fileId,generation)`; ownership and path reads via `ownsFile, ownsOutput, ownedPaths`; `registerOutput(sessionId,path)`. | SessionStore reserves, writes or imports bytes through the file owner, then finalizes. SQLite verifies the Session and writer generation, clears the reservation and inserts ownership atomically. Bytes, path validation and fileId transfer stay with the file owner. | -| Session file sweep → sqliteStorage | `releaseStaleFileWriters(generation), unownedFiles(), deleteIfUnowned(fileId), recordedFiles(names)`. | SessionStore removes files outside SQLite. SQLite rechecks ownership when deleting the row. Failed cleanup remains retryable. | -| StorageMethods → sqliteStorage; native Transport → SQLite readiness | `storage.report` calls `sqliteStorage.storageReport({})`. Transport gates endpoint binding on the storage face. | SQLite owns the report and holds the database lock before readiness. Transport performs no storage read. | - -Each batch reuses the timelineStore append fields `{sessionId,branchId,batchId,events: StoredEvent[]}`. -Return one outcome per distinct input Session. The result uses the existing completion -result type, `Result<(), CommitFailure {code,message}>`. SQLite preserves batch order within each Session, including when retrying -Sessions separately. SessionStore keeps the publication callbacks locally and settles each -batch exactly once with its Session's result, original key, batchId and final sequence. -An admitted round is drained on shutdown. Losing the reply does not authorize replay of the write. - -### Settings → sqliteStorage - -| Operation | Contract | -| --- | --- | -| readUser({source}) | Return null or {version,document}. The document is the stored text. Settings decodes it using the registered format. | -| importUserIfAbsent({source,document,importedRevision}) | In one transaction insert version 1 and provenance if absent, read the winning row and return it. Settings reads and validates the legacy file only after a miss. | -| replaceUser({source,expectedVersion,decision}) | Check the expected version first. For an accepted document, write it, increment the version and return the committed version. For a rejected protected-field change, return the existing rejection without writing. Missing row, conflict, overflow and storage failure keep their existing mappings. | - -Settings decodes and validates the document. The writer checks the expected version before -applying the decision and enqueues the change notice in commit order on a successful replace. -First import emits no notice. File and project profiles retain their lease and notification paths. - -### Provider → sqliteStorage - -| Operation family | Current call sites and proposed inputs/results | -| --- | --- | -| readSelection(scope); writeSelection(scope,expectedVersion,selection) | selection/select. Return the stored selection and version; the write checks the scope version and commits the selected model atomically. | -| readPreferences(providerId,modelId) | saved_preferences. Read the one model preference field and keep the existing absent-value behavior in Provider. | -| readRecord({providerId,projection}) | catalog, catalog_for, catalog_target, resolve_connection, probe, discovery and edit preparation. Select header/version, one target model, managed catalog or full editable record as required. Return missing or the matching persisted projection. A projection containing an inline credential returns its stored value. | -| findCandidates(criteria); listProviders(filter); queryModels(page); managementPage(page) | Candidate IDs/ordered models, provider list, filtered model pages and management windows use their existing indexed selectors, limits, ordering and row-error behavior. Pass bundle identity, required catalog inputs and account facts as data. Keep transaction-local adoption and page selection together wherever the existing query does both. | -| activateSource(revision,baseFacts); adoptProvider(id,revision,baseFacts) | Existing source activation and per-provider adoption transactions. Supply only the bundle facts required by the existing operation. | -| commitEdit({providerId,edit}) | Closed edit variants: create, delete, connection/header patch, model create/edit/reset/delete, preferences, single/bulk enablement and discovery refresh. Preserve each existing transaction's touched columns, indexes, write precondition and projection. Create checks absence; versioned edits check the expected version. Refresh and connection changes that compare the prior record keep that exact comparison. Return the committed version and requested existing projection. | -| importLegacy(batch) | The existing legacy import commits its related records together and returns the existing item results. Cancellation and rollback keep the original transaction boundary. | - -Provider validates edits and runs probe/discovery HTTP requests outside SQLite. A conditional -commit returns the original conflict on a stale snapshot. - -**Record reads.** `readRecord({providerId,projection}) → PersistedProviderRecord | null`. -Use the existing persisted managed/static variants and the five SQLite model projections: -`header`, `all`, `mutable`, `one{modelId}`, `selected{modelIds}`. Header and target reads -retain their original query bounds. A version-only read uses the existing header version lookup. - -**Conditional edits.** `commitEdit({providerId,edit})` selects one transaction by the edit tag. -Each variant carries its own precondition; callers cannot choose a weaker one. - -| Edit | Input and precondition | Reply to Provider | -| --- | --- | --- | -| create / delete | Admitted create record and absence / expected version. Built-in deletion disables the record. | Created record / void | -| patchHeader | Expected version, existing ProviderPatch header fields, UpdateReplyKind (full or summary) | Committed projection for the requested reply | -| replaceConnection / refreshStatic | Prior complete static record and admitted replacement. Compare the exact prior record in the transaction. | Committed record | -| refreshManaged | Previous optional version, discovered account catalog and current account facts. Preserve account identity and optional-version checks. | Committed managed record | -| createModel / deleteModel / editModel | Expected version and ModelEntry / modelId / {modelId, edit: ModelEdit or null}. Null resets the edit. | Committed catalog projection | -| preferences / enableModel / enableModels | Expected version and {modelId, patch: PreferencesPatch} / {modelId, enabled} / {modelIds}. Retain bundled and account facts used by the existing mutation. | Management projection / version / catalog projection | - -Discovery and credential admission run in Provider before the conditional write. SQLite executes -the existing mutation, including its index updates, in one transaction. Provider constructs the -existing business reply. `importLegacy` remains its existing separate bulk transaction. +Superseded by the owner contracts. The Agent records belong to [Agents and Collaboration](https://github.com/arcships/dim/pull/2098), the Settings document operations to [Settings](https://github.com/arcships/dim/pull/2094), the Provider record operations to [Provider](https://github.com/arcships/dim/pull/2096), and the Session repository operations to [SessionStore](../plugins/SessionStore.md). The engine's public face is the capacity read and the offline operations ([SqliteStorage](../plugins/SqliteStorage.md)); its transactions are the data owners' crate-private implementation, and no operation of those owners is published under `sqliteStorage`. ### Credential values in replies diff --git a/docs/design/plugins/Attachments.md b/docs/design/plugins/Attachments.md index a1aace89fd..a79c2fcca0 100644 --- a/docs/design/plugins/Attachments.md +++ b/docs/design/plugins/Attachments.md @@ -9,7 +9,7 @@ The cross-module design is [file transfer](../research/file-transfer.md). | Part | Scope | Consumes | Provides | | --- | --- | --- | --- | -| Attachments | Session | Session identity; [`sessionFiles`](../appserver/session-files.md#9-interface); `sessionMethods` | `attachment.put`, `attachment.import`, `attachment.read` | +| Attachments | Session | Session identity; [`sessionFiles`](SessionFiles.md); `sessionMethods` | `attachment.put`, `attachment.import`, `attachment.read` | The profile installs Attachments where SessionStore and local execution are available. Each method uses its own Session identity. Rpc authorizes and holds the @@ -57,7 +57,7 @@ file scope under [Session files §11](../appserver/session-files.md#11-security) ## 4. Timing and conflicts -`put` and `import` use drain interruption. Cancellation before the owner's commit +The operation shapes are [SessionFiles](SessionFiles.md). `put` and `import` use drain interruption. Cancellation before the owner's commit cleans pending storage; after commit the stored result stands. Losing a client connection does not revoke committed ownership. Retrying an import creates a new file. `read` reports interruption and has no durable mutation. diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md index 898fd98b30..f008a1163b 100644 --- a/docs/design/plugins/ManagedWorktrees.md +++ b/docs/design/plugins/ManagedWorktrees.md @@ -38,11 +38,11 @@ An operation exists only where its row says No. Agents creates a worktree, writes the Session, and settles the worktree when the Session creation fails. ```rust -let created = worktrees.create(Create { source, base, branch }, cancelled.clone()).await?; +let created = worktrees.create(CreateWorktree { source, base, branch }, cancelled.clone()).await?; match store.create(session_request(&created), cancelled.clone()).await { Ok(()) => (), Err(error) => { - worktrees.discard(Discard { task_id: created.task_id }, CancellationToken::new()).await?; + worktrees.discard(DiscardWorktree { task_id: created.task_id }).await?; return Err(error); } } @@ -51,9 +51,9 @@ match store.create(session_request(&created), cancelled.clone()).await { The CLI previews a prune and removes the confirmed ids. ```rust -let preview = worktrees.prune_selection(Prune { older_than_ms: Some(age), keep: None, force }).await?; +let preview = worktrees.prune_selection(PruneSelection { older_than_ms: Some(age), keep: None, force }).await?; for candidate in confirmed(&preview) { - worktrees.remove(Remove { task_id: candidate.task_id, force }).await?; + worktrees.remove(RemoveWorktree { task_id: candidate.task_id, force }).await?; } ``` @@ -69,9 +69,9 @@ for candidate in confirmed(&preview) { | --- | --- | --- | --- | --- | --- | | `create` | Allocate a task id and make a Git worktree and branch for a Session creation | `{source, base?, branch?}` | `{taskId, repository, root, subtree, branch, base}` | Between Git calls and before the branch is created; a cancelled creation removes its empty task directory | `unavailable`, `invalid`, `branch_exists`, `git`, `interrupted` | | `discard` | Settle a created worktree that the Session creation did not adopt | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `in_use`, `git` | -| `list` | Managed worktrees with Git state and Session use | `{}` | `{worktrees}` | While the views are built | `unavailable`, `storage` | -| `pruneSelection` | Candidates a prune would delete and the kept ones with reasons | `{olderThanMs? , keep?, force}` | `{candidates, kept}` | While the selection is built | `invalid`, `unavailable`, `storage` | -| `remove` | Remove one managed worktree, or an unregistered directory, with its record | `{taskId, force}` | `{removed}` | Before the Git removal; after it starts the removal completes or reports `git` | `invalid`, `not_found`, `in_use`, `git`, `storage` | +| `list` | Managed worktrees with Git state and Session use | `{}` | `{worktrees}` | While the views are built | `unavailable`, `closed`, `storage` | +| `pruneSelection` | Candidates a prune would delete and the kept ones with reasons | `{olderThanMs?, keep?, force}` | `{candidates, kept}` | While the selection is built | `invalid`, `unavailable`, `closed`, `storage` | +| `remove` | Remove one managed worktree, or an unregistered directory, with its record | `{taskId, force}` | `{removed}` | Before the Git removal; after it starts the removal completes or reports `git` | `invalid`, `not_found`, `in_use`, `git`, `closed`, `storage` | `create` returns a value; `discard` and `remove` take the task id. No object crosses. The preparation table is the owner's generation state: a reload drops it, and `discard` for a task id the generation did not create answers `unknown_preparation`; the directory is then an unregistered directory that `remove` handles. @@ -108,8 +108,17 @@ A process death between `create` and `store.create` leaves an unregistered direc - A branch is kept when `remove` deletes a worktree: committed content must not disappear with the directory. - `discard` is not cancellable: a cancelled Session creation still has to settle what the owner made. - Unregistered directories are never pruned: the owner has no record to age, so only an explicit `remove` by task id deletes them. +- A branch outlives a creation that was never adopted: a process death between `create` and `store.create`, or a `discard` that ended before the branch deletion, leaves the branch. `remove` on an unregistered directory deletes the directory only; the operator deletes the leftover branch with Git, and `list` names the task id the branch was made for. - Git is the owner's process resource: the owner starts each call, bounds it (10s read, 30s write) and reaps it on cancellation. +## Client-visible changes + +None. `worktree.list`, `worktree.remove` and `worktree.prune` keep their request, reply and error shapes; the redesign changes the plugin surface and the owner name only. + +## Supersedes + +- [Managed worktrees](../worktree-management.md) §3–§5: creation, the directory records and associations, and the list/remove/prune composition under the store's removal operation. + ## Verification Flow tests on the owner: @@ -160,7 +169,7 @@ use rutis::Ctx; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Created { +pub struct CreatedWorktree { pub task_id: String, pub repository: String, pub root: String, @@ -171,37 +180,46 @@ pub struct Created { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Discard { +pub struct DiscardWorktree { pub task_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Remove { +pub struct RemoveWorktree { pub task_id: String, pub force: bool, } -#[derive(Debug, thiserror::Error)] -pub enum WorktreeError { - #[error("{0}")] - Unavailable(String), - #[error("{0}")] - Invalid(String), - #[error("{0}")] - BranchExists(String), - #[error("{0}")] - NotFound(String), - #[error("{0}")] - InUse(String), - #[error("{0}")] - Git(String), - #[error("{0}")] - Interrupted(String), - #[error("{0}")] - UnknownPreparation(String), - #[error("{0}")] - Storage(String), +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CreateWorktree { + pub source: String, + pub base: Option<String>, + pub branch: Option<String>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PruneSelection { + pub older_than_ms: Option<u64>, + pub keep: Option<usize>, + pub force: bool, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RemoveWorktreeReply { + pub removed: bool, +} + +/// The wire error: `{code, message}`, with `code` one of the kinds in the error table. +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +#[error("{code}: {message}")] +pub struct WorktreeError { + pub code: String, + pub message: String, } impl PublicService for ManagedWorktrees {} @@ -211,17 +229,16 @@ impl ManagedWorktrees { pub async fn create( &self, caller: &Ctx, - request: Create, + request: CreateWorktree, cancelled: CancelledFn, - ) -> Result<Created, WorktreeError> { + ) -> Result<CreatedWorktree, WorktreeError> { // ... } pub async fn discard( &self, caller: &Ctx, - request: Discard, - cancelled: CancelledFn, + request: DiscardWorktree, ) -> Result<(), WorktreeError> { // ... } @@ -229,9 +246,9 @@ impl ManagedWorktrees { pub async fn remove( &self, caller: &Ctx, - request: Remove, + request: RemoveWorktree, cancelled: CancelledFn, - ) -> Result<Removed, WorktreeError> { + ) -> Result<RemoveWorktreeReply, WorktreeError> { // ... } } diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..04047b5291 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,10 @@ 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 | | --- | --- | --- | --- | --- | +| [SessionStore](SessionStore.md) (owner contract) | the stored Session, grants, language, titles, worktree records and the Session exclusion behind `store`; the Timeline operations bound as `timelineStore` | — | — | [#2018](https://github.com/arcships/dim/issues/2018) | +| [SessionFiles](SessionFiles.md) (owner contract) | Session file bytes, the write generation and ownership rows behind `sessionFiles` | — | — | [#2018](https://github.com/arcships/dim/issues/2018) | +| [ManagedWorktrees](ManagedWorktrees.md) (owner contract) | the managed root, task ids and Git behind `managedWorktrees` | — | — | [#2018](https://github.com/arcships/dim/issues/2018) | +| [SqliteStorage](SqliteStorage.md) (owner contract) | the database file, lease, format and connections; the capacity read and the offline operations | — | — | [#2018](https://github.com/arcships/dim/issues/2018) | | [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 | @@ -51,6 +55,6 @@ A plugin is split by the owner of its state into parts, each placed in its owner | Scope | Parts | | --- | --- | -| Process parts | Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RuntimeManager, RemoteGateway, Skills (installation), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | +| Process parts | SessionStore, SessionFiles, ManagedWorktrees, SqliteStorage (owner contracts), Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RuntimeManager, RemoteGateway, Skills (installation), PromptSuggestion (the Settings source), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | | Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, Scheduler, Workflow, PromptSources, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | | Branch parts | Goal (with Pursuit), ModelRecovery (proposed), Hooks, Prompt, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md index ed4c115c70..c7882d0626 100644 --- a/docs/design/plugins/SessionFiles.md +++ b/docs/design/plugins/SessionFiles.md @@ -2,13 +2,13 @@ Scope: process. Issue: #2018. -SessionFiles owns the bytes of Session files and the ownership rows that make a path or a file id belong to a Session. This document is the owner's target contract. The current implementation is described in [Session files](../appserver/session-files.md). The engine's row operations this owner uses are private to the storage crate; the Session store uses this owner when a delete releases files. +SessionFiles owns the bytes of Session files and the ownership rows that make a path or a file id belong to a Session. This document is the owner's target contract. The current implementation is described in [Session files](../appserver/session-files.md); the interface there is superseded by this contract. The engine's row operations this owner uses are private to the storage crate; the Session store uses this owner when a delete releases files. ## Use and scope: responsibility split SessionFiles owns: -- **The file namespace.** One immutable file per `fileId` under `<db>.session-files/<fileId>/<name>`, written through FileStorage. +- **The file namespace.** One file per `fileId` under `<db>.session-files/<fileId>/<name>`, written through FileStorage. - **The write generation.** One generation per store generation. A write reserves its name, the bytes land, and the ownership row commits only in the same generation that reserved it. - **The sweep.** Removes files no row owns, rows pending under a dead generation, and directory entries with no row. - **Ownership rows.** Which Session owns a Session file and which Session owns a registered output path. @@ -18,38 +18,40 @@ Callers keep: - **The purpose of the file.** An attachment, an image sent to a model, a tool result, an event payload, a command output path. - **The name** the caller gives a stored file, within the owner's component rule. +- **The output roots.** WorkspaceTools owns `command-output/<session>/…`; HostPlatform owns `.dim/exec/<session>/<branch>/…`. The caller decides which root a path belongs to and passes a resolved absolute path; the owner records it. - **The model's content rules.** Image budgets, request materialization and what reaches the model stay with the model provider. - **The tool result.** What a registration means for the user stays with the tool. -- **The output directory.** WorkspaceTools owns the output path and its policy. | Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| Store produced bytes under a new file id for a Session | No: the reservation, the file write and the ownership commit are one ordered protocol; a caller composing them would drive a half transaction | `put` | +| Store produced bytes under a new file id for a Session; an event body names the path a read tool opens | No: the reservation, the file write and the ownership commit are one ordered protocol, and the path is the owner's layout | `put` | | Import a host file the user or model named as a Session file | No: the source is outside the file namespace and the size limit must stop the copy before it lands | `import` | -| Replace the bytes of an existing Session file under the same id and path | No: the id, the path and the ownership row are the owner's; a replace must keep the read tool's path valid | `write` | -| Read a Session file for a model request or a UI | No: the caller cannot read the owner's directory or the file id's row | `read` | -| Record a command output path as owned by the Session | No: ownership is the owner's row and the path must stay inside the Session's output directory | `register` | +| Replace an existing Session file's bytes under the same id and path; an MCP result file is rewritten | No: the id, the path and the ownership row are the owner's; a replace must keep the read tool's path valid | `write` | +| Read a Session file in bounded pages for a model request, an attachment read or a web download | No: the caller cannot read the owner's directory or the file id's row | `read` | +| Record a command output path as owned by the Session | No: ownership is the owner's row | `register` | | Answer whether a path or file id belongs to the Session | No: the answer composes two ownership tables and the file directory mapping | `owns` | -| Remove a Session file and its ownership row | No: the directory entry and the row are the owner's | `remove` | +| Remove an MCP result file and its ownership row | No: the directory entry and the row are the owner's | `remove` | | List every path the Session owns, for deletion or for a grant | No: the caller has no row access | `ownedPaths` | An operation exists only where its row says No. ## Caller example -WorkspaceTools registers a command output path. +WorkspaceTools registers a command output path it owns the root of. ```rust -files.register(Register { session_id, path }, cancelled).await?; +files.register(Register { session_id, path }).await?; ``` -ImageUnderstanding and the model provider read a file for one request. +Attachments reads one 64 KiB page and stops at the end of the file. ```rust -let stored = files.read(ReadFile { session_id, file_id }, cancelled.clone()).await?; +let page = files.read(ReadFile { session_id, file_id, offset }, cancelled.clone()).await?; +// `page.data` is the next page in base64; `page.eof` is true exactly when the page is empty. +if page.eof { /* the end of the file */ } ``` -Attachments import a host file the user chose. +Attachments imports a host file the user chose; the reply carries the path the tool result names. ```rust let stored = files.import(Import { session_id, name, source }, cancelled).await?; @@ -59,30 +61,30 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? ### Dependencies -`fsHost` for the owner's directory, file creation, atomic replacement, import, listing and removal; the operations used are the ones in [FileStorage's contract](FileStorage.md). The engine's file-ownership rows are private to the storage crate and are not a service. The owner does not depend on `store`: the store depends on this owner when a delete releases files. +`fsHost` for the owner's directory, file creation, atomic replacement, import, listing and removal; the operations used are the ones in [FileStorage's contract](https://github.com/arcships/dim/pull/2080). The engine's file-ownership rows are private to the storage crate and are not a service. The owner does not depend on `store`: the store depends on this owner when a delete releases files. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, bytes}` | `{fileId, path, size}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | -| `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, size}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | -| `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, bytes}` | `{fileId, path, size}` | Before the replacement; the old bytes stay | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | -| `read` | Read one Session file whole, within the owner's limit | `{sessionId, fileId}` | `{bytes}` | While the file is read; nothing changes | `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | -| `remove` | Remove one Session file and its ownership row; a file the Session does not own answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal | `not_found`, `node_unavailable`, `storage` | -| `register` | Record an output path as owned by the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `storage` | -| `owns` | Whether a path or file id belongs to the Session | `{sessionId, path}` | `{owned}` | While the path is resolved | `node_unavailable`, `cancelled`, `storage` | -| `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `node_unavailable`, `storage` | +| `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, content}`, `content` is base64 | `{fileId, path, bytes}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, path, bytes}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, content}`, `content` is base64 | `{fileId, path, bytes}` | Before the replacement; the old bytes stay | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `read` | One page of a Session file, at most 64 KiB | `{sessionId, fileId, offset}` | `{data, eof}`, `data` is base64 and `eof` is true exactly when it is empty | While the page is read; nothing changes | `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `register` | Record a caller-owned output path for the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `storage` | +| `owns` | Whether a path or file id belongs to the Session | `{sessionId, path}` | `{owned}` | While the path is resolved | `node_unavailable`, `cancelled`, `closed`, `storage` | +| `remove` | Remove one Session file and its ownership row; an absent or foreign file answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal | `storage` | +| `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `storage` | -`bytes` is the file content as data; the owner's limit is 16 MiB. `read` answers the whole file within that limit: the limit is the owner's, so callers do not page. A `fileId` outside the Session, or a name that is not one component, is `invalid`. +`path` is absolute on the Session's resource node; `bytes` is the stored length. `offset` at or beyond the end answers an empty `data` with `eof`. A `fileId` outside the Session, or a name that is not one component, is `not_found` for reads and writes and `invalid` for a name `put` or `import` receives. ### Errors | Kind | What the caller does next | | --- | --- | -| `invalid` | Fix the input: a name that is not one component, a relative or non-file import source, a path outside the Session's output directory | +| `invalid` | Fix the input: a name that is not one component, a relative or non-UTF-8 path, an import source that is not a regular file | | `too_large` | Treat the file as not storable; store a smaller representation or refuse the attachment | -| `not_found` | The Session has no such file, or the Session no longer exists; the caller refuses the request | +| `not_found` | The Session has no such file, the file belongs to another Session, or the Session no longer exists; the caller refuses the request | | `node_unavailable` | The Session's resource node cannot be reached; retry later or report the node as unavailable | | `cancelled` | Nothing was committed; the caller stops | | `closed` | This generation is unloading; call the replacement generation | @@ -95,10 +97,10 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `put` | Reserve the file under the generation, write the bytes through FileStorage, commit the ownership row while the generation and the Session still exist | The reservation and the written bytes are abandoned; the sweep removes them; no owned row | The write completes under the owner's task, or the reservation expires with the generation; the sweep removes unowned bytes | Admission stops; admitted writes finish; a new generation sweeps the old one's pending rows | FileSystem by FileStorage; rows and sweep by SessionFiles | | `import` | Open the source, check size, copy through FileStorage into a temporary file, commit ownership | The temporary file is removed; no owned row | The copy completes or is abandoned; the sweep removes what no row owns | As `put` | Source and temporary file by FileStorage; rows by SessionFiles | | `write` | Resolve the file id, write the new bytes through FileStorage under the same path, keep the row | Before the replacement: the old bytes stay | The write completes or is abandoned | As `put` | File and path by FileStorage; row by SessionFiles | -| `read` | Resolve the file id under the generation's directory, read the bytes within the limit | The read stops; nothing changes | The read stops | Pending reads end `closed` | FileStorage | -| `remove` | Resolve the file id, remove the directory entry through FileStorage, delete the row | None | The call ends | Rows stay for the next generation | File and row by SessionFiles | -| `register` | Check the Session and the output directory, insert the ownership row | None | The row stays; a later Session delete removes it | Rows stay for the next generation | SessionFiles | -| `owns` | Resolve the path, check the output row, else map the file directory and the file id row | The resolution stops | Nothing to release | Pending calls end `closed` | SessionFiles | +| `read` | Resolve the file id, read one page at the offset; an offset at or past the end is an empty page | The page stops; nothing changes | The read stops | Pending reads end `closed` | FileStorage | +| `remove` | Resolve the file id; an absent or foreign id answers success; remove the directory entry through FileStorage, delete the row | None | The call ends | Rows stay for the next generation | File and row by SessionFiles | +| `register` | Check the Session, record the path the caller resolved | None | The row stays; a later Session delete removes it | Rows stay for the next generation | SessionFiles | +| `owns` | Resolve the path against the owner's directory, check the output row, else the file id row | The resolution stops | Nothing to release | Pending calls end `closed` | SessionFiles | | `ownedPaths` | Read both ownership rows, map file ids to the directory | None | Nothing to release | Rows stay | SessionFiles | A Session delete releases this owner's rows before the sweep runs; the sweep deletes bytes no row owns. Files another Session owns are never removed by one Session's delete. @@ -107,19 +109,31 @@ A Session delete releases this owner's rows before the sweep runs; the sweep del - The file directory is below the database directory: a Session's files are removed with the store that owns their rows, and the delete's last-owner guard is scoped to one database (ADR 013). - The generation is the store's generation: a stale writer cannot commit into a Session that a newer store generation created. -- `read` answers the whole file within the owner's 16 MiB limit instead of paging: every caller needs the whole file, and a page protocol would push the read id's lifetime to callers. +- `read` pages by offset instead of opening a read id: the callers (Attachments' `attachment.read`, the web download, image materialization) already page by offset, and a read id would put its release on every error path. +- `register` records a path the caller resolved and owns the root of: WorkspaceTools and HostPlatform have two different output roots, and the owner cannot decide which root a path belongs to without depending on both. +- `write` and `remove` serve MCP result files ([#2022](https://github.com/arcships/dim/pull/2101)): a result file is rewritten as the child reports progress and removed when the child's result is discarded. - The ownership rows live in the engine's database but belong to this owner: the engine executes the transaction, SessionFiles decides when it commits. +## Client-visible changes + +None. `read` keeps the offset page and the 64 KiB bound; `put` and `import` keep `{fileId, path, bytes}`; the error codes and the `attachment.read` reply are unchanged. `write` and `remove` are new plugin operations, not client protocol methods. + +## Supersedes + +- [Session files §9.1](../appserver/session-files.md#91-language-neutral-adr-002-d5): the operation table, the paging note, the register root rule and the paragraph that says SessionStore offers no operation that changes or removes one file. +- [Service faces §3.2](../service-faces.md): the `sessionFiles` row. +- [Resource faces §4.6](../resource-faces.md): the Session files paragraph. + ## Verification Flow tests on the owner: -- `put` reserves, writes and commits; a cancelled put leaves no owned row and the sweep removes the bytes; a second put with the same name gets a new file id. -- `import` refuses a directory, a non-regular file and a source over the limit without landing anything. +- `put` reserves, writes and commits; a cancelled put leaves no owned row and the sweep removes the bytes; a second put with the same name gets a new file id; the reply names the path and the stored length. +- `import` refuses a directory, a non-regular file and a source over the limit without landing anything; the reply names the path. +- `read` pages by offset; the last page has `eof`; an offset past the end is an empty page; a foreign file id answers `not_found`. - `write` keeps the file id and path and replaces the bytes; an unknown id answers `not_found`; the old bytes survive a cancelled write. -- `remove` answers success for a file the Session does not own, deletes the file and the row for an owned one, and never removes another Session's file. -- `read` answers `not_found` for another Session's file id and for an unknown id; a file over the limit is never stored. -- `register` refuses a path outside the output directory; `owns` answers true for a registered output and for a Session file path, and false for another Session's file. +- `remove` answers success for an absent or foreign file, deletes the file and the row for an owned one. +- `register` records a path without judging its root; a missing Session answers `not_found`; `owns` answers true for a registered output and for a Session file path, and false for another Session's file. - A Session delete releases the rows; the sweep removes the bytes; a file still owned by another Session survives. - A generation close stops admission; a new generation sweeps pending rows and directory entries without rows. @@ -139,7 +153,7 @@ Flow tests on the owner: | §4 rule 7 | Callers use these operations; no caller reads a generation or a directory entry. | | §4 rule 8 | No infrastructure change; requirements below. | | §4 rule 9 | No Timeline fact. | -| §7.2 ids and values | File ids, names and bytes cross as data; a `fileId` is the resource id. | +| §7.2 ids and values | File ids, paths and bytes cross as data; a `fileId` is the resource id; pages are offset reads. | | §7.2 one public face | The service is marked on the file owner's type under the existing `sessionFiles` name; the `SessionFiles` wrapper type and the `SessionFilesService` trait do not exist beside it. | | §7.2 caller mechanisms | The reservation, the generation and the sweep stay inside the owner; callers handle the business errors only. | | ADR 002 D1 | Process scope: the namespace and the rows outlive Sessions. | @@ -155,43 +169,127 @@ Flow tests on the owner: ## Binding appendix -The service is marked on the file owner's type; the wire name stays `sessionFiles`. The `SessionFiles` wrapper and `SessionFilesService` no longer exist. `CancelledFn` is the binding's cancellation argument. +The service is marked on the file owner's type; the wire name stays `sessionFiles`. The `SessionFiles` wrapper and `SessionFilesService` no longer exist. `CancelledFn` is the binding's cancellation argument; operations that do not wait take none. ```rust use dim_agent_capabilities::host::CancelledFn; use dim_agent_runtime::PublicService; use rutis::Ctx; +use std::sync::Arc; + +/// A caller's own refusal or failure; the wire carries its `code` and `message` unchanged. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, thiserror::Error)] +#[error("{code}: {message}")] +pub struct FileRejected { + pub code: String, + pub message: String, +} + +impl From<rutis::host::CallError> for FileRejected { + fn from(error: rutis::host::CallError) -> Self { + Self { + code: error.code().unwrap_or_else(|| "rejected".into()), + message: error.message().to_owned(), + } + } +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Put { + pub session_id: String, + pub name: String, + /// base64 + pub content: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Import { + pub session_id: String, + pub name: String, + pub source: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WriteFile { + pub session_id: String, + pub file_id: String, + /// base64 + pub content: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ReadFile { + pub session_id: String, + pub file_id: String, + pub offset: u64, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RemoveFile { + pub session_id: String, + pub file_id: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Register { + pub session_id: String, + pub path: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Owns { + pub session_id: String, + pub path: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct OfSession { + pub session_id: String, +} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct StoredFile { pub file_id: String, pub path: String, - pub size: u64, + pub bytes: u64, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Page { + /// base64, at most 64 KiB + pub data: String, + pub eof: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FileBytes { - pub bytes: String, // base64 text +pub struct Owned { + pub owned: bool, } -#[derive(Debug, thiserror::Error)] -pub enum SessionFileError { - #[error("{0}")] - Invalid(String), - #[error("{0} is over the Session file limit")] - TooLarge(String), - #[error("no such file: {0}")] - NotFound(String), - #[error("the resource node is unavailable: {0}")] - NodeUnavailable(String), - #[error("the call was cancelled")] - Cancelled, - #[error("the file service is unloading")] - Closed, - #[error("{0}")] - Storage(String), +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Paths { + pub paths: Vec<String>, +} + +/// The wire error: `{code, message}`. +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +#[error("{code}: {message}")] +pub struct SessionFileError { + pub code: String, + pub message: String, } impl PublicService for SessionFiles {} @@ -230,16 +328,7 @@ impl SessionFiles { caller: &Ctx, request: ReadFile, cancelled: CancelledFn, - ) -> Result<FileBytes, SessionFileError> { - // ... - } - - pub async fn remove( - &self, - caller: &Ctx, - request: RemoveFile, - cancelled: CancelledFn, - ) -> Result<(), SessionFileError> { + ) -> Result<Page, SessionFileError> { // ... } @@ -247,7 +336,6 @@ impl SessionFiles { &self, caller: &Ctx, request: Register, - cancelled: CancelledFn, ) -> Result<(), SessionFileError> { // ... } @@ -261,11 +349,18 @@ impl SessionFiles { // ... } + pub async fn remove( + &self, + caller: &Ctx, + request: RemoveFile, + ) -> Result<(), SessionFileError> { + // ... + } + pub async fn owned_paths( &self, caller: &Ctx, request: OfSession, - cancelled: CancelledFn, ) -> Result<Paths, SessionFileError> { // ... } diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index bdd674a4be..0b00ff768b 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -54,7 +54,7 @@ Agents creates a Session; admission, protocol checks and the worktree creation h ```rust // `prepared` is the value ManagedWorktrees.create returned. -store.create(Create { +store.create(CreateSession { id, config, agent_id, protocol_version, leader: None, origin, worktree: prepared, }, cancelled).await?; ``` @@ -67,8 +67,8 @@ let text: TextFn = Arc::new(move |source: String| { let next = strip_initial_title(&source); // lifecycle owner's decision Box::pin(async move { Ok(next) }) }); -store.fork(Fork { source, id: fork, at }, text, cancelled).await?; -let removed = store.delete(Delete { id }, cancelled).await?; +store.fork(ForkSession { source, id: fork, at }, text, cancelled).await?; +let removed = store.delete(DeleteSession { id }, cancelled).await?; ``` SessionTitle decides the next title from the current one; the owner serializes the decision and announces the committed revision. @@ -96,7 +96,7 @@ store.removeWorktree(Directory { repository, root }, remove, cancelled.clone()). ### Dependencies -The engine's crate-private operations for every row read and write and for the Timeline batches; `sqliteStorage` is not a service face. The file owner `sessionFiles` for the Session file steps a delete releases. Neither dependency crosses back into SessionStore. The assembly provides both; deployment chooses the instance. +The engine's crate-private transaction operations for every row read and write and for the Timeline batches; the engine's public face is the capacity read. The file owner `sessionFiles` for the Session file steps a delete releases. Neither dependency crosses back into SessionStore. The assembly provides both; deployment chooses the instance. ### Operations @@ -104,26 +104,26 @@ Every operation takes one request object and answers one reply object. Writes ar | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `create` | Write one admitted Session and its optional worktree association | `{id, config, agentId, protocolVersion, leader?, origin, worktree?}` | `{}` | Before the transaction starts; a dropped future does not undo a commit | `invalid`, `workspace_missing`, `storage` | -| `delete` | Remove a closed Session's output, visible rows and Timeline rows | `{id}` | `{hadRows}` | Before the first step; after the first commit the steps run to their end | `storage` | -| `fork` | Copy a source's rows at a cut, with the target text decided from the source text under the fork's exclusion | `{source, id, at}` + `text` | `{}` | Before the first transaction; the callback's future is dropped | `invalid`, `rejected`, `storage` | -| `creationRecord` | One Session's origin and leader link | `{id}` | `{origin, leader?}` | None | `not_found`, `storage` | -| `owner` | The Agent that owns a stored Session | `{id}` | `{agentId?}` | None | `storage` | -| `hasRecords` | Whether an id has any stored row | `{id}` | `{exists}` | None | `storage` | -| `sessionConfig` | A stored Session's decoded configuration | `{id}` | `{config?}` | None | `not_found`, `storage` | -| `catalog` | One stored Session page | `{request, agent?, version, hosts, closed}` | the stored page | While the page is read | `invalid`, `cancelled`, `storage` | -| `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not) | `{scope, query, page?}` | the query result | While the page is read | `storage`, `cancelled` | -| `grants` | The Session's grant set | `{id}` | `{grants}` | None | `storage` | -| `addGrant` | Add one grant, never downgrading a write grant | `{id, path, kind, mode}` | `{}` | None | `not_found`, `invalid`, `storage` | -| `removeGrant` | Remove one grant; an absent grant counts as removed | `{id, path}` | `{}` | None | `storage` | -| `setLanguage` | Write the reply language into the stored configuration | `{id, language?}` | `{}` | None | `not_found`, `invalid`, `storage` | -| `title` | The title, its source and its committed revision | `{id}` | `{revision, title?: {text, source}}` | None | `not_found`, `storage` | -| `setTitle` | Commit the title the caller's change returns and announce it; the owner serializes writes | `{id}` + `change` | `{revision}` | The reply may be dropped; the admitted write is not cancelled | `not_found`, `rejected`, `storage` | -| `associateWorktree` | Record a verified directory and the Session's subtree in one commit | `{id, repository, root, subtree}` | `{}` | None | `not_found`, `invalid`, `storage` | -| `worktrees` | Recorded directories, with their last use when known | `{}` | `{directories}` | None | `storage` | -| `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `storage` | -| `sessionsUnder` | Stored Sessions whose workspace is a root or lies under it | `{root}` | `{sessionIds}` | None | `invalid`, `storage` | -| `removeWorktree` | Remove one recorded directory under the Session exclusion, with the caller's own removal step | `{repository, root}` + `remove` | `{removed}` | The caller's step ends; the record stays | `invalid`, `in_use`, `rejected`, `storage` | +| `create` | Write one admitted Session and its optional worktree association | `{id, config, agentId, protocolVersion, leader?, origin, worktree?}` | `{}` | Before the transaction starts; a dropped future does not undo a commit | `invalid`, `workspace_missing`, `closed`, `storage` | +| `delete` | Remove a closed Session's output, visible rows and Timeline rows | `{id}` | `{hadRows}` | Before the first step; after the first commit the steps run to their end | `invalid`, `closed`, `storage` | +| `fork` | Copy a source's rows at a cut, with the target text decided from the source text under the fork's exclusion | `{source, id, at}` + `text` | `{}` | Before the first transaction; the callback's future is dropped | `invalid`, `rejected`, `closed`, `storage` | +| `creationRecord` | One Session's origin and leader link | `{id}` | `{origin, leader?}` | None | `not_found`, `closed`, `storage` | +| `owner` | The Agent that owns a stored Session | `{id}` | `{agentId?}` | None | `closed`, `storage` | +| `hasRecords` | Whether an id has any stored row | `{id}` | `{exists}` | None | `closed`, `storage` | +| `sessionConfig` | A stored Session's decoded configuration | `{id}` | `{config?}` | None | `not_found`, `closed`, `storage` | +| `catalog` | One stored Session page | `{request, agent?, version, hosts, closed}` | the stored page | While the page is read | `invalid`, `cancelled`, `closed`, `storage` | +| `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not) | `{scope, query, page?}` | the query result | While the page is read | `storage`, `cancelled`, `closed` | +| `grants` | The Session's grant set | `{id}` | `{grants}` | None | `closed`, `storage` | +| `addGrant` | Add one grant, never downgrading a write grant | `{id, path, kind, mode}` | `{}` | None | `not_found`, `invalid`, `closed`, `storage` | +| `removeGrant` | Remove one grant; an absent grant counts as removed | `{id, path}` | `{}` | None | `closed`, `storage` | +| `setLanguage` | Write the reply language into the stored configuration | `{id, language?}` | `{}` | None | `not_found`, `invalid`, `closed`, `storage` | +| `title` | The title, its source and its committed revision | `{id}` | `{revision, title?: {text, source}}` | None | `not_found`, `closed`, `storage` | +| `setTitle` | Commit the title the caller's change returns and announce it; the owner serializes writes | `{id}` + `change` | `{revision}` | The reply may be dropped; the admitted write is not cancelled | `not_found`, `rejected`, `closed`, `storage` | +| `associateWorktree` | Record a verified directory and the Session's subtree in one commit | `{id, repository, root, subtree}` | `{}` | None | `not_found`, `invalid`, `closed`, `storage` | +| `worktrees` | Recorded directories, with their last use when known | `{}` | `{directories}` | None | `closed`, `storage` | +| `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `closed`, `storage` | +| `sessionsUnder` | Stored Sessions whose workspace is a root or lies under it | `{root}` | `{sessionIds}` | None | `invalid`, `closed`, `storage` | +| `removeWorktree` | Remove one recorded directory under the Session exclusion, with the caller's own removal step | `{repository, root}` + `remove` | `{removed}` | The caller's step ends; the record stays | `invalid`, `in_use`, `rejected`, `closed`, `storage` | `worktree` in `create` and `associateWorktree` is `{repository, root, subtree}`: absolute UTF-8 paths, `subtree` inside `root`. The caller passes paths it already resolved; the owner re-checks that each is absolute, UTF-8 and, for an association, that the root still is a directory. @@ -140,18 +140,20 @@ Every operation takes one request object and answers one reply object. Writes ar | `closed` | This generation is unloading; call the replacement generation | | `storage` | The store failed; the caller reports the failure and keeps the Session or worktree for a retry | +When a change, text or removal callback refuses, the operation carries the callback's own `code` and `message` unchanged in `rejected`. + ### Flows | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `create` | Validate the id and the workspace, take the exclusion, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller keeps the id it supplied and decides whether to publish or delete the Session | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | +| `create` | Validate the id, take the exclusion, validate the workspace, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller keeps the id it supplied and decides whether to publish or delete the Session | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | | `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove visible and Timeline rows, schedule the file sweep | Before the first commit: every row stays. After: the steps run to their end | The work continues under the owner's task; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | | `fork` | Take the exclusion, read the source text, call `text`, copy in bounded transactions with the returned text, write the target row, commit | Before the first copy; a refused text step copies nothing | The copy continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | | `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | -| `catalog`, `query` | One consistent read under the caller's token | The read stops; no partial page | Nothing to release | Pending reads end `cancelled` | SessionStore | +| `catalog`, `query` | One consistent read under the caller's token | The read stops; no partial page | Nothing to release | Pending reads end `cancelled`; a new call ends `closed` | SessionStore | | `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | | `setTitle` | Admit the write behind earlier admitted writes, read the current title, call `change` under the serialization, write the returned title as revision + 1, commit, announce, answer the revision | Dropping the reply never cancels the admitted write; a change that refuses leaves the title unchanged | The change callback is revoked before it returns; the admitted write fails and the title stays | Close stops admission, waits for every admitted write | SessionStore; the change computes only | -| `removeWorktree` | Validate the paths, take the exclusion, check associations and stored workspaces, call `remove`, delete the record on success, release | The removal step ends `cancelled`; the record stays | The callback ends; the record stays; the exclusion releases | New calls are refused `closed`; an in-flight removal ends, and the record stays unless the step succeeded | Directory by the caller; record by SessionStore | +| `removeWorktree` | Validate the paths, take the exclusion, check associations and stored workspaces, call `remove`, delete the record on success, release | The removal step refuses with its own code (for example `cancelled`); the record stays | The callback ends; the record stays; the exclusion releases | New calls are refused `closed`; an in-flight removal ends, and the record stays unless the step succeeded | Directory by the caller; record by SessionStore | ## Exceptions with reasons @@ -161,6 +163,18 @@ Every operation takes one request object and answers one reply object. Writes ar - `removeWorktree` runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. - `owner` answers the Agent id for a delete notice; the Agent directory's own records are not returned here. +## Client-visible changes + +None. The client methods (`session.rename`, `sessions.list`, `session.delete`, `session.fork`) keep their request and reply shapes; the redesign changes the plugin surface only. + +## Supersedes + +- [Resource faces §5 and §5.2](../resource-faces.md): the `store`/`timelineStore` split, the Session row operations, the Rust `Store` binding and the metadata and association rows. +- [Service faces §3.3 and §3.4](../service-faces.md): the `sessionStore` row and the `store` and `timelineStore` rows. +- [Resource owner operations](../contracts/resource-owner-operations.md): the `SessionStore → sqliteStorage` rows and the Session row paragraphs. +- [Session title metadata](../appserver/session-title-metadata.md): the `readMetadata` and `setTitle` shapes. +- [SessionTitle](SessionTitle.md): the paragraph that writes a title under an expected revision. + ## Verification Flow tests on the owner: @@ -202,7 +216,9 @@ Material uncertainty: a process death during the caller's removal step leaves th ## Requirements raised to mechanism owners -1. **SessionScope (#2025): `timelineStore` ownership aligned.** This owner owns the Timeline operations and the `timelineStore` face; SessionScope binds that face at the Session instance. The face does not carry `createSession`, `releaseSession`, `rollbackSession` or `append`; those belong to the store's own creation and commit paths. The process `store.query` and `store.sessionConfig` are the same engine's reads for callers outside a Session (loaded or not) and keep one implementation. A comment on #2025 records the alignment. +1. **SessionTitle (#2033): the title write is a change callback.** `store.setTitle(id, change)` receives the current title, its source and revision, and returns the next title or its own refusal; the owner serializes the write and announces the commit. The revision-checked `{expectedRevision, title}` shape in SessionTitle.md and session-title-metadata.md is superseded; the manual-title rule moves into the change. A comment on #2033 states the requirement. + +2. **SessionScope (#2025): `timelineStore` ownership aligned.** This owner owns the Timeline operations and the `timelineStore` face; SessionScope binds that face at the Session instance. The face does not carry `createSession`, `releaseSession`, `rollbackSession` or `append`; those belong to the store's own creation and commit paths. The process `store.query` and `store.sessionConfig` are the same engine's reads for callers outside a Session (loaded or not) and keep one implementation. A comment on #2025 records the alignment. ## Binding appendix @@ -211,6 +227,7 @@ The service is marked on the `SessionStore` type; the wire name stays `store`. ` ```rust use dim_agent_capabilities::host::CancelledFn; use dim_agent_runtime::{PublicService, SessionConfig}; +use std::future::Future; use dim_agent_types::grant::{GrantKind, GrantMode, SessionGrant}; use rutis::Ctx; @@ -243,14 +260,58 @@ pub struct TitleState { pub title: Option<Title>, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CreateSession { + pub id: String, + pub config: SessionConfig, + pub agent_id: String, + pub protocol_version: u32, + pub leader: Option<String>, + pub origin: dim_agent_types::SessionOrigin, + pub worktree: Option<Worktree>, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct DeleteSession { + pub id: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DeleteSessionReply { + pub had_rows: bool, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ForkSession { + pub source: String, + pub id: String, + pub at: u64, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SetTitle { + pub id: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TitleReply { + pub revision: u64, +} + /// The caller's fork decision: the source's exact configuration text in, the target's text or its own refusal out. pub type TextFn = Arc< - dyn Fn(String) -> rutis::host::BoxFuture<'static, Result<String, Rejected>> + Send + Sync, + dyn Fn(String) -> rutis::host::BoxFuture<'static, Result<String, StoreRejected>> + Send + Sync, >; /// The caller's decision: the current title and revision in, the next title (none clears) or its own refusal out. pub type ChangeFn = Arc< - dyn Fn(TitleState) -> rutis::host::BoxFuture<'static, Result<Option<Title>, Rejected>> + dyn Fn(TitleState) -> rutis::host::BoxFuture<'static, Result<Option<Title>, StoreRejected>> + Send + Sync, >; @@ -271,14 +332,23 @@ pub struct Directory { /// The caller's own refusal or failure, carried unchanged. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, thiserror::Error)] #[error("{code}: {message}")] -pub struct Rejected { +pub struct StoreRejected { pub code: String, pub message: String, } +impl From<rutis::host::CallError> for StoreRejected { + fn from(error: rutis::host::CallError) -> Self { + Self { + code: error.code().unwrap_or_else(|| "rejected".into()), + message: error.message().to_owned(), + } + } +} + /// The caller's own removal step: it removes the checked directory and reports success, or refuses with its own code and message. pub type RemoveFn = Arc< - dyn Fn(String) -> rutis::host::BoxFuture<'static, Result<(), Rejected>> + Send + Sync, + dyn Fn(String) -> rutis::host::BoxFuture<'static, Result<(), StoreRejected>> + Send + Sync, >; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -296,24 +366,13 @@ pub struct DirectoryRecord { pub last_used_at_ms: Option<i64>, } -#[derive(Debug, thiserror::Error)] -pub enum StoreError { - #[error("{0}")] - Invalid(String), - #[error("the Session workspace no longer exists: {0}")] - WorkspaceMissing(String), - #[error("no stored Session {0}")] - NotFound(String), - #[error("{0} is in use")] - InUse(String), - #[error("{code}: {message}")] - Rejected { code: String, message: String }, - #[error("the call was cancelled")] - Cancelled, - #[error("the store is unloading")] - Closed, - #[error("{0}")] - Storage(String), +/// The wire error: `{code, message}`, with `code` one of the kinds in the error table. +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +#[error("{code}: {message}")] +pub struct StoreError { + pub code: String, + pub message: String, } impl PublicService for SessionStore {} @@ -323,7 +382,7 @@ impl SessionStore { pub async fn create( &self, caller: &Ctx, - request: Create, + request: CreateSession, cancelled: CancelledFn, ) -> Result<(), StoreError> { // ... @@ -332,30 +391,30 @@ impl SessionStore { pub async fn delete( &self, caller: &Ctx, - request: Delete, + request: DeleteSession, cancelled: CancelledFn, - ) -> Result<DeleteReply, StoreError> { + ) -> Result<DeleteSessionReply, StoreError> { // ... } pub async fn fork( &self, caller: &Ctx, - request: Fork, + request: ForkSession, text: TextFn, cancelled: CancelledFn, ) -> Result<(), StoreError> { // ... } - pub async fn set_title( + /// Admits the write under the owner's serialization and returns the wait future; dropping it never cancels the admitted write. + pub fn set_title( &self, caller: &Ctx, request: SetTitle, change: ChangeFn, - cancelled: CancelledFn, - ) -> Result<TitleReply, StoreError> { - // ... + ) -> impl Future<Output = Result<TitleReply, StoreError>> + Send + 'static { + // admits the write, starts the owner's task, returns the wait } pub async fn remove_worktree( diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 1db4af1c80..a2cc2bac11 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -2,7 +2,7 @@ Overall design: [overview](../overview.md) (SessionTitle). Scope: [ADR 002](../../adr/002-plugin-scope.md) (Session). -SessionTitle is a Session plugin that gives an interactive leader Session a title stored through SessionStore metadata. It observes its own Session through the existing Session broadcast; when the first eligible input on `main` is adopted (`input/applied`) — an operator input with `user` content, or Goal's applied objective (A10) — it generates a title from that input's text alone through the routing policy in §3.3. The title is SessionStore state: SessionTitle writes it only through SessionStore's typed `setTitle` operation, and SessionStore announces each change with a Session broadcast notice that clients consume (the delivered C6 notice record is described in [§9](#9-requirements-raised-to-mechanism-owners); the SessionStore title metadata and the Rpc forwarding are supplements in [overview Appendix B.2](../overview.md#b2-app-server-process-plugins)). It serves `session.rename` by registering the namespace `session.rename` with its Session's `sessionMethods` ([methods and tool contributions](../contracts/session-boundary.md)), and it writes the title a Session's creation requested, once, as the first manual title (§3.4). It writes no Timeline event and has no model-visible effect. Contracts are given in neutral form ([ADR 002 D5](../../adr/002-plugin-scope.md#d5-contracts-are-language-neutral)); the Rust binding is in Appendix G. +SessionTitle is a Session plugin that gives an interactive leader Session a title stored through SessionStore metadata. It observes its own Session through the existing Session broadcast; when the first eligible input on `main` is adopted (`input/applied`) — an operator input with `user` content, or Goal's applied objective (A10) — it generates a title from that input's text alone through the routing policy in §3.3. The title is SessionStore state: SessionTitle writes it only through `store.setTitle` with a change callback, which receives the current title and returns the next one, and SessionStore serializes the write, and SessionStore announces each change with a Session broadcast notice that clients consume (the delivered C6 notice record is described in [§9](#9-requirements-raised-to-mechanism-owners); the SessionStore title metadata and the Rpc forwarding are supplements in [overview Appendix B.2](../overview.md#b2-app-server-process-plugins)). It serves `session.rename` by registering the namespace `session.rename` with its Session's `sessionMethods` ([methods and tool contributions](../contracts/session-boundary.md)), and it writes the title a Session's creation requested, once, as the first manual title (§3.4). It writes no Timeline event and has no model-visible effect. Contracts are given in neutral form ([ADR 002 D5](../../adr/002-plugin-scope.md#d5-contracts-are-language-neutral)); the Rust binding is in Appendix G. ## 0. Implementation boundary @@ -39,7 +39,7 @@ only outcome and duration. | Observation | Read the Session id from `sessionIdentity`, the creation configuration from `sessionConfig` and closing from `sessionLifecycle` ([plugin contract](../plugin-contract.md#9-requirements-raised-to-mechanism-owners) R2), then the records on its Session's `session/{sessionId}` channel. C4 broadcast #180 is delivered; #63/#168 are closed. | | Timeline reads | Use the Session’s branch query facade on `main`, with a fixed published cutoff. Read only the adopted input identity, its user content or Goal objective, and the adopted model fields (§0.1). | | Configuration | Existing named Settings and row source declaration, user scope only (A.3/A12). Read settings.read({source:"session-title",scope:"user"}) at each decision and use its validated/defaulted document directly. | -| Metadata/notice | S5b #60/#96 defines the process service `sessionMetadata` (`read` and `setTitle`, both async), its errors `conflict`/`not_found`/`storage`, the handover and the v3 list fields `title`/`titleSource`/`titleRevision` ([title metadata](../appserver/session-title-metadata.md)); A.2 restates that contract. After each commit SessionStore calls `session_broadcast::notify`, and Rpc forwards the record to attached v3 clients as `session.notice {sessionId, source, kind, data}` (C6 #49/#85, [Session broadcast notices](../appserver/session-notices.md)). Names, modes, handover and errors follow S5b. | +| Metadata/notice | The process `store` face provides `title` and `setTitle(id, change)`; `setTitle` commits the title the change returns and answers the revision, with errors `rejected`/`not_found`/`storage` ([SessionStore](SessionStore.md)); the v3 list fields are `title`/`titleSource`/`titleRevision`. After each commit SessionStore calls `session_broadcast::notify`, and Rpc forwards the record to attached v3 clients as `session.notice {sessionId, source, kind, data}` (C6 #49/#85, [Session broadcast notices](../appserver/session-notices.md)). | | Auxiliary request | The profile's model-selection owner implements AuxiliaryModel and its named `auxiliaryModel.complete` HostDispatch/catalog binding: Provider in the product profile, ConfiguredModels in the model-config profile. Inject it through ordinary C4 dependencies; credentials stay with that owner ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)). | | Policies | A1–A12 define the first implementation. Appendix D requires public-flow acceptance; documentation CI alone is not runtime acceptance. | @@ -84,6 +84,8 @@ The fixed snapshot ends at returned T, not necessarily at N. Its first adopted e supplies text. With model=null, the latest ContextConfiguredData.settings in that snapshot supplies providerId/modelId; without an adopted model, generation uses the excerpt fallback in §3.3 instead of the profile's current default. +The sequence diagrams in this appendix predate the `setTitle` change callback and show `setTitle(expected revision, title)`; the target call is `setTitle(id, change)` ([SessionStore](SessionStore.md)). + Cancellation before setTitle handover stops work without writing. The handover is the setTitle call itself: from then on SessionStore settles its own atomic operation, and a lost reply does not authorize repeating or undoing it ([S5b §6](../appserver/session-title-metadata.md#6-handover-cancellation-and-settlement)). No rollback or @@ -149,7 +151,7 @@ flowchart TB classDef new fill:#d3f9d8,stroke:#2b8a3e,color:#000 ``` -SessionStore owns the title: it keeps the text, source and revision counter and accepts changes only through its typed `setTitle` operation, which SessionTitle alone calls. After each committed change SessionStore emits a title notice on the Session broadcast (A11); the title never enters the Timeline. Each decision reads Settings first and skips disabled generation before metadata or Timeline queries; otherwise it reads metadata and the required fields at a fixed cutoff. An image-only first input is remembered for the loaded generation. In-memory state is lost on reload or Session unload, which only allows another attempt. +SessionStore owns the title: it keeps the text, source and revision counter and accepts changes only through `setTitle(id, change)`, which SessionTitle alone calls. After each committed change SessionStore emits a title notice on the Session broadcast (A11); the title never enters the Timeline. Each decision reads Settings first and skips disabled generation before metadata or Timeline queries; otherwise it reads metadata and the required fields at a fixed cutoff. An image-only first input is remembered for the loaded generation. In-memory state is lost on reload or Session unload, which only allows another attempt. ## 3. Flows @@ -196,7 +198,7 @@ sequenceDiagram ST-->>Rpc: title, titleSource manual, revision ``` -Rpc resolves the Session as for any Session method, loading it if needed. On `conflict` SessionTitle rereads and retries up to 3 times. +Rpc resolves the Session as for any Session method, loading it if needed. A `rejected` change is SessionTitle's own refusal; a title the operator set is decided inside the change. ### 3.3 Generation routing and optional service @@ -261,7 +263,7 @@ sequenceDiagram - **Once.** The write happens only while the stored revision is 0. A later rename or clear is therefore never undone by a reload: the configuration keeps `initialTitle`, and the part skips the write once anything has titled the - Session. A `conflict` at `setTitle` means another writer titled it first, and that title wins. + Session. The change sees the current title, so a title another writer committed first is inside the decision. - **The text rule.** It is `session.rename`'s: trim the text, and write nothing for an empty one or one with a control character or a line separator. The length is bounded to the operator's `maxLength` the way a fallback title is, and punctuation stays: `title_text` strips it because it is for model output, and this text is the caller's. @@ -381,7 +383,7 @@ Registered with `sessionMethods` (Session, namespace `session.rename`) with one | Service | Method | Kind | Request | Reply and errors | | --- | --- | --- | --- | --- | | SessionStore `sessionMetadata` (S5b) | `read` | async | `{sessionId}` | `{revision, title: {text, source: "auto" \| "manual"} \| null}`; errors `not_found`, `storage` ([S5b §4](../appserver/session-title-metadata.md#4-operations)) | -| SessionStore `sessionMetadata` (S5b) | `setTitle` | async | `{sessionId, expectedRevision, title: {text, source} \| null}` | `{revision}`; errors `conflict`, `not_found`, `storage`. The call is the handover; after a commit SessionStore emits the title notice | +| SessionStore `store` | `setTitle` | async | `{sessionId}` plus a change that receives `{revision, title}` and returns the next title or `null` | `{revision}`; errors `rejected`, `not_found`, `storage`. The call is the handover; after a commit SessionStore emits the title notice | | SessionStore (S5b) | title notice | Session broadcast notice (C6 record, §9) | — | `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}` on the Session's broadcast channel; no sequence number, not replayed | | `AuxiliaryModel` (the profile's model-selection owner) | `complete` | async | `{model: {providerId, modelId}, request: {system, messages: [{role: "user", content: text}]}}`, optional `cancelled: () => Promise<void>` ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)) | `{text, stopReason, usage}`; rejects with the existing error code/message. Resolve the cancellation reference on timeout or closing and await the original call's settlement | @@ -411,7 +413,7 @@ omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remain | Check | `sessionMetadata.read({sessionId})`: skip if any title exists; keep revision `r` | | Read | The four field queries in §0.1 share published T >= N. No adopted eligible input/text means no title (A8/A10). | | Generate | Route and fall back under §3.3 within the shared 30 s budget (A4); normalize the first line, remove quotes and trailing punctuation, collapse whitespace, cut at `maxLength`, trim again | -| Write | `setTitle({sessionId, expectedRevision: r, title: {text, source: "auto"}})`; `conflict` or `not_found` discards | +| Write | `setTitle({sessionId}, change)` where the change returns the generated title or `null`; a `rejected` change discards | | Timeline | No writes, no Dispatcher registration, no `StateCell` | | Reload / unload | Cancel before store handover; the owner settles an admitted mutation. Events in the gap are not replayed | diff --git a/docs/design/plugins/SqliteStorage.md b/docs/design/plugins/SqliteStorage.md index 92bf384d86..37b0414f21 100644 --- a/docs/design/plugins/SqliteStorage.md +++ b/docs/design/plugins/SqliteStorage.md @@ -12,7 +12,7 @@ SqliteStorage owns: - **The format.** The version row, the schema, the ordered upgrades and the refusal of an unsupported format. - **The connections.** One writer connection with its queue, a read pool, the WAL checkpoint and the close drain. - **Transactions and reads.** One commit or one consistent read per call; the engine does not interpret the rows. These operations are the engine's private implementation for the data owners; they are not a service face. -- **Offline operations.** Backup, restore and vacuum, each holding the same lease and refusing while a daemon owns the store. +- **Offline operations.** Backup and vacuum hold the same lease and refuse while a daemon owns the store; restore writes a new destination that must not exist yet, and its exclusion is that destination rule. - **The capacity value.** Database bytes, WAL bytes and reclaimable bytes, read through `storageReport`. The rows belong to their data owners, and their operations live on those owners' faces: the Session rows and the Timeline batches to [SessionStore](SessionStore.md), the Agent records to Agents and Collaboration ([#2098](https://github.com/arcships/dim/pull/2098)), the Settings documents to Settings ([#2094](https://github.com/arcships/dim/pull/2094)), the Provider records to Provider ([#2096](https://github.com/arcships/dim/pull/2096)). The engine executes each owner's transactions and returns the stored form; it answers no business read or write on its public face and is not in the catalog for those rows. @@ -26,7 +26,8 @@ Callers keep: | Requirement (public callers) | Compose from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | | Report the store's own bytes | No: only the process holding the file knows them | `storageReport` | -| Back up, restore or vacuum the store while no daemon owns it | No: the operation needs the file lease and the format check | `backup`, `restore`, `vacuum` | +| Back up or vacuum the store while no daemon owns it | No: the operation needs the file lease and the format check | `backup`, `vacuum` | +| Restore an archive into a new store | No: the destination rule and the format check are the owner's | `restore` | | Bind the daemon's endpoints after the database lock is held | No operation: the dependency orders loading | the `sqliteStorage` key in `injects` | The transaction operations the data owners use are not on this face: Settings, Provider, Agents, Collaboration and SessionStore call them as crate-private operations of the engine, and each owner's contract owns the request, reply and error shapes. A caller that needs different data asks the row's owner, not the engine. @@ -56,9 +57,9 @@ None. The assembly provides the store; deployment chooses its instance. Offline | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `storageReport` | The store's own file bytes, WAL bytes and reclaimable bytes | `{}` | `{databaseBytes, walBytes, reclaimableBytes}` | None | `storage` | +| `storageReport` | The store's own file bytes, WAL bytes and reclaimable bytes | `{}` | `{databaseBytes, walBytes, reclaimableBytes}` | None | `closed`, `storage` | | `backup` | Copy a closed store and its sidecar files into an archive | the database path and the destination | `{}` | None; the tool runs alone | `owned`, `storage` | -| `restore` | Replace a store from an archive produced by `backup` | the archive and the destination | `{}` | None; the tool runs alone | `owned`, `format`, `storage` | +| `restore` | Write a store from an archive produced by `backup` into a destination that does not exist | the archive and the destination | `{}` | None; the tool runs alone | `format`, `storage` | | `vacuum` | Remove the content rows no stored reference reaches and reclaim the file's free pages | the database path | the removed rows, content bytes and sizes | None; the tool runs alone | `owned`, `format`, `storage` | `storage.report` is the client method registered through `managementMethods`; the registration point calls `storageReport` and is not a second operation. The transaction operations the data owners use are private to the storage crate and are listed in their owners' contracts. @@ -79,13 +80,14 @@ The engine answers no business error: a missing row, a stale version or a refuse | --- | --- | --- | --- | --- | --- | | Open, upgrade, verify | Open the file, take the lease, read and write the format, run the ordered upgrades in one transaction, start the writer and the read pool | Not applicable: assembly admits the daemon once | Not applicable | A failed open leaves the previous format, or the startup note names the newer store | File and lease by SqliteStorage; the process exits | | `storageReport` | Read the file sizes and the free-page count | None | Nothing to release | Pending calls end `closed` | SqliteStorage | -| `backup`, `restore`, `vacuum` | Take the same lease, operate on the file, release | Not applicable; the tool runs alone | Not applicable | Refused while a daemon holds the lease | The offline tool and SqliteStorage share the lease | +| `backup`, `vacuum` | Take the same lease, operate on the file, release | Not applicable; the tool runs alone | Not applicable | Refused while a daemon holds the lease | The offline tool and SqliteStorage share the lease | +| `restore` | Require a destination that does not exist, write the archive there, verify the format | Not applicable; the tool runs alone | Not applicable | A destination a daemon owns is refused by the non-existence rule | The offline tool | | Close | Refuse new work, wait for the running calls, close the readers, checkpoint, close the writer, release the lease | Not applicable | In-flight calls finish | The next process opens after the lease is free | SqliteStorage | | Private transactions | The data owner's call runs on the writer or a pooled reader, under the open store's drain | The owner's operation decides its own cancellation | The writer completes or rolls back the transaction | The admitted calls end before close | SqliteStorage; the owner's contract owns the operation | ## Exceptions with reasons -- Offline tools (`dim-migration`, backup, restore, vacuum) open the file under the same lease and write rows in the published format: an import or a repair runs while no daemon may own the store, and the format is the contract both sides implement. The lease is the exclusion; the format version is the gate. +- Offline tools (`dim-migration`, backup, restore, vacuum) write the published format while no daemon owns the store: backup, migration and vacuum take the same lease; restore writes a destination that must not exist. The format version is the gate for every one. - `storageReport` is a client method and a service operation: the management method is a registration point (ADR 002), and the service operation is the same read for plugins. - The data owners' transaction operations are crate-private: each owner's contract defines its request, reply and errors, and the engine executes them without interpreting the rows. Publishing them again under `sqliteStorage` would answer the owners' business on the engine's face. @@ -96,9 +98,20 @@ Flow tests on the owner: - Opening a newer format refuses and leaves the file unchanged; an upgrade is one transaction; a second process fails to open while the lease is held. - `storageReport` answers the file, WAL and free-page values; the client method returns the same values. - Closing drains the running owner calls, checkpoints and releases the lease; an offline tool cannot open while the daemon owns it. -- A backup round-trips through restore; vacuum refuses a store a daemon owns and a store whose format differs. +- A backup round-trips through restore; restore refuses an existing destination; vacuum refuses a store a daemon owns and a store whose format differs. - The data owners' transactions are tested by their owners' flow tests; the engine's tests cover their commit, rollback and drain, not their business answers. +## Client-visible changes + +None. The `storage.report` client method keeps its request, reply and error shapes; the offline CLI commands are unchanged. + +## Supersedes + +- [Resource owner operations](../contracts/resource-owner-operations.md): the Native storage section — the `SessionStore → sqliteStorage` rows, the Settings and Provider storage tables and the `sqliteStorage` public face. +- [Resource faces §5](../resource-faces.md): the `sqliteStorage` paragraph of the `store`/`timelineStore` section. +- [Service faces §3.4](../service-faces.md): the `sqliteStorage` row. +- [Native storage format](../appserver/native-storage-format.md): the paragraphs that describe the public storage face. + ## Rule check | Rule | Application | @@ -145,16 +158,19 @@ pub struct Capacity { pub reclaimable_bytes: u64, } -#[derive(Debug, thiserror::Error)] -pub enum StorageError { - #[error("{0}")] - Storage(String), - #[error("another process owns the database")] - Owned, - #[error("{0}")] - Format(String), +/// The wire error: `{code, message}`, with `code` one of `storage`, `owned` or `format` for the offline functions. +#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +#[error("{code}: {message}")] +pub struct StorageError { + pub code: String, + pub message: String, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Empty {} + impl PublicService for SqliteStorage {} #[rutis::service(name = "sqliteStorage")] diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index e5dd257f13..116fefe951 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -583,10 +583,9 @@ grant, and tool approval still follows the preset ### 4.6 Session files and exec output -`sessionFiles.put` uses `createDirectory` and `replace` with `permissions: "privateReadOnly"` to -store the file on the resource node. It returns a node path and owns the rows under the -[Session-file contract](appserver/session-files.md#31-on-disk). Command output stays on the node -and is read through `execHost.output` and `execHost.tail` (§3.4–§3.5). +Session files are [SessionFiles](plugins/SessionFiles.md): the file id, the page read, the import +reply and the ownership rows are defined there. Exec output ownership is ADR 013; the tool that +produces a path registers it through `sessionFiles.register`. ### 4.7 Errors @@ -604,18 +603,18 @@ 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. -SessionTitle and FileAccess use the process repository operations in the [resource owner contract](contracts/resource-owner-operations.md). +The repository and Timeline operations are the Session store's, defined in +[the SessionStore contract](plugins/SessionStore.md): process `store` provides the repository +operations and the Timeline reads for callers outside a Session, and Session-scoped +`timelineStore` is the same owner's Timeline face, bound at the Session instance by SessionScope. +`createSession`, `releaseSession`, `rollbackSession` and `append` are the store's own creation and +commit paths, not operations of that face. | Family | Operations | | --- | --- | -| Timeline (`timelineStore`) | `createSession`, `sessionConfig`, `releaseSession`, `rollbackSession`, `append` (sync), `head`, `branches`, `readPage`, `readSegments`, `query`, `trace`, `batchEnd`, `batchEndAt`, `saveSnapshot`, `latestSnapshot` | +| Timeline (`timelineStore`) | `sessionConfig`, `head`, `branches`, `readPage`, `readSegments`, `query`, `trace`, `batchEnd`, `batchEndAt`, `saveSnapshot`, `latestSnapshot` | | Timeline completion (`timelineStore`) | `commits`, `closeCommits`; notifications `{subscriptionId, batchId, branchId, through, result}` | -| Session rows (`store`) | The repository operations listed in §5.2 | +| Session rows (`store`) | The repository operations in [SessionStore](plugins/SessionStore.md) | | Worktree association (`store`) | `associateWorktree`; [service faces](service-faces.md) §4.8 | ### 5.1 Ordered admission and durable completion @@ -668,15 +667,13 @@ it does not introduce a separate wire operation or replace an override with fall 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. -`createSession {sessionId,config}`, `releaseSession {sessionId}`, `rollbackSession {sessionId}` -and `saveSnapshot {sessionId,branchId,snapshot}` return `{}`. `sessionConfig {sessionId}` returns +`saveSnapshot {sessionId,branchId,snapshot}` returns `{}`. `sessionConfig {sessionId}` returns `{config}`. `latestSnapshot {sessionId,branchId,through,interpreter}` returns `{snapshot}`. -These are storage lifecycle steps. `createSession` prepares the backend record; it does not -initialize or publish an Agent Session. `rollbackSession` undoes a successfully prepared creation -whose initialization failed, after its producers have stopped; it is not the general deletion -workflow. `releaseSession` drains accepted backend writes and releases their resources without -closing the Agent Session or its admission. App Server creation/deletion retain the repository -and lifecycle obligations in §5.2. +`createSession`, `releaseSession`, `rollbackSession` and `append` are the store's own creation and +commit steps, not operations of the `timelineStore` face: the Session store prepares the backend +record, rolls back a prepared creation, releases a Session's writes and admits batches inside its +own operations ([SessionStore](plugins/SessionStore.md)). App Server creation/deletion retain the +repository and lifecycle obligations the contract states. Snapshots retain their canonical fields (`sequence`, `event_id`, `interpreter`, `state`), optional acceleration semantics and owner validation. Domain errors preserve `{code,message}` using @@ -709,135 +706,10 @@ with the existing ordering and draining. ### 5.2 Session rows -The process `store` face exposes the existing Session repository operations below. -Every method is asynchronous. Paths are the caller's already resolved absolute strings; -`config` is the existing SessionConfig data and `configText` retains its exact stored bytes. -The operations keep the owner transactions and existing existence checks; they do not -resolve paths, decide permission or create a second Session lifecycle. - -| Operation | Request | Reply | -| --- | --- | --- | -| `addGrant` | `{sessionId,path,kind,mode}` | `{}` | -| `removeGrant` | `{sessionId,path}` | `{}` | -| `grants` | `{sessionId}` | `{grants:[{path,kind,mode}]}` | -| `setSessionLanguage` | `{sessionId,language}` | `{}` | -| `creationRecord` | `{sessionId}` | `{origin,leaderSessionId}` | -| `owner` | `{sessionId}` | `{agentId}` | -| `hasRecords` | `{sessionId}` | `{exists}` | -| `createOwnedSession` | `{sessionId,config,agentId,protocolVersion,leaderSessionId,origin,worktree}` | `{}` | -| `sessionConfig` | `{sessionId}` | `{config}` | -| `sessionConfigText` | `{sessionId}` | `{configText}` | -| `fork` | `{sourceSessionId,sessionId,at,configText}` | `{}` | -| `delete` | `{sessionId}` | `{removed}` | -| `worktreeDirectories` | `{}` | `{directories:[{repository,root,lastUsedAtMs}]}` | -| `sessionsUnderWorkspace` | `{root}` | `{sessionIds}` | -| `worktreeUsages` | `{repository,root}` | `{usages:[{sessionId,subtree}]}` | -| `removeWorktreeDirectory` | `{repository,root}` | `{removed}` | -| `removeWorktree` | `{repository,root}`, asynchronous removal callback | `{removed}` | -| `removeUnregisteredDirectory` | `{root}`, asynchronous removal callback | `{removed}` | -| `catalog` | `{request,agent?,version,hosts,closed}` | existing catalog page | -| `query` | `{scope,query,page?}` | `{result,next}` | - -These are repository steps, not the client lifecycle workflows `sessions.delete` and -`session.fork`. Trusted plugins may address any Session id; the process face does not apply -per-caller Session ownership or grant scoping. The lifecycle owner remains responsible for: - -- `createOwnedSession`: reserve the creation/admission identity, select a supported protocol, - validate the configuration and apply that protocol's live feature restrictions before - persisting it, then initialize/publish the Session or roll the preparation back. -- `delete`: close the Session and settle its producers before removing its rows and output. - This operation neither closes a live Session nor removes its Agent admission slot. -- `fork`: validate the source collaboration role, published main cut, atomic/context boundary - and rest point; supply the source's stored configuration text with `initialTitle` removed, - then initialize the fork under the source Agent/protocol. The repository copies the supplied - text without applying live protocol exclusions or rebuilding the configuration. - -`createOwnedSession`, `fork` and `delete` reject Session ids that are not a single normal path -component with `invalid`, before acquiring ownership or touching rows or output paths. These -checks are shared with the native Session admission/deletion boundary. - -Grant kind is `file` or `dir`, mode is `read` or `write`; adding read never downgrades -an existing write grant. `language` is a ReplyLanguage code or null to clear it. -`origin` is the existing Session origin. `leaderSessionId`, `agentId`, `config` and -`configText` are null when the corresponding optional owner value is absent; -`creationRecord` and language writes still reject a missing Session. `worktree` -is null or `{repository,root,subtree}`. Session creation retains the atomic -owner/configuration/worktree publication. `lastUsedAtMs` is null for legacy directory -records without an association timestamp. - -`removeWorktree` holds the owner exclusion for its usage checks and for registering the -resolved root as being removed, then releases it and awaits the callback, which receives -the checked root path; the exclusion is taken again only to delete the directory row after -the callback returns. No SQL or Timeline commit lock is held while awaiting it. The -registration ends in the removal's own task, so dropping the caller stops neither the -deletion nor the registration. While it runs, `createOwnedSession`, `fork`, -`store.associateWorktree`, `removeWorktreeDirectory`, `removeWorktree` and -`removeUnregisteredDirectory` are refused with `invalid` for a path at, under or above the -registered one, and proceed for unrelated paths. The callback may refuse with `invalid`, -`cancelled` or `storage`; unexpected callback or transport failures are `storage`. A -callback failure leaves the directory row in place and no registration. The registration -is the only record of the removal: there is no separate check/remove lease, and a Session -creation on a directory being removed is refused instead of waiting for it. -`removeWorktreeDirectory` is the existing database-only candidate cleanup, with its -existing association checks and the same refusal for a path being removed. - -`removeUnregisteredDirectory` takes `{root}` and the same asynchronous removal callback. -It is the unregistered removal of -[worktree management §5](worktree-management.md#5-列出删除与清理): the root is absolute -without relative components, and the operation holds the owner exclusion for its -directory-record and workspace checks and for registering the resolved root, then awaits -the callback, which re-checks the unregistered filesystem facts before it deletes -anything. A callback failure is `invalid`, `cancelled` or `storage` as above. The -registration keeps the root refused to the operations above until the same removal task -clears it, and the deletion itself has no time limit: it covers a recursive `--force` -deletion of any size. Dropping the caller stops neither the deletion nor the registration. - -`catalog` takes the existing Session catalog request and the calling Agent owner's -loaded/closed snapshots. Its result is the stored catalog page: sequence comes from the -database and `closed` is false on each returned row. The Agent lifecycle owner enriches that -page with live sequence and closed state for client responses; `store.catalog` does not read -or reproduce AgentIndex. Its pagination and filtering remain the storage catalog contract. `query` takes the existing fixed read scope: `{key:{sessionId, -branchId},through,segments:[{branchId,from,through,storedThrough,tail}]}`. Its query, -page, result and immutable tail events retain the Timeline query contract. Neither -operation adds a preliminary query or rereads the caller's snapshots. - -Refusals are `{code,message}`: `invalid`, `closed`, `cancelled` or `storage`, preserving -the owner message. Existing absence behavior is retained: `addGrant` on an unknown Session -fails `storage` (foreign-key refusal), `removeGrant` succeeds without a matching row, and -`setSessionLanguage` fails `closed`. Unsupported protocol versions retain the native database -`storage` refusal; the lifecycle owner validates versions before preparation. These methods expose storage operations to trusted plugins, not -new external client entry points. Session files use `sessionFiles`. Metadata consumers call `store.readMetadata` and `store.setTitle`; FileAccess calls `store.associateWorktree`. Retire the catalog entries `sessionMetadata` and `worktreeAssociations` when migrating their callers. - -The Rust `Store` binding exposes only these repository operations and directly returns -the same owner's operation futures. Its typed key and dispatcher share one binding; -`SessionStore` remains the native bootstrap/implementation owner, not the public `store` -type. Title reads use `store.readMetadata`. Native shared result types -and filesystem paths retain their existing lossless Rust representation; only the wire -boundary serializes paths as data. The existing asynchronous removal callback keeps its -original path argument and ownership exclusion. - - -- `store.associateWorktree {sessionId, repository, root, subtree}` writes the worktree directory - record and the Session usage association as one commit and answers `{}` after it, so the reply is the - acknowledgement the file facts owner waits for before publishing a confirmed root (§4.2.1). Its - deduplication, its place in Session deletion and its format decision belong to - [worktree access §4](worktree-access.md#4-持久使用关联与清理边界) and the storage owner; the - directory identity is Session memory and is not stored by this operation. -- `fork` and `delete` keep their accepted storage contract: the visibility switch is one - transaction, and the copy or removal around it is written in bounded chunks so one large - Session cannot hold the writer for every other Session - ([deletion and fork](appserver/session-deletion-and-fork.md), - [timeline storage](../architecture/rust-agent/timeline-storage.md) §3). This face does not - restate those steps; it exposes them as one operation each. -- The Session-row operations are the repository operations of - [#1298](https://github.com/arcships/dim/issues/1298); that issue's list and field sets are the - contract, and this document does not pre-empt them. -- Both SQLite and PostgreSQL implement the same face. Which engine answers is configuration of - the state owner, not a difference the caller sees; a Session whose state is unreachable is a - failed call, and the Session layer's own rule decides whether it stops - ([#1298](https://github.com/arcships/dim/issues/1298)). -- One Session has one writer, and the store face carries no lease, takeover or second-writer - operation: that rule belongs to the Session owner, above the store. +Superseded by [the SessionStore contract](plugins/SessionStore.md). The Session repository +operations, the title and association operations, the worktree removal and the error kinds are +defined there; the Rust `Store` binding type no longer exists and the service is marked on the +store owner. ## 6. Provider, binding, and the owners that use each operation @@ -936,9 +808,11 @@ No other requirement is raised: the text is the file operation's own (line numbers, previews, image blocks). A command returns records, and the control side composes the tool result, because the task identity, the background policy and the output-path registration are its. -6. **Repository face names.** `store` names the Session-row repository operations, and - `timelineStore` names the Timeline operations and completion notifications. Both delegate - to the same state owner (#1298); the naming split changes neither placement nor ordering. +6. **Repository face names.** `store` names the Session-row repository operations and the + Timeline reads for callers outside a Session; `timelineStore` is the same owner's Timeline + face bound at the Session instance by SessionScope. One owner, two scope bindings + ([SessionStore](plugins/SessionStore.md)); `createSession`, `releaseSession`, + `rollbackSession` and `append` are the owner's own steps. 7. **Root identity form.** The Session passes the opaque `rootIdentity` back to the provider. The provider owns its platform form and comparison. 8. **Retained task records.** Settlement is explicit (§3.8). If a long-lived local provider wants a diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..e34eff2573 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -91,14 +91,14 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `scheduleJobs` | `scheduleJobs.call(JobRequest)` | 按 [Scheduler](plugins/Scheduler.md#a2-tool-schedule) 的 flat `JobRequest`/`JobReply`,与 `wakeups` 同一批次([#1396](https://github.com/arcships/dim/pull/1396))。 | | `wakeups` | `wakeups.create/list/cancel` | 形状按 [Scheduler](plugins/Scheduler.md#102-methods-and-tool) §10.2。 | | `loops` | `loops.start/next/list/stop` | 形状按 [Scheduler](plugins/Scheduler.md#126-interfaces) §12.6;`start`、`next`、`stop` 是迁改,`list` 是读取。投递 pass、恢复与 `settle_delivering` 不在此面。 | -| `sessionFiles` | `sessionFiles.put/import/read/register/owns/owned_paths` | 形状按 [Session files](appserver/session-files.md) §9.1,`SessionFiles` 是进程内绑定。 | +| `sessionFiles` | `sessionFiles.put/import/write/read/register/owns/remove/owned_paths` | 形状按 [SessionFiles](plugins/SessionFiles.md);服务标注在所有者类型上。 | | `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。 | | `sessionLanguage` | `sessionLanguage.get()` | 形状见 §4.8。 | | `skillsConfig` | `skillsConfig.get()` | 形状见 §4.8。 | | `collaborationConfig` | `collaborationConfig.get()` | 形状见 §4.8。 | -| `worktreeAssociations` | `store.associateWorktree` | 形状见 §4.8。 | +| `worktreeAssociations` | 已并入 `store.associateWorktree` | 见 [SessionStore](plugins/SessionStore.md)。 | | `toolSourcesView` | `toolSourcesView.get/observe` | 同一 ToolRegistry owner 的独立只读观察面;贡献注册仍由 `toolRegistry` 负责,见 [工具贡献 §7.5](../architecture/rust-agent/tool-contributions.md#75-服务接口)。 | 宿主读取端口的数据面(§4.10)包括 `executionSettingsHost`、`toolchainSourceHost`、`promptSuggestionSettingsHost`。模型选择与列表统一由 `providerService` 提供;调用方和配置见[进程操作](contracts/process-owner-operations.md);其余读取端口沿用现名。 @@ -113,7 +113,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `settingsService` | `settings` | GoalBranch 的取消契约见 §4.1。 | | `modelHost` | `modelHost` | 完整模型请求直接调用所选配置的执行入口;辅助请求使用 `providerService.complete`。 | | `loader` | `rutis/loader` | 插件管理走数据面 | -| `sessionStore` | `store`、`sessionFiles`、`timelineStore` | 标题与 worktree 关联直接调 store | +| `sessionStore` | `store`、`sessionFiles`、`timelineStore` | 已退役:绑定读取与标题、关联、worktree 记录都是 `store` 的操作,见 [SessionStore](plugins/SessionStore.md) | | `treeCommands`、`timelineTreeControl` | `timelineTree` | 分支操作直接调用 Session 的树;不保留别名 | ### 3.4 对象/句柄:拆成操作加 id @@ -125,8 +125,8 @@ 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) | +| `sqliteStorage` | 连接与事务 | 公开面只剩 `storageReport` 与离线操作;Settings、Provider、Agent 记录与 Timeline 事务是各数据所有者的私有实现([SqliteStorage](plugins/SqliteStorage.md))。 | +| `timelineStore` | 连接与批次 | Session 仓储自己的 Timeline 面,由 SessionScope 在 Session 实例上绑定([SessionStore](plugins/SessionStore.md)):`sessionConfig`/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`createSession`/`releaseSession`/`rollbackSession`/`append` 是所有者内部步骤 | | `promptSourcesBranch` | 分支 prompt 装配 | 按 #1292 确认公共操作与装配内部职责。 | 这些行按当前对象形状分组。前四行的数据契约由 [resource and store data faces](resource-faces.md) 定义(#1295/#1297/#1298)。其余行按 #1292 逐批确定操作面。 @@ -248,7 +248,7 @@ workflowRuns.call(RunRequest) ### 4.5 `sessionFiles` -按 owner 契约 [Session files](appserver/session-files.md) §9.1 暴露 `sessionFiles`。`SessionFiles` 作为这组操作的进程内绑定。 +按 owner 契约 [SessionFiles](plugins/SessionFiles.md) 暴露 `sessionFiles`;服务标注在所有者类型上,不另设包装类型。 文件导入、分块读取、归属操作的参数、回复、错误及取消语义均由 §9.1 定义。文件传输使用按路径导入与有界读取操作。 From 5abf26f3482d4af320e14e35ec272615b991b9ab Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 11:25:22 +0800 Subject: [PATCH 07/19] docs(storage): address round-three review and self-checks Rebase onto main. SessionStore keeps setTitle on the hand-written method table so a dropped wire reply still admits the write; the title interface is migrated in SessionTitle and the title metadata doc to store.title and setTitle(id, change), without expectedRevision or conflict. Resource faces section 5.1 now describes admission and drain as the store's internal steps. SessionFiles removes the unused invalid code from write and reports node_unavailable on remove; the FileStorage dependency drops root_path and states that the host's root set covers the store directory. ManagedWorktrees maps store refusals in discard and deletes the default dim/<taskId> branch of a never-adopted worktree. SqliteStorage reports format from backup and limits the lease to backup and vacuum; the stale pointers are fixed. The binding appendices use the routed error enums with the code tag, the callback error keeps the callback's code in reason, and all four appendices compile in a temporary crate against rutis 0.23. Refs #2018 Refs #2015 --- .../design/appserver/native-storage-format.md | 2 + .../appserver/session-title-metadata.md | 61 ++++---- .../contracts/resource-owner-operations.md | 2 +- docs/design/plugins/ManagedWorktrees.md | 46 ++++-- docs/design/plugins/SessionFiles.md | 139 +++--------------- docs/design/plugins/SessionStore.md | 78 +++++++--- docs/design/plugins/SessionTitle.md | 22 +-- docs/design/plugins/SqliteStorage.md | 31 ++-- docs/design/resource-faces.md | 65 ++++---- 9 files changed, 197 insertions(+), 249 deletions(-) diff --git a/docs/design/appserver/native-storage-format.md b/docs/design/appserver/native-storage-format.md index 5d34144b45..98649be37c 100644 --- a/docs/design/appserver/native-storage-format.md +++ b/docs/design/appserver/native-storage-format.md @@ -1683,6 +1683,8 @@ semantics, preserved Steer candidates, automation origins and rollback. ## SQLite owner operations +These operations are the engine's crate-private implementation for the data owners; the public faces are [SqliteStorage](../plugins/SqliteStorage.md), [SessionStore](../plugins/SessionStore.md), [SessionFiles](../plugins/SessionFiles.md) and each data owner's contract. The paragraphs below describe the internal call flow and remain the implementation record. + Persistent Agents calls `sqliteStorage.agents`, `owners`, `save` and `delete` for its directory and Session ownership. Delegation reads use `members`, `ledMembers`, `ownedAgents`, `memberSessions` and `agentOwner`. Startup repair reads both lists from `unfinishedOwned`. SQLite owns all record reads and writes. SessionStore calls `sqliteStorage.createSession({sessionId,config})` to create a Session and its main branch in one transaction. `sessionConfig({sessionId})`, `branches({sessionId})`, `head({sessionId,branchId})`, `batchEnd({sessionId,branchId,sequence})` and `batchEndAt({sessionId,branchId,sequence})` use the existing TimelineStore requests and replies. The export reads the same branch directory through its read-only snapshot. diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index d1174e48ba..b1a31f074e 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -42,7 +42,7 @@ protocol version. Session scope Process scope (control node) ---------------------------- -------------------------------------------------------------- SessionTitle (Session part) SessionStore (existing plugin) - inject 'sessionMetadata' sessionMetadata (HostDispatch) + inject 'store' store (HostDispatch) read --------------------------> read -> metadata() ------------------+ setTitle ----------------------> setTitle -> set_title() | | v @@ -89,11 +89,11 @@ The `store` face, process scope, control node only, no instance key, provided by | Method | Mode | Request | Reply value | Errors | | --- | --- | --- | --- | --- | -| `title` | async | `{sessionId}` | `{revision, title: {text, source} \| null}` | `not_found`, `storage` | -| `setTitle` | async | `{sessionId}` plus the change callback | `{revision}`: the committed revision | `rejected`, `not_found`, `storage` | +| `title` | async | `{id}` | `{revision, title: {text, source} \| null}` | `not_found`, `closed`, `storage` | +| `setTitle` | async | `{id}` plus the change callback | `{revision}`: the committed revision | `rejected`, `not_found`, `closed`, `storage` | - Replies use one envelope, `{ok: true, value}` or `{ok: false, error: {code, message}}`, as `settings` does. -- Neither method loads the Session. `read` reads committed state and does not wait for the title writer (§5). +- Neither method loads the Session. `title` reads committed state and does not wait for the title writer (§5). - The change returns the next title or `null` to clear; the owner stores what the change returns. A caller's change decides the manual-title rule and the clear, so an omission never erases a user's title. - A malformed call (unknown method, not exactly one request object, an unknown field, a wrong type or a missing @@ -107,9 +107,9 @@ The `store` face, process scope, control node only, no instance key, provided by ### 4.2 Rust -Rust consumers inject the `store` owner and call `title`/`set_title`. The pre-migration binding was `SessionMetadataService`, the typed binding of `sessionMetadata`, and call +Rust consumers inject the `store` owner and call `title`/`set_title`. The pre-migration binding was `SessionMetadataService`, the typed binding of `sessionMetadata`; the target calls `read` and `set_title`. The binding is the existing dispatcher, published at both its typed key -and `host_key("sessionMetadata")`; both routes delegate directly to the same SessionStore owner. +and `host_key("store")` delegate directly to the same SessionStore owner. The existing `SessionMetadata` reply type is unchanged. `set_title` is a regular function returning the owner's wait future. Calling it admits the write @@ -129,7 +129,7 @@ adds no asynchronous wrapper before handover, cancellation point, read, or secon | (one write at a time) +-- BEGIN IMMEDIATE ---------------------------> revision of S | no Session: not_found, rollback - | revision != r: conflict, rollback + | change refuses: rejected, rollback | write r+1 and T +-- COMMIT ------------------------------------> committed, or storage | committed only: @@ -168,7 +168,7 @@ that drops the call still has to read to learn the outcome; and a JavaScript cal | `data` | `{title: string \| null, titleSource: "auto" \| "manual" \| null, titleRevision}` | - **Once per commit.** Emitted after each committed write with SessionStore's own context through - `session_broadcast::notify`. A conflict, a missing Session or a failed write emits nothing. + `session_broadcast::notify`. A rejected change, a missing Session or a failed write emits nothing. - **No `sessionId` in `data`.** The channel names the Session, and Rpc adds `sessionId` to `session.notice` ([C6 D4](session-notices.md#10-decisions)). - **The list's fields.** `data` holds exactly the three title fields of a v3 Session list entry (§8). A client @@ -204,7 +204,8 @@ Rpc never calls `setTitle` and gains no method. How each error reaches clients: | --- | --- | --- | | `storage` | The catalog read fails as it does today | `storage_failed` | | `not_found` | The Session is not listed | `session_not_found` | -| `conflict` | — | SessionTitle reads again and retries ([§3.2](../plugins/SessionTitle.md#32-manual-rename)) | +| `rejected` | — | SessionTitle's change refused (for example a manual title exists); it discards its attempt ([§3.2](../plugins/SessionTitle.md#32-manual-rename)) | +| `closed` | — | `service_reloading`; the call is not admitted and the caller retries on the replacement generation | ## 9. Lifecycle @@ -215,13 +216,13 @@ Rpc never calls `setTitle` and gains no method. How each error reaches clients: | `session.delete` (S5c) | Removed in S5c's single delete transaction, before the Session record. Afterwards `read` and `setTitle` fail `not_found` | | Creation rollback | The same transaction as a delete; it removes a row that a racing write committed | | `session.fork` (S5c) | Not copied ([SessionTitle A7](../plugins/SessionTitle.md#appendix-e-assumptions)): the fork starts untitled at revision 0 | -| SessionStore or SqliteStorage reload | Settles as in §6. Consumers of `sessionMetadata` reload with SessionStore ([ADR 002](../../adr/002-plugin-scope.md) D3), which SessionTitle §1 accepts. SessionStore reloads only with SqliteStorage, which has no dependencies | +| SessionStore or SqliteStorage reload | Settles as in §6. Consumers of `store` reload with SessionStore ([ADR 002](../../adr/002-plugin-scope.md) D3), which SessionTitle §1 accepts. SessionStore reloads only with SqliteStorage, which has no dependencies | ## 10. Timing and conflicts | Scenario | Outcome | | --- | --- | -| Two writes with the same expected revision | The first to commit wins; the other fails `conflict` and announces nothing | +| Two changes in flight | The owner serializes them; the second change sees the first title and decides; a refusal announces nothing | | Writes to different Sessions | Run one at a time by the one title writer; each commits in its own transaction | | `setTitle` and `session.delete` | The store's write transactions order them: a commit first is removed by the delete; a delete first makes the write `not_found` | | `setTitle` and `session.fork` | Independent: the fork copies no title | @@ -279,12 +280,12 @@ after the upgrade commits (S5a's log line, with the version the store came from) | Item | Rule | | --- | --- | -| Identity | `dyn HostDispatch` at `host_key("sessionMetadata")`, provided by SessionStore; `register_shared("sessionMetadata")` in App Server's service catalog, beside `sessions` and `settings` | -| Use | A C4 Session part declares `inject: ['sessionMetadata']` and calls `ctx.use('sessionMetadata')`, the path `settings` takes from a Session part ([settings-owner fixture](../../../runtime/fixtures/settings-owner.ts)). Types are in [npm/plugin.d.ts](../../../npm/plugin.d.ts) | +| Identity | `dyn HostDispatch` at `host_key("store")`, provided by SessionStore; `register_shared("store")` in App Server's service catalog, beside `sessions` and `settings` | +| Use | A C4 Session part declares `inject: ['store']` and calls `ctx.use('store')`, the path `settings` takes from a Session part ([settings-owner fixture](../../../runtime/fixtures/settings-owner.ts)). Types are in [npm/plugin.d.ts](../../../npm/plugin.d.ts) | | Modes | `read` and `setTitle` are both `async` | | Writer | The service carries no caller identity, as for `settings` (AGENTS.md rule 11). SessionTitle is the title's one writer by design ([SessionTitle §2](../plugins/SessionTitle.md#2-data-and-state)); other packages only read | | Reload | A consuming row reloads with SessionStore. SessionStore reloads only with SqliteStorage, so no directory part that never reloads is needed, unlike `sessions`, whose index reloads with Settings ([sessions D1](sessions-service.md#3-decisions)) | -| Missing provider | A daemon without a native store has no SessionStore, so a row that injects `sessionMetadata` stays Pending under the existing rules; native Sessions continue | +| Missing provider | A daemon without a native store has no SessionStore, so a row that injects `store` stays Pending under the existing rules; native Sessions continue | This uses only the existing catalog and `HostDispatch` mechanisms ([#4](https://github.com/arcships/dim/issues/4) named-service rules). S5b leaves nothing for C4 or S4 to add; S4's own named auxiliary binding is a separate @@ -300,7 +301,7 @@ SessionTitle gate. | [Session deletion and fork](session-deletion-and-fork.md) | §3.3 and §14 point to this design | | [Native storage format](native-storage-format.md) | The v16 decision, the table, the record example | | [ADR 001](../../adr/001-harness-foundation.md), [Timeline storage](../../architecture/rust-agent/timeline-storage.md) | Current format v16 | -| [TypeScript plugin authoring](../../typescript-plugin-authoring.md), [npm/plugin.d.ts](../../../npm/plugin.d.ts) | The `sessionMetadata` service and its types | +| [TypeScript plugin authoring](../../typescript-plugin-authoring.md), [npm/plugin.d.ts](../../../npm/plugin.d.ts) | The `store` service and its types | ## 14. Rule check @@ -312,7 +313,7 @@ SessionTitle gate. | §4 rule 4 (no business meaning in core) | SessionStore stores text and source without interpreting them; the notice is C6's generic record; Rpc copies the fields | | §4 rule 5 (batches) | Not applicable: no Timeline event | | §4 rule 6 (model context) | No model-visible effect | -| §4 rule 7 (public events and services) | SessionTitle uses the public `sessionMetadata` service; clients use the public notice and list fields | +| §4 rule 7 (public events and services) | SessionTitle uses the public `store` service; clients use the public notice and list fields | | §4 rule 8 (infrastructure unchanged) | Timeline, Dispatcher, event formats, assembly, rutis and the Session facade are unchanged. SessionTitle's requirement closes inside SessionStore, its owner, as the overview B.2 supplement records | | §4 rule 9 (only decision facts in the Timeline) | The title never enters the Timeline; clients see changes through the notice | | §1 (Capability and App Server boundary) | Inside the existing SessionStore plugin and Rpc; no new plugin | @@ -330,7 +331,7 @@ None. S5b uses C6's `notify`, the existing service catalog and `HostDispatch`, a 1. `setTitle` commits and returns the next revision; `read` returns it. Two v3 clients attached over IPC and WebSocket each receive exactly one `session.notice` per commit, in commit order, with `data` equal to the list's - title fields. A conflict and an unknown Session announce nothing. + title fields. A rejected change and an unknown Session announce nothing. 2. Concurrent writers: every commit is announced once, in increasing `titleRevision` order. 3. A clear (`null`) commits a revision with no title and announces nulls. 4. `read` and `setTitle` of a Session that was never created, or was deleted: `not_found`. @@ -344,7 +345,7 @@ None. S5b uses C6's `notify`, the existing service catalog and `HostDispatch`, a 9. An empty store is created at v16. Disposable v15 and v13 stores upgrade in place to the exact v16 schema with every business row unchanged and report the upgrade once; v16 schemas with a wrong marker, partial upgrades and older schemas are refused and preserved. -10. A TypeScript Session part running in Node injects `sessionMetadata`, reads and sets the title, and the attached +10. A TypeScript Session part running in Node injects `store`, reads and sets the title, and the attached client receives the notice (`node_` test, run by CI's Node step). 11. A `setTitle` request without `title` is rejected; the plugin SDK type check covers the call shapes. 12. Unload: writes admitted before SessionStore starts closing, one in its turn and one waiting for it, commit and @@ -352,7 +353,7 @@ None. S5b uses C6's `notify`, the existing service catalog and `HostDispatch`, a is not in the store after a restart (§6). Tests: items 1 to 8, 10 and 12 are in [titles.rs](../../../crates/dim-app-server/tests/transport_flow/titles.rs), through -the `sessionMetadata` service as a Session part injects it and the [session-metadata +the `store` service as a Session part injects it and the [session-metadata fixture](../../../runtime/fixtures/session-metadata.ts); items 6 and 12 hold the write with `storage::testing::hold_title_write` (feature `testing`); item 9 is `a_v15_store_upgrades_in_place_once`, `a_v13_store_upgrades_in_place_once`, `the_daemon_reports_a_v13_upgrade_on_stderr_once` and the refusal cases in @@ -370,11 +371,11 @@ fixture](../../../runtime/fixtures/session-metadata.ts); items 6 and 12 hold the | D5 | Notice `data` is `{title, titleSource, titleRevision}` | A.2's `{sessionId, title, titleSource, revision}` | The channel already names the Session (C6 D4); one field set for list entries and notices lets clients merge without mapping | | D6 | `titleRevision` in v3 list entries | `title` and `titleSource` only | Without it a client cannot order a list reply against a notice (§8) | | D7 | List fields for protocol v3 only | All protocol versions | v1 and v2 are frozen and receive no title notices | -| D8 | Service `sessionMetadata` with `read` and `setTitle`; the Rust binding uses `read` and `set_title` | A.2's method name `metadata` | `sessionMetadata.metadata` repeats itself; `read` matches `settings.read` | -| D9 | Errors `conflict`, `not_found`, `storage` as data; malformed calls are bridge errors | A `rejected` code as in `sessions` | The three codes are the write's outcomes; a malformed call is a programming error, as in `settings` | +| D8 | Service `store` with `title` and `setTitle(id, change)`; the Rust binding uses `title` and `set_title` | A.2's method name `metadata` | `store.title` reads the title; the change carries the decision | +| D9 | Errors `rejected`, `not_found`, `closed`, `storage` as data; malformed calls are bridge errors | A `conflict` code | The change decides the manual rule, so there is no revision conflict | | D10 | `not_found` for a Session the store does not hold | `session_closed` | Maintainer decision; it is SessionStore's vocabulary, and SessionTitle maps it to `session_not_found` | | D11 | SessionStore stores text as given | Validating length and characters | SessionTitle owns the title rules and validates them; checking again would duplicate the contract | -| D12 | SessionStore itself provides `sessionMetadata` | A part that never reloads | SessionStore reloads only with SqliteStorage (§12) | +| D12 | SessionStore itself provides `store` | A part that never reloads | SessionStore reloads only with SqliteStorage (§12) | | D13 | The same text written again commits a new revision | Treating it as a no-op | SessionTitle Appendix B expects a duplicate rename to rewrite; a no-op would need its own reply | | D14 | Admission at the call; unload stops admission, then waits for every admitted write | Admitting a write when it takes its turn, and failing the writes still waiting at unload (the first implementation) | That left a handed-over write without a definite admission: whether it ran depended on whether its task reached the title writer before the disposer did, and a call that arrived during unload was neither refused nor admitted until the write in progress ended. Admitting at the call makes both the handover and the refusal immediate. Titles are written rarely, so waiting for the admitted ones is short. Session files' puts are admitted the same way | @@ -394,14 +395,16 @@ pub struct SessionMetadata { pub revision: u64, pub title: Option<Title> } #[derive(Clone, Default, Serialize)] #[serde(rename_all = "camelCase")] pub struct TitleFields { pub title: Option<String>, pub title_source: Option<TitleSource>, pub title_revision: u64 } -pub enum MetadataError { Conflict, NotFound, Storage(String) } +#[serde(tag = "code", rename_all = "snake_case")] +pub enum StoreError { Rejected { reason: String, message: String }, NotFound { message: String }, Closed, Storage { message: String } } -impl SessionMetadataService { - pub async fn read(&self, session_id: &str) -> Result<SessionMetadata, MetadataError>; - /// Admits and starts the write when called, or fails `Storage` once +impl SessionStore { + pub async fn title(&self, id: &str) -> Result<SessionMetadata, StoreError>; + /// Admits and starts the write when called, or fails `Closed` once /// SessionStore is closing: the call is the handover. Dropping the - /// returned future loses only the reply. - pub fn set_title(&self, session_id: &str, expected_revision: u64, title: Option<Title>) - -> impl Future<Output = Result<u64, MetadataError>> + Send + 'static; + /// returned future loses only the reply; the hand-written method table + /// calls this plain fn eagerly, so a wire caller that drops the reply still commits. + pub fn set_title(&self, id: &str, change: ChangeFn) + -> impl Future<Output = Result<u64, StoreError>> + Send + 'static; } ``` diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 721560de84..319347333a 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -9,7 +9,7 @@ directly. The rutis binding dispatches its data arguments and returns its result | --- | --- | | `hostPlatform` | Exec and Shell use the task and PTY operations in [execHost §3](../resource-faces.md#3-exechost). Hooks calls configured(request); OCR calls confined(request). Both return the result of that call. Process handles remain with the platform. | | `fileStorage`, `mentionIndex` | File tools and workspace completion use [fsHost §4](../resource-faces.md#4-fshost), including mentions. Storage clients use the owner's file and lease operations. An opened reader uses openRead/readAt/closeRead. | -| `sessionStore` | Session repository, metadata, attachments, Timeline and worktree associations use store, store.readMetadata/setTitle, sessionFiles, timelineStore and store.associateWorktree respectively. Session construction binds the existing Session-scoped timelineStore. Path import and fileId reads use the [Session files contract](../appserver/session-files.md). | +| `sessionStore` | The Session repository, title, worktree-record and association operations use the [SessionStore contract](../plugins/SessionStore.md); files use [SessionFiles](../plugins/SessionFiles.md); the Session-scoped `timelineStore` is the same owner's Timeline face, bound by SessionScope. This row keeps only the pointer. | | `pluginFiles` | Scheduler uses pluginFiles.open(). EventHub retains a caller-managed scope through settlement of admitted publishes across row restarts. Both use scope.withLock and lease.read/replace for the same atomic text update. Scope.list/remove and lease.readBytes/replaceBytes have their existing contracts. | | `settingsService` | Declared sources use settings.register/read/update/projects. PluginManager uses the owner-write form for CAS edits and applies its existing writeOnly redaction. SettingsMethods retains the local client-write path. [Settings contract](../appserver/settings-service.md#42-service-settings-owner-path). | | Permission, PromptSources, Skills catalog/management and execution/shell Settings → resource owners | Use the node facts and file operations in the [resource caller matrix](../resource-faces.md#6-provider-binding-and-the-owners-that-use-each-operation), including execHost.info and fsHost resolution and reads. | diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md index f008a1163b..818292f0d4 100644 --- a/docs/design/plugins/ManagedWorktrees.md +++ b/docs/design/plugins/ManagedWorktrees.md @@ -68,14 +68,14 @@ for candidate in confirmed(&preview) { | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `create` | Allocate a task id and make a Git worktree and branch for a Session creation | `{source, base?, branch?}` | `{taskId, repository, root, subtree, branch, base}` | Between Git calls and before the branch is created; a cancelled creation removes its empty task directory | `unavailable`, `invalid`, `branch_exists`, `git`, `interrupted` | -| `discard` | Settle a created worktree that the Session creation did not adopt | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `in_use`, `git` | +| `discard` | Settle a created worktree that the Session creation did not adopt | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `in_use`, `git`, `closed`, `storage` | | `list` | Managed worktrees with Git state and Session use | `{}` | `{worktrees}` | While the views are built | `unavailable`, `closed`, `storage` | | `pruneSelection` | Candidates a prune would delete and the kept ones with reasons | `{olderThanMs?, keep?, force}` | `{candidates, kept}` | While the selection is built | `invalid`, `unavailable`, `closed`, `storage` | | `remove` | Remove one managed worktree, or an unregistered directory, with its record | `{taskId, force}` | `{removed}` | Before the Git removal; after it starts the removal completes or reports `git` | `invalid`, `not_found`, `in_use`, `git`, `closed`, `storage` | `create` returns a value; `discard` and `remove` take the task id. No object crosses. The preparation table is the owner's generation state: a reload drops it, and `discard` for a task id the generation did not create answers `unknown_preparation`; the directory is then an unregistered directory that `remove` handles. -`remove` composes the store's `removeWorktree`: the store checks the record, the associations and the stored workspaces under its exclusion and calls this owner's Git removal as a callback; the record is deleted when the callback succeeds and kept when it refuses or fails. No claim id or lock crosses. `force` overrides only the content check; the Git removal receives `--force` only then. +`remove` composes the store's removal under its exclusion: `removeWorktree` for a recorded directory and `removeUnregisteredDirectory` for a directory no record names. The store checks the associations and the stored workspaces and calls this owner's Git and filesystem removal as a callback; the record is deleted when the callback succeeds and kept when it refuses or fails. No claim id or lock crosses. `force` overrides only the content check; the Git removal receives `--force` only then. ### Errors @@ -90,6 +90,7 @@ for candidate in confirmed(&preview) { | `interrupted` | The call was stopped; a creation's partial state is cleaned, a removal is retried | | `unknown_preparation` | The preparation ended with the generation; the directory is unregistered and `remove` handles it | | `storage` | A record read or write failed; the caller reports the failure and keeps the record | +| `closed` | This generation is unloading; call the replacement generation | ### Flows @@ -99,16 +100,16 @@ for candidate in confirmed(&preview) { | `discard` | Look up the preparation, `store.removeWorktree(directory, remove)`, delete the branch; the record may be absent | No cancellation; the cleanup is the owner's | The preparation ends with the row; the directory is unregistered | The table drops with the generation; the directory stays unregistered | Directory and branch by ManagedWorktrees; record by the store | | `list` | Read the records and associations, join Git state per directory, add unregistered directories | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | | `pruneSelection` | `list`, then apply age, keep and force rules per candidate | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | -| `remove` | Resolve the record or the unregistered directory, then `store.removeWorktree(directory, remove)`: the store checks and holds the exclusion, this owner removes the Git worktree, the store deletes or keeps the record | Before the Git removal; a started removal completes or reports `git`; the store keeps the record | The callback ends with the row; the store keeps the record | An in-flight removal ends; the store keeps the record unless the Git step succeeded | Directory by ManagedWorktrees; record by the store | +| `remove` | Resolve the record or the unregistered directory; a recorded one goes through `store.removeWorktree(directory, remove)`, an unregistered one through `store.removeUnregisteredDirectory(root, remove)`: the store checks and holds the exclusion, this owner removes the Git worktree or the directory, the store deletes or keeps the record | Before the Git removal; a started removal completes or reports `git`; the store keeps the record | The callback ends with the row; the store keeps the record | An in-flight removal ends; the store keeps the record unless the Git step succeeded | Directory by ManagedWorktrees; record by the store | A process death between `create` and `store.create` leaves an unregistered directory; `list` reports it and `remove` deletes it after the operator names the task id. A process death during the removal step leaves the record; the next `list` reports the directory as missing or no longer registered, and `remove` cleans the record. ## Exceptions with reasons -- A branch is kept when `remove` deletes a worktree: committed content must not disappear with the directory. -- `discard` is not cancellable: a cancelled Session creation still has to settle what the owner made. +- A branch is kept when `remove` deletes an adopted worktree: committed content must not disappear with the directory. Only the default `dim/<taskId>` branch of a never-adopted worktree is deleted with the directory. +- `discard` is not cancellable: a cancelled Session creation still has to settle what the owner made. A store refusal (`closed` or `storage`) leaves the directory and branch in place; the caller reports it, and the preparation stays for a retry on the replacement generation. - Unregistered directories are never pruned: the owner has no record to age, so only an explicit `remove` by task id deletes them. -- A branch outlives a creation that was never adopted: a process death between `create` and `store.create`, or a `discard` that ended before the branch deletion, leaves the branch. `remove` on an unregistered directory deletes the directory only; the operator deletes the leftover branch with Git, and `list` names the task id the branch was made for. +- A branch outlives a creation that was never adopted: a process death between `create` and `store.create` leaves the branch. `remove` on an unregistered directory deletes the directory and, when the owner created the default `dim/<taskId>` branch for a worktree that was never adopted, deletes that branch too; an explicit branch from the request is retained and reported, so a name the operator chose is never deleted. - Git is the owner's process resource: the owner starts each call, bounds it (10s read, 30s write) and reaps it on cancellation. ## Client-visible changes @@ -117,7 +118,7 @@ None. `worktree.list`, `worktree.remove` and `worktree.prune` keep their request ## Supersedes -- [Managed worktrees](../worktree-management.md) §3–§5: creation, the directory records and associations, and the list/remove/prune composition under the store's removal operation. +- [Managed worktrees](../worktree-management.md) §5: the list/remove/prune composition under the store's removal operations and the branch rule for a never-adopted worktree. §3 and §4 remain the source for creation and the directory records. ## Verification @@ -213,13 +214,30 @@ pub struct RemoveWorktreeReply { pub removed: bool, } -/// The wire error: `{code, message}`, with `code` one of the kinds in the error table. -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -#[error("{code}: {message}")] -pub struct WorktreeError { - pub code: String, - pub message: String, +/// The wire error: one variant per code; `code` is the variant name in snake_case. +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum WorktreeError { + #[error("{message}")] + Unavailable { message: String }, + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + BranchExists { message: String }, + #[error("{message}")] + NotFound { message: String }, + #[error("{message}")] + InUse { message: String }, + #[error("{message}")] + Git { message: String }, + #[error("{message}")] + Interrupted { message: String }, + #[error("{message}")] + UnknownPreparation { message: String }, + #[error("{message}")] + Closed { message: String }, + #[error("{message}")] + Storage { message: String }, } impl PublicService for ManagedWorktrees {} diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md index c7882d0626..3f3d738966 100644 --- a/docs/design/plugins/SessionFiles.md +++ b/docs/design/plugins/SessionFiles.md @@ -61,7 +61,7 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? ### Dependencies -`fsHost` for the owner's directory, file creation, atomic replacement, import, listing and removal; the operations used are the ones in [FileStorage's contract](https://github.com/arcships/dim/pull/2080). The engine's file-ownership rows are private to the storage crate and are not a service. The owner does not depend on `store`: the store depends on this owner when a delete releases files. +`fsHost` for file creation, atomic replacement, import, page reads, listing and removal; the operations used are the ones in [FileStorage's contract](https://github.com/arcships/dim/pull/2080). The owner computes its own directory (`<db>.session-files`) from the database path it holds and passes absolute paths; FileStorage's root set must cover the native store directory, which the host registers. The engine's file-ownership rows are private to the storage crate and are not a service. The owner does not depend on `store`: the store depends on this owner when a delete releases files. ### Operations @@ -69,11 +69,11 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | --- | --- | --- | --- | --- | --- | | `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, content}`, `content` is base64 | `{fileId, path, bytes}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, path, bytes}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | -| `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, content}`, `content` is base64 | `{fileId, path, bytes}` | Before the replacement; the old bytes stay | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, content}`, `content` is base64 | `{fileId, path, bytes}` | Before the replacement; the old bytes stay | `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `read` | One page of a Session file, at most 64 KiB | `{sessionId, fileId, offset}` | `{data, eof}`, `data` is base64 and `eof` is true exactly when it is empty | While the page is read; nothing changes | `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `register` | Record a caller-owned output path for the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `storage` | | `owns` | Whether a path or file id belongs to the Session | `{sessionId, path}` | `{owned}` | While the path is resolved | `node_unavailable`, `cancelled`, `closed`, `storage` | -| `remove` | Remove one Session file and its ownership row; an absent or foreign file answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal | `storage` | +| `remove` | Remove one Session file and its ownership row; an absent or foreign file answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal | `node_unavailable`, `storage` | | `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `storage` | `path` is absolute on the Session's resource node; `bytes` is the stored length. `offset` at or beyond the end answers an empty `data` with `eof`. A `fileId` outside the Session, or a name that is not one component, is `not_found` for reads and writes and `invalid` for a name `put` or `import` receives. @@ -164,7 +164,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -1. **FileStorage (#2016): the operations this owner calls.** `root_path`, `create_directory`, `write` with the read-only permission, `import` with `max_bytes` and the read-only permission, `list`, `remove`, `read`. [FileStorage's contract](https://github.com/arcships/dim/pull/2080) defines all of them; this contract raises no new need. +1. **FileStorage (#2016): the operations this owner calls.** `read` with `{offset, length}`, `write` with its `source` and `privateReadOnly`, `import` with `max_bytes` and `privateReadOnly`, `create_directory`, `list` and `remove` exist in [FileStorage's contract](https://github.com/arcships/dim/pull/2080) at head `e951536ec`. `root_path` left that face: the owner computes `<db>.session-files` from its database path, so the only need is that the host's root set covers the native store directory; a comment on #2016 states it. 2. **Service type placement (#2015): a process owner in the app server.** The owner type is in `dim-app-server`, where the engine and the rows are; callers in plugin crates cannot depend on the app server. The request and reply types are plain data in `dim-agent-capabilities::host`, and callers outside the crate call the operations by the `sessionFiles` name. If the maintainers decide every process face must be annotated on a type plugin crates can name, the type moves to a shared crate; a comment on #2015 states the requirement. ## Binding appendix @@ -177,119 +177,24 @@ use dim_agent_runtime::PublicService; use rutis::Ctx; use std::sync::Arc; -/// A caller's own refusal or failure; the wire carries its `code` and `message` unchanged. -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, thiserror::Error)] -#[error("{code}: {message}")] -pub struct FileRejected { - pub code: String, - pub message: String, -} - -impl From<rutis::host::CallError> for FileRejected { - fn from(error: rutis::host::CallError) -> Self { - Self { - code: error.code().unwrap_or_else(|| "rejected".into()), - message: error.message().to_owned(), - } - } -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Put { - pub session_id: String, - pub name: String, - /// base64 - pub content: String, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Import { - pub session_id: String, - pub name: String, - pub source: String, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct WriteFile { - pub session_id: String, - pub file_id: String, - /// base64 - pub content: String, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct ReadFile { - pub session_id: String, - pub file_id: String, - pub offset: u64, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct RemoveFile { - pub session_id: String, - pub file_id: String, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Register { - pub session_id: String, - pub path: String, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Owns { - pub session_id: String, - pub path: String, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct OfSession { - pub session_id: String, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct StoredFile { - pub file_id: String, - pub path: String, - pub bytes: u64, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Page { - /// base64, at most 64 KiB - pub data: String, - pub eof: bool, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Owned { - pub owned: bool, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Paths { - pub paths: Vec<String>, -} - -/// The wire error: `{code, message}`. -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -#[error("{code}: {message}")] -pub struct SessionFileError { - pub code: String, - pub message: String, +/// The wire error: one variant per code; `code` is the variant name in snake_case. +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum SessionFileError { + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + TooLarge { message: String }, + #[error("{message}")] + NotFound { message: String }, + #[error("{message}")] + NodeUnavailable { message: String }, + #[error("the call was cancelled")] + Cancelled, + #[error("the file service is unloading")] + Closed, + #[error("{message}")] + Storage { message: String }, } impl PublicService for SessionFiles {} diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 0b00ff768b..032db4db00 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -2,7 +2,7 @@ Scope: process. Issue: #2018. -SessionStore owns the stored Session: its rows, its grants, its reply language, its title revision, its worktree records, the exclusion that keeps those records consistent with Session creation, and the Timeline storage engine those rows are read through. This document is the owner's target contract. The current implementation is described in [Session rows §5.2](../resource-faces.md#52-session-rows) and [Native storage format](../appserver/native-storage-format.md). The Session-scoped `timelineStore` face carries this owner's Timeline operations; SessionScope binds that face at the Session instance ([#2093](https://github.com/arcships/dim/pull/2093)). +SessionStore owns the stored Session: its rows, its grants, its reply language, its title revision, its worktree records, the exclusion that keeps those records consistent with Session creation, and the Timeline storage engine those rows are read through. This document is the owner's target contract. The current implementation is described in [Native storage format](../appserver/native-storage-format.md). The Session-scoped `timelineStore` face carries this owner's Timeline operations; SessionScope binds that face at the Session instance ([#2093](https://github.com/arcships/dim/pull/2093)). ## Use and scope: responsibility split @@ -45,6 +45,7 @@ Callers keep: | Record a verified worktree directory and the Session's subtree | No: the directory record, the association and the last-use time are one commit | `associateWorktree` | | List recorded worktree directories or their Session associations, or learn which stored Sessions have a workspace under a root | No: the caller has no row access | `worktrees`, `worktreeUsages`, `sessionsUnder` | | Remove one recorded worktree together with its directory | No: the association and workspace checks, the caller's own removal step and the record deletion must not interleave with a Session creation that would point into the removed root | `removeWorktree` with a removal callback | +| Remove an unregistered directory left by a failed creation | No: the stored-workspace check and the exclusion are the store's, and the directory has no record | `removeUnregisteredDirectory` with a removal callback | An operation exists only where its row says No. @@ -124,6 +125,7 @@ Every operation takes one request object and answers one reply object. Writes ar | `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `closed`, `storage` | | `sessionsUnder` | Stored Sessions whose workspace is a root or lies under it | `{root}` | `{sessionIds}` | None | `invalid`, `closed`, `storage` | | `removeWorktree` | Remove one recorded directory under the Session exclusion, with the caller's own removal step | `{repository, root}` + `remove` | `{removed}` | The caller's step ends; the record stays | `invalid`, `in_use`, `rejected`, `closed`, `storage` | +| `removeUnregisteredDirectory` | Remove a directory no record names, under the Session exclusion, with the caller's own removal step | `{root}` + `remove` | `{removed}` | The caller's step runs to its end; no record is involved | `invalid`, `in_use`, `rejected`, `closed`, `storage` | `worktree` in `create` and `associateWorktree` is `{repository, root, subtree}`: absolute UTF-8 paths, `subtree` inside `root`. The caller passes paths it already resolved; the owner re-checks that each is absolute, UTF-8 and, for an association, that the root still is a directory. @@ -140,7 +142,7 @@ Every operation takes one request object and answers one reply object. Writes ar | `closed` | This generation is unloading; call the replacement generation | | `storage` | The store failed; the caller reports the failure and keeps the Session or worktree for a retry | -When a change, text or removal callback refuses, the operation carries the callback's own `code` and `message` unchanged in `rejected`. +When a change, text or removal callback refuses, the operation answers `rejected` with the callback's own code in `reason` and its message unchanged; the wire code stays `rejected` so the callback's code cannot be mistaken for one of this owner's codes. ### Flows @@ -154,13 +156,14 @@ When a change, text or removal callback refuses, the operation carries the callb | `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | | `setTitle` | Admit the write behind earlier admitted writes, read the current title, call `change` under the serialization, write the returned title as revision + 1, commit, announce, answer the revision | Dropping the reply never cancels the admitted write; a change that refuses leaves the title unchanged | The change callback is revoked before it returns; the admitted write fails and the title stays | Close stops admission, waits for every admitted write | SessionStore; the change computes only | | `removeWorktree` | Validate the paths, take the exclusion, check associations and stored workspaces, call `remove`, delete the record on success, release | The removal step refuses with its own code (for example `cancelled`); the record stays | The callback ends; the record stays; the exclusion releases | New calls are refused `closed`; an in-flight removal ends, and the record stays unless the step succeeded | Directory by the caller; record by SessionStore | +| `removeUnregisteredDirectory` | Validate the root, take the exclusion, check stored workspaces under it, call `remove`, release | The removal step refuses with its own code; nothing changes | The callback ends; the exclusion releases | New calls are refused `closed`; an in-flight removal ends | Directory by the caller; exclusion by SessionStore | ## Exceptions with reasons - `create` takes the caller's already-validated configuration; `fork` reads the source text itself and calls the caller's text step under the fork's exclusion, so the lifecycle owner's `initialTitle` decision cannot race the copy and the copied bytes stay the source's text. - `delete` does not close the Session, remove its Agent admission slot or remove the worktree: closing is Agents', and a managed worktree is removed by ManagedWorktrees under `removeWorktree`. - `setTitle` runs the caller's change under the owner's serialization: the change only computes the next title from the current title and revision, and returns its own refusal; the reply may be lost, so the caller re-reads rather than assumes failure. -- `removeWorktree` runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. +- `removeWorktree` runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. The exclusion has no time bound: a recursive forced deletion of an unregistered directory may run to its end, and `removeUnregisteredDirectory` uses the same exclusion for a directory no record names. - `owner` answers the Agent id for a delete notice; the Agent directory's own records are not returned here. ## Client-visible changes @@ -169,7 +172,7 @@ None. The client methods (`session.rename`, `sessions.list`, `session.delete`, ` ## Supersedes -- [Resource faces §5 and §5.2](../resource-faces.md): the `store`/`timelineStore` split, the Session row operations, the Rust `Store` binding and the metadata and association rows. +- [Resource faces §5, §5.1 and §5.2](../resource-faces.md): the `store`/`timelineStore` split, the admission and drain steps, the Session row operations, the Rust `Store` binding and the metadata and association rows. - [Service faces §3.3 and §3.4](../service-faces.md): the `sessionStore` row and the `store` and `timelineStore` rows. - [Resource owner operations](../contracts/resource-owner-operations.md): the `SessionStore → sqliteStorage` rows and the Session row paragraphs. - [Session title metadata](../appserver/session-title-metadata.md): the `readMetadata` and `setTitle` shapes. @@ -339,10 +342,20 @@ pub struct StoreRejected { impl From<rutis::host::CallError> for StoreRejected { fn from(error: rutis::host::CallError) -> Self { - Self { - code: error.code().unwrap_or_else(|| "rejected".into()), - message: error.message().to_owned(), - } + let (message, raw) = error.into_raw(); + let code = raw + .as_deref() + .and_then(|raw| { + raw.downcast_ref::<StoreRejected>() + .map(|rejected| rejected.code.as_str()) + .or_else(|| { + raw.downcast_ref::<rutis_bridge::session::Error>() + .and_then(|error| error.code()) + }) + }) + .unwrap_or("rejected") + .to_owned(); + Self { code, message } } } @@ -366,17 +379,43 @@ pub struct DirectoryRecord { pub last_used_at_ms: Option<i64>, } -/// The wire error: `{code, message}`, with `code` one of the kinds in the error table. -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -#[error("{code}: {message}")] -pub struct StoreError { - pub code: String, - pub message: String, +/// The wire error: one variant per code; `code` is the variant name in snake_case. +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum StoreError { + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + WorkspaceMissing { message: String }, + #[error("{message}")] + NotFound { message: String }, + #[error("{message}")] + InUse { message: String }, + #[error("{reason}: {message}")] + Rejected { reason: String, message: String }, + #[error("the call was cancelled")] + Cancelled, + #[error("the store is unloading")] + Closed, + #[error("{message}")] + Storage { message: String }, } impl PublicService for SessionStore {} +impl SessionStore { + /// Admits the write under the owner's serialization and returns the wait future; dropping it never cancels the admitted write. + /// `setTitle` stays on the hand-written method table: `invoke` calls this function eagerly and returns the wait, so a wire caller that drops the reply still commits the write. + pub fn set_title( + &self, + caller: &Ctx, + request: SetTitle, + change: ChangeFn, + ) -> impl Future<Output = Result<TitleReply, StoreError>> + Send + 'static { + // admits the write, starts the owner's task, returns the wait + } +} + #[rutis::service(name = "store")] impl SessionStore { pub async fn create( @@ -407,15 +446,6 @@ impl SessionStore { // ... } - /// Admits the write under the owner's serialization and returns the wait future; dropping it never cancels the admitted write. - pub fn set_title( - &self, - caller: &Ctx, - request: SetTitle, - change: ChangeFn, - ) -> impl Future<Output = Result<TitleReply, StoreError>> + Send + 'static { - // admits the write, starts the owner's task, returns the wait - } pub async fn remove_worktree( &self, diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index a2cc2bac11..3cd8387e1f 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -69,10 +69,10 @@ and registers the Session part; each Session mounts a copy. The part injects `sessionMethods` and registers `session.rename` with it from `apply`; it provides no service. `apply` reads the Session identity and creation configuration and registers observation/cleanup; it does not start an asynchronous initialization job. Its creation configuration is immutable. -The plugin depends on the existing public Rust Settings and sessionMetadata bindings; it does not expose or alter their implementations. Plugin behavior and cross-plugin title flows live in this crate's tests and use the public client and host APIs. App Server tests have no dependency on this crate and install no title plugin implicitly. +The plugin depends on the existing public Rust Settings and `store` bindings; it does not expose or alter their implementations. Plugin behavior and cross-plugin title flows live in this crate's tests and use the public client and host APIs. App Server tests have no dependency on this crate and install no title plugin implicitly. The part injects its required dependencies: the process services -`settings`, `sessionMetadata` and `auxiliaryModel`, and the Session services branch queries, `sessionIdentity`, +`settings`, `store` and `auxiliaryModel`, and the Session services branch queries, `sessionIdentity`, `sessionConfig`, `sessionLifecycle` and `sessionMethods`. The optional `sessionTitleGenerator` is read by name when used, without injection or a readiness gate, under the [required/optional binding contract](../rutis-usage.md#3-services-by-name). @@ -125,7 +125,7 @@ flowchart LR | Part | Scope | Depends on | Provides | | --- | --- | --- | --- | | `session-title` | Process | Settings and part registry | Registers the Settings source and Session part | -| `SessionTitle` | Session | Session services `sessionIdentity`, `sessionConfig`, `sessionLifecycle` and `sessionMethods`; Session branch queries; process Settings, title metadata `sessionMetadata` (S5b) and required `auxiliaryModel` (a profile without an owner of model selection keeps the row Pending); optional `sessionTitleGenerator` read at use | Registers session.rename with sessionMethods | +| `SessionTitle` | Session | Session services `sessionIdentity`, `sessionConfig`, `sessionLifecycle` and `sessionMethods`; Session branch queries; process Settings, the title operations `store` and required `auxiliaryModel` (a profile without an owner of model selection keeps the row Pending); optional `sessionTitleGenerator` read at use | Registers session.rename with sessionMethods | Dependencies stay in the Session or enclosing process. Session observation, branch queries and Settings supply observation, field reads and configuration; S5b supplies title metadata and C6 the notices; the profile's model-selection owner supplies the named auxiliary operation. The plugin's row registers its source in its `apply`. Real provider reloads cancel the row's work (ADR 002 D3); SessionStore index reload does not. Business data changes never reload the plugin (D4). @@ -360,7 +360,7 @@ post-commit title notices. SessionTitle consumes these delivered contracts. | Effect on sequence, batch, interrupt, reload | No sequence number and no batch; not replayed: a client that resubscribes reads current state through the owner's query (`session.summaries`); interrupts do not apply; a reload of the emitter only stops notices. | | Owner and issue | Runtime C6 [#49](https://github.com/arcships/dim/issues/49), implemented in [#85](https://github.com/arcships/dim/pull/85): the record, `session_broadcast::notify` and Rpc's `session.notice` ([Session broadcast notices](../appserver/session-notices.md)). SessionStore emits the title notice ([S5b](../appserver/session-title-metadata.md), the supplement in [overview Appendix B.2](../overview.md#b2-app-server-process-plugins)). | -**#4: None.** Observation uses the Session services and the Session channel; branch queries are Session services; Settings, `sessionMetadata` and the auxiliary model are process services. SessionTitle injects no branch service. +**#4: None.** Observation uses the Session services and the Session channel; branch queries are Session services; Settings, `store` and the auxiliary model are process services. SessionTitle injects no branch service. **The model-selection owner (S4): the named `auxiliaryModel` binding.** Provider (product) and ConfiguredModels (model-config) bind their existing `AuxiliaryModel` operation for C4 injection ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)). A profile without such an owner keeps SessionTitle's row Pending through its ordinary required dependency. No core mechanism is needed. @@ -382,7 +382,7 @@ Registered with `sessionMethods` (Session, namespace `session.rename`) with one | Service | Method | Kind | Request | Reply and errors | | --- | --- | --- | --- | --- | -| SessionStore `sessionMetadata` (S5b) | `read` | async | `{sessionId}` | `{revision, title: {text, source: "auto" \| "manual"} \| null}`; errors `not_found`, `storage` ([S5b §4](../appserver/session-title-metadata.md#4-operations)) | +| SessionStore `store` | `title` | async | `{id}` | `{revision, title: {text, source: "auto" \| "manual"} \| null}`; errors `not_found`, `closed`, `storage` ([SessionStore](SessionStore.md)) | | SessionStore `store` | `setTitle` | async | `{sessionId}` plus a change that receives `{revision, title}` and returns the next title or `null` | `{revision}`; errors `rejected`, `not_found`, `storage`. The call is the handover; after a commit SessionStore emits the title notice | | SessionStore (S5b) | title notice | Session broadcast notice (C6 record, §9) | — | `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}` on the Session's broadcast channel; no sequence number, not replayed | | `AuxiliaryModel` (the profile's model-selection owner) | `complete` | async | `{model: {providerId, modelId}, request: {system, messages: [{role: "user", content: text}]}}`, optional `cancelled: () => Promise<void>` ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)) | `{text, stopReason, usage}`; rejects with the existing error code/message. Resolve the cancellation reference on timeout or closing and await the original call's settlement | @@ -410,7 +410,7 @@ omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remain | Listen | The Session's copy of the part listens to its Session's `session/{sessionId}` from `apply`, filters main input/applied, registers an owned task and returns; `sessionLifecycle.closing()` or copy cleanup ends owned work | | Eligibility | C4 creation snapshot: `interactive !== false && collaborationRole === "leader"` for generation; native omission means true. A requested initial title (`initialTitle`, §3.4) is written for interactive and non-interactive Sessions alike: it needs no model, and it is the caller's own text | | Trigger | On `input/applied` at `N`: skip if not eligible, disabled, in flight or failed attempts ≥ 3 (A5); otherwise start a generation task owned by the plugin's lifetime | -| Check | `sessionMetadata.read({sessionId})`: skip if any title exists; keep revision `r` | +| Check | `store.title({id})`: the change decides from the current title and revision; a `rejected` change discards | | Read | The four field queries in §0.1 share published T >= N. No adopted eligible input/text means no title (A8/A10). | | Generate | Route and fall back under §3.3 within the shared 30 s budget (A4); normalize the first line, remove quotes and trailing punctuation, collapse whitespace, cut at `maxLength`, trim again | | Write | `setTitle({sessionId}, change)` where the change returns the generated title or `null`; a `rejected` change discards | @@ -427,7 +427,7 @@ omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remain | First input withdrawn (`session.input.withdraw`) before it is applied | input < withdraw < `input/deleted` | Never applied: no generation, text never sent; the first applied eligible input triggers | SessionTitle | | First user input carries only images | — | No automatic title (A8) | SessionTitle | | Rename before the check | rename < check | Title present: skip | SessionTitle | -| Rename during generation | check (r) < rename (r+1) < write | `conflict`: automatic title discarded | SessionStore revision | +| Rename during generation | check < rename < write | the change sees the rename and refuses: automatic title discarded | SessionStore serialization | | Concurrent renames | revision order | Last committed rename wins | SessionStore | | Duplicate `session.rename` | — | Rewrites the same text | SessionTitle | | Steer/Queue/Append inputs after the first | — | Never in the excerpt | SessionTitle | @@ -447,7 +447,7 @@ omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remain | --- | --- | | Model error, timeout, empty output, unavailable policy | Input-excerpt fallback (§3.3); cancellation never falls back | | Settings read fails | Automatic: no write, diagnostic, failure counted; rename: `storage_failed`. No fallback document | -| `setTitle` `conflict` on automatic write | Discarded (diagnostic) | +| `setTitle` `rejected` on automatic write | Discarded (diagnostic) | | `setTitle` `storage` | Automatic: failure counted; rename: `storage_failed` | | Unknown Session on rename | `session_not_found` | | SessionTitle reloading | Before handover: service_reloading, no rename. After handover/lost reply: read metadata; do not infer no commit or repeat the write | @@ -512,10 +512,10 @@ auxiliary binding use the owner contracts in §0. The optional service contract | Generation task | Spawned under `ctx.effect` | ```rust -// SessionMetadataService (S5b; named service `sessionMetadata`) +// the `store` face; `setTitle` stays on the hand-written method table async fn read(&self, session_id: &str) -> Result<SessionMetadata, MetadataError>; -fn set_title(&self, session_id: &str, expected_revision: u64, title: Option<Title>) - -> impl Future<Output = Result<u64, MetadataError>>; // Conflict | NotFound | Storage; the call is the handover +fn set_title(&self, id: &str, change: ChangeFn) + -> impl Future<Output = Result<u64, StoreError>>; // Rejected | NotFound | Closed | Storage; the call is the handover pub struct SessionMetadata { pub revision: u64, pub title: Option<Title> } pub struct Title { pub text: String, pub source: TitleSource } // Auto | Manual // AuxiliaryModel (the profile's model-selection owner) diff --git a/docs/design/plugins/SqliteStorage.md b/docs/design/plugins/SqliteStorage.md index 37b0414f21..b5919b5ec0 100644 --- a/docs/design/plugins/SqliteStorage.md +++ b/docs/design/plugins/SqliteStorage.md @@ -2,13 +2,13 @@ Scope: process. Issue: #2018. -SqliteStorage owns the database file, the lease that admits one process to it, the format version and its upgrades, the writer and the read connections, and the transactions the data owners' rows are read and written in. This document is the owner's target contract. The current implementation is described in [Native storage format](../appserver/native-storage-format.md) and [Resource owner operations](../contracts/resource-owner-operations.md). +SqliteStorage owns the database file, the lease that admits one process to it, the format version and its upgrades, the writer and the read connections, and the transactions the data owners' rows are read and written in. This document is the owner's target contract. The current implementation is described in [Native storage format](../appserver/native-storage-format.md). ## Use and scope: responsibility split SqliteStorage owns: -- **The file and its lease.** `<db>` and `<db>.lock`; one process opens the store, upgrades it and holds the lock until close; an offline tool takes the same lock. +- **The file and its lease.** `<db>` and `<db>.lock`; one process opens the store, upgrades it and holds the lock until close; backup and vacuum take the same lock, and restore writes a destination that must not exist. - **The format.** The version row, the schema, the ordered upgrades and the refusal of an unsupported format. - **The connections.** One writer connection with its queue, a read pool, the WAL checkpoint and the close drain. - **Transactions and reads.** One commit or one consistent read per call; the engine does not interpret the rows. These operations are the engine's private implementation for the data owners; they are not a service face. @@ -58,7 +58,7 @@ None. The assembly provides the store; deployment chooses its instance. Offline | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `storageReport` | The store's own file bytes, WAL bytes and reclaimable bytes | `{}` | `{databaseBytes, walBytes, reclaimableBytes}` | None | `closed`, `storage` | -| `backup` | Copy a closed store and its sidecar files into an archive | the database path and the destination | `{}` | None; the tool runs alone | `owned`, `storage` | +| `backup` | Copy a closed store and its sidecar files into an archive | the database path and the destination | `{}` | None; the tool runs alone | `owned`, `format`, `storage` | | `restore` | Write a store from an archive produced by `backup` into a destination that does not exist | the archive and the destination | `{}` | None; the tool runs alone | `format`, `storage` | | `vacuum` | Remove the content rows no stored reference reaches and reclaim the file's free pages | the database path | the removed rows, content bytes and sizes | None; the tool runs alone | `owned`, `format`, `storage` | @@ -98,7 +98,7 @@ Flow tests on the owner: - Opening a newer format refuses and leaves the file unchanged; an upgrade is one transaction; a second process fails to open while the lease is held. - `storageReport` answers the file, WAL and free-page values; the client method returns the same values. - Closing drains the running owner calls, checkpoints and releases the lease; an offline tool cannot open while the daemon owns it. -- A backup round-trips through restore; restore refuses an existing destination; vacuum refuses a store a daemon owns and a store whose format differs. +- A backup round-trips through restore; backup of a store whose format differs answers `format`; restore refuses an existing destination; vacuum refuses a store a daemon owns and a store whose format differs. - The data owners' transactions are tested by their owners' flow tests; the engine's tests cover their commit, rollback and drain, not their business answers. ## Client-visible changes @@ -158,19 +158,20 @@ pub struct Capacity { pub reclaimable_bytes: u64, } -/// The wire error: `{code, message}`, with `code` one of `storage`, `owned` or `format` for the offline functions. -#[derive(Debug, thiserror::Error, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -#[error("{code}: {message}")] -pub struct StorageError { - pub code: String, - pub message: String, +/// The wire error: one variant per code; `code` is the variant name in snake_case. +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum StorageError { + #[error("{message}")] + Storage { message: String }, + #[error("{message}")] + Owned { message: String }, + #[error("{message}")] + Format { message: String }, + #[error("the store is unloading")] + Closed, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Empty {} - impl PublicService for SqliteStorage {} #[rutis::service(name = "sqliteStorage")] diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 116fefe951..b74b1321e3 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -619,37 +619,34 @@ commit paths, not operations of that face. ### 5.1 Ordered admission and durable completion -`append` keeps the existing contract, split into data: **admission is synchronous and ordered, -completion is a notification in branch sequence order.** +Admission and release are the Session store's own steps, not operations of the `timelineStore` +face. The store's `create`, `fork`, `delete` and its internal commit path assign each batch its +place in the Session's single writer queue, drain accepted batches before a release and roll back +a prepared creation ([SessionStore](plugins/SessionStore.md)). The face carries the reads and the +completion notifications below. + +The store's admission is synchronous and ordered, and completion is a notification in branch +sequence order: ```text -append {sessionId, branchId, batchId, events} (sync) - -> {accepted: true} | error {code, message} +admission (owner step) batch -> queued in call order commits {sessionId} (async) -> {subscriptionId} notification {subscriptionId, batchId, branchId, through, result: "committed" | {code, message}} ``` -- `append` is a **sync** operation, like `localId.get`: it validates, assigns the batch its place - in the Session's single writer queue, and answers `{accepted}` without waiting for I/O. It is the - one face operation a caller may issue inside its own commit lock, because it performs no I/O and - returns nothing the caller must await. The Timeline's existing admission — one - `TimelineStore::append` under the branch's commit mutex — maps onto it one to one: batches are - queued in call order, so per-branch sequence order is the admission order. - `commits` registers the caller's completion listener and answers a subscription id. The provider then delivers one notification per accepted batch, after that batch is durable or has failed, **in branch sequence order**. `through` is the inclusive sequence of the batch's last event on `branchId`. It advances the durable watermark only when `result` is `"committed"`. -- A failed batch is reported with its `batchId` and error, and rejects later `append` calls for - that Session with a storage error until it is released. The failure is not delivered twice. -- `releaseSession` and `rollbackSession` answer only after every batch the Session had accepted - has completed or failed: draining is the reply, so a caller that closes a Session knows no write - is still in flight. A Session's close waits for its release. +- A failed batch is reported with its `batchId` and error, and refuses later admissions for that + Session with a storage error until the store releases it. The failure is not delivered twice. +- A Session's close waits for the store's release, which answers only after every accepted batch + has completed or failed, so a caller that closes a Session knows no write is still in flight. - `closeCommits {subscriptionId}` ends a listener; the caller's unload ends it too. -- A remote consumer must not call `append`: the store is provided where the Session state is, and - a synchronous call across a link would block the caller inside its lock. Reading history - (`readPage`, `query`, `trace`, and the completion notifications) is the part a remote consumer - may use. +- A remote consumer reads history (`readPage`, `query`, `trace`, and the completion + notifications); it does not admit a batch, because the store is provided where the Session + state is. #### Binding shapes and lifecycle @@ -665,15 +662,12 @@ 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 of [SessionStore](plugins/SessionStore.md) and +keeps that canonical reply. `saveSnapshot {sessionId,branchId,snapshot}` returns `{}`. `sessionConfig {sessionId}` returns `{config}`. `latestSnapshot {sessionId,branchId,through,interpreter}` returns `{snapshot}`. -`createSession`, `releaseSession`, `rollbackSession` and `append` are the store's own creation and -commit steps, not operations of the `timelineStore` face: the Session store prepares the backend -record, rolls back a prepared creation, releases a Session's writes and admits batches inside its -own operations ([SessionStore](plugins/SessionStore.md)). App Server creation/deletion retain the -repository and lifecycle obligations the contract states. +App Server creation/deletion retain the repository and lifecycle obligations the contract states. Snapshots retain their canonical fields (`sequence`, `event_id`, `interpreter`, `state`), optional acceleration semantics and owner validation. Domain errors preserve `{code,message}` using @@ -681,28 +675,23 @@ acceleration semantics and owner validation. Domain errors preserve `{code,messa The bridge binding of `commits` is `commits({sessionId}, listener) -> {subscriptionId}`. The caller must declare `timelineStore`; the owner registers the listener with that calling row before -returning, and the row's unload withdraws it. Register before the batches to observe are admitted; -there is no replay of earlier admissions. `closeCommits` withdraws it explicitly and is +returning, and the row's unload withdraws it. Register before the store admits the batches to +observe; there is no replay of earlier admissions. `closeCommits` withdraws it explicitly and is idempotent. Each listener receives only its requested Session's completions, tagged with its own subscription id. A slow or failed observer does not delay durable completion or release, and ending observation never cancels a write or the native publication callback. The calling row must belong to the runtime in which the provider installed the binding; sharing the native binding with another runtime does not connect that runtime's listeners to the provider's completion bus. -The native binding retains synchronous `append` admission and its existing publish callback. +The native binding keeps the store's synchronous admission and its existing publish callback. Its notification `batchId` is the JSON encoding of `[branchId, through]`, the batch identity already known at admission; local data calls preserve their supplied `batchId`. This identifier -is notification correlation only, with no additional durable fact or lookup. A synchronous -admission refusal produces no completion notification. The one backend callback keeps native -publication synchronous, then enqueues observation on rutis's existing ordered asynchronous -bus. Release drains that backend's writes and callbacks; it does not wait for observers to finish. +is notification correlation only, with no additional durable fact or lookup. A refused admission +produces no completion notification. The one backend callback keeps native publication +synchronous, then enqueues observation on rutis's existing ordered asynchronous bus. Release +drains that backend's writes and callbacks; it does not wait for observers to finish. Foreign-language rows in the provider runtime may observe and read; a separate runtime has -read-only access. Synchronous append across a link is rejected as stated in §5.1. - -The Rust `TimelineStore` trait is the local binding of `timelineStore`, not a second contract -(§6); the SQL engine remains the provider's implementation. The binding of `append` is -synchronous admission, and the binding of `commits` is publish-callback registration, -with the existing ordering and draining. +read-only access. ### 5.2 Session rows From 3676a27cc5b73d01e7bf3cbc72c5e94bf3971c56 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 11:44:45 +0800 Subject: [PATCH 08/19] docs(storage): restore the FileStorage root_path dependency FileStorage's latest contract restores root_path, add_root, stat and read's size. SessionFiles reads the store directory's root with root_path instead of computing it from the database path; the requirement names the operations at that head and the host's root registration for the native store directory. Refs #2018 Refs #2015 --- docs/design/plugins/SessionFiles.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md index 3f3d738966..6887964303 100644 --- a/docs/design/plugins/SessionFiles.md +++ b/docs/design/plugins/SessionFiles.md @@ -61,7 +61,7 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? ### Dependencies -`fsHost` for file creation, atomic replacement, import, page reads, listing and removal; the operations used are the ones in [FileStorage's contract](https://github.com/arcships/dim/pull/2080). The owner computes its own directory (`<db>.session-files`) from the database path it holds and passes absolute paths; FileStorage's root set must cover the native store directory, which the host registers. The engine's file-ownership rows are private to the storage crate and are not a service. The owner does not depend on `store`: the store depends on this owner when a delete releases files. +`fsHost` for `root_path`, file creation, atomic replacement, import, page reads, listing and removal; the operations used are the ones in [FileStorage's contract](https://github.com/arcships/dim/pull/2080). The owner joins the store directory's root path from `root_path` with `<db>.session-files` and passes absolute paths under it; the host registers the native store directory as a root. The engine's file-ownership rows are private to the storage crate and are not a service. The owner does not depend on `store`: the store depends on this owner when a delete releases files. ### Operations @@ -164,7 +164,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -1. **FileStorage (#2016): the operations this owner calls.** `read` with `{offset, length}`, `write` with its `source` and `privateReadOnly`, `import` with `max_bytes` and `privateReadOnly`, `create_directory`, `list` and `remove` exist in [FileStorage's contract](https://github.com/arcships/dim/pull/2080) at head `e951536ec`. `root_path` left that face: the owner computes `<db>.session-files` from its database path, so the only need is that the host's root set covers the native store directory; a comment on #2016 states it. +1. **FileStorage (#2016): the operations this owner calls.** `root_path`, `read` with `{offset, length}` and `{data, eof, size}`, `write` with its `source` and `privateReadOnly`, `import` with `max_bytes` and `privateReadOnly`, `create_directory`, `list` and `remove` exist in [FileStorage's contract](https://github.com/arcships/dim/pull/2080) at head `7224c0cd4`. The owner reads the store directory's root with `root_path`; the host registers the native store directory as a root, and a comment on #2016 records the dependency. 2. **Service type placement (#2015): a process owner in the app server.** The owner type is in `dim-app-server`, where the engine and the rows are; callers in plugin crates cannot depend on the app server. The request and reply types are plain data in `dim-agent-capabilities::host`, and callers outside the crate call the operations by the `sessionFiles` name. If the maintainers decide every process face must be annotated on a type plugin crates can name, the type moves to a shared crate; a comment on #2015 states the requirement. ## Binding appendix From f562eeba2f5565f6ce6ff3820a6d8c6410a74331 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 13:31:13 +0800 Subject: [PATCH 09/19] docs(storage): address the round-five inline review SessionStore: the store face is one hand-written HostDispatch on the owner, so setTitle is admitted in invoke before the reply future is returned; the supersede entry names title and setTitle(id, change). SessionFiles: an offset above the file size is clamped before the page read, remove reports closed during unload, and the parent close row matches. SessionTitle and session-title-metadata: use {id} and setTitle(id, change), list closed with its service_reloading mapping, and replace the SessionMetadataService binding. Resource faces: the rule check names the store's internal admission instead of append as a face operation. The credential rules now point at the Provider and Settings owners' operations, not at sqliteStorage. ManagedWorktrees: a discard refused by a closing store drops its preparation and retries through remove. Refs #2018 Refs #2015 --- .../appserver/session-title-metadata.md | 11 ++++--- .../contracts/resource-owner-operations.md | 14 +++----- docs/design/plugins/ManagedWorktrees.md | 2 +- docs/design/plugins/SessionFiles.md | 6 ++-- docs/design/plugins/SessionStore.md | 33 +++++++++++++++++-- docs/design/plugins/SessionTitle.md | 8 ++--- docs/design/resource-faces.md | 4 +-- 7 files changed, 50 insertions(+), 28 deletions(-) diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index b1a31f074e..d6c98d3138 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -103,7 +103,8 @@ The `store` face, process scope, control node only, no instance key, provided by | --- | --- | --- | | `not_found` | The store holds no record of the Session: never created, deleted, or rolled back. A stored Session that is closed or not loaded is found | Unchanged | | `rejected` | The change refused with its own `code` and `message`; the manual-title rule is the change's | Unchanged, no notice. Act on the change's code | -| `storage` | The transaction failed, or the call arrived after SessionStore started closing (§6) | Unchanged, no notice | +| `storage` | The transaction or the file write failed | Unchanged, no notice | +| `closed` | The call arrived after SessionStore started closing (§6) | Unchanged, no notice; retry on the replacement generation | ### 4.2 Rust @@ -121,7 +122,7 @@ adds no asynchronous wrapper before handover, cancellation point, read, or secon ```text caller SessionStore SQLite Session channel ------ ----------------------------------------------- ----------------- --------------- - setTitle(S, r, T) ----> SessionStore closing? -> storage at once, nothing written + setTitle(S, C) ----> SessionStore closing? -> closed at once, nothing written admit: start the write task <== handover (the call) | (SessionStore owns the task; dropping the | call from here on only loses the reply) @@ -150,10 +151,10 @@ This settles the boundary that SessionTitle §0 left to S5b. | Point | Rule | | --- | --- | | Before the call | The caller's own work. Cancelling it before the call writes nothing | -| The call | The handover is SessionStore receiving the call: before it returns, `setTitle` admits the write and starts it as SessionStore's own task, or, once SessionStore is closing, fails `storage` without writing. In Rust `set_title` is a plain function that does this and returns a future of the reply. That future only awaits the task, so dropping it detaches the reply, never the write. The named service calls it inside `invoke`, so a JavaScript call is handed over once the host receives it | +| The call | The handover is SessionStore receiving the call: before it returns, `setTitle` admits the write and starts it as SessionStore's own task, or, once SessionStore is closing, fails `closed` without writing. In Rust `set_title` is a plain function that does this and returns a future of the reply. That future only awaits the task, so dropping it detaches the reply, never the write. The named service calls it inside `invoke`, so a JavaScript call is handed over once the host receives it | | After the call | SessionStore settles the write itself: it commits and announces, or fails and writes nothing. Dropping the call, unloading the calling row or losing the reply neither cancels nor undoes it. `setTitle` has no cancel action | | Lost reply | The caller reads with `title`. It does not repeat the write blindly: a second change would commit another revision ([SessionTitle Appendix C](../plugins/SessionTitle.md#appendix-c-errors-and-recovery)) | -| SessionStore unload | Its disposer first stops admission: from then on a call fails `storage` at once and writes nothing. It then waits until every admitted write, the one in its turn and those waiting for theirs, has committed and announced or failed. Only then does it close Session files and the Timeline writer, and SqliteStorage, which unloads after SessionStore, closes the connection. The notices follow C6 delivery: once the Session is no longer loaded, nobody listens and they are dropped. Nothing is retried after a reload | +| SessionStore unload | Its disposer first stops admission: from then on a call fails `closed` at once and writes nothing. It then waits until every admitted write, the one in its turn and those waiting for theirs, has committed and announced or failed. Only then does it close Session files and the Timeline writer, and SqliteStorage, which unloads after SessionStore, closes the connection. The notices follow C6 delivery: once the Session is no longer loaded, nobody listens and they are dropped. Nothing is retried after a reload | Rejected: a cancel action that works until the transaction starts. It would only move the uncertainty, since a caller that drops the call still has to read to learn the outcome; and a JavaScript caller cannot cancel a host call in rutis @@ -349,7 +350,7 @@ None. S5b uses C6's `notify`, the existing service catalog and `HostDispatch`, a client receives the notice (`node_` test, run by CI's Node step). 11. A `setTitle` request without `title` is rejected; the plugin SDK type check covers the call shapes. 12. Unload: writes admitted before SessionStore starts closing, one in its turn and one waiting for it, commit and - reply with their revisions while shutdown waits for them; a call after closing starts fails `storage` at once and + reply with their revisions while shutdown waits for them; a call after closing starts fails `closed` at once and is not in the store after a restart (§6). Tests: items 1 to 8, 10 and 12 are in [titles.rs](../../../crates/dim-app-server/tests/transport_flow/titles.rs), through diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 319347333a..ca7dd6e3b4 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -33,17 +33,11 @@ Superseded by the owner contracts. The Agent records belong to [Agents and Colla ### Credential values in replies -Any trusted plugin in the same process-service scope can call these storage methods. -`sqliteStorage.readRecord` returns the stored fields selected by its projection, -including inline credentials when selected. A stored secret reference is returned as a -reference. Provider resolves it through its configured secret host and obtains managed -OAuth credentials from their existing owner. +The Provider and Settings owners' record operations return the stored fields their contracts name ([Provider](https://github.com/arcships/dim/pull/2096), [Settings](https://github.com/arcships/dim/pull/2094)). A stored secret reference is returned as a reference; Provider resolves it through its configured secret host and obtains managed OAuth credentials from their existing owner. -`sqliteStorage.readUser` and `importUserIfAbsent` return the complete stored document, -including original values in `mcp-secrets`. `replaceUser` returns the committed version. -MCP reads its credential document through Settings and uses it to establish connections. -Provider and MCP business replies omit credentials. The business API `settings.read` -serves declared sources and excludes the native `mcp-secrets` document. +Provider's record read returns inline credentials only in the projection its contract names, and its business replies omit them. Settings' document read and import return the complete stored document, including original values in `mcp-secrets`; its replace answers the committed version. MCP reads its credential document through Settings and uses it to establish connections. The business API `settings.read` serves declared sources and excludes the native `mcp-secrets` document. + +The exception is scoped to the Provider and Settings owners' own operations, not to `sqliteStorage`: the engine's row operations are its crate-private implementation and are not callable by plugins. ## Settings diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md index 818292f0d4..8e5fb52a4a 100644 --- a/docs/design/plugins/ManagedWorktrees.md +++ b/docs/design/plugins/ManagedWorktrees.md @@ -107,7 +107,7 @@ A process death between `create` and `store.create` leaves an unregistered direc ## Exceptions with reasons - A branch is kept when `remove` deletes an adopted worktree: committed content must not disappear with the directory. Only the default `dim/<taskId>` branch of a never-adopted worktree is deleted with the directory. -- `discard` is not cancellable: a cancelled Session creation still has to settle what the owner made. A store refusal (`closed` or `storage`) leaves the directory and branch in place; the caller reports it, and the preparation stays for a retry on the replacement generation. +- `discard` is not cancellable: a cancelled Session creation still has to settle what the owner made. A store refusal (`closed` or `storage`) leaves the directory and branch in place; the caller reports it. The preparation is dropped with the generation, so the directory is unregistered and `remove` by task id is the retry path on the replacement generation. - Unregistered directories are never pruned: the owner has no record to age, so only an explicit `remove` by task id deletes them. - A branch outlives a creation that was never adopted: a process death between `create` and `store.create` leaves the branch. `remove` on an unregistered directory deletes the directory and, when the owner created the default `dim/<taskId>` branch for a worktree that was never adopted, deletes that branch too; an explicit branch from the request is retained and reported, so a name the operator chose is never deleted. - Git is the owner's process resource: the owner starts each call, bounds it (10s read, 30s write) and reaps it on cancellation. diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md index 6887964303..48dce3cd02 100644 --- a/docs/design/plugins/SessionFiles.md +++ b/docs/design/plugins/SessionFiles.md @@ -73,10 +73,10 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `read` | One page of a Session file, at most 64 KiB | `{sessionId, fileId, offset}` | `{data, eof}`, `data` is base64 and `eof` is true exactly when it is empty | While the page is read; nothing changes | `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `register` | Record a caller-owned output path for the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `storage` | | `owns` | Whether a path or file id belongs to the Session | `{sessionId, path}` | `{owned}` | While the path is resolved | `node_unavailable`, `cancelled`, `closed`, `storage` | -| `remove` | Remove one Session file and its ownership row; an absent or foreign file answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal | `node_unavailable`, `storage` | +| `remove` | Remove one Session file and its ownership row; an absent or foreign file answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal during close | `node_unavailable`, `closed`, `storage` | | `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `storage` | -`path` is absolute on the Session's resource node; `bytes` is the stored length. `offset` at or beyond the end answers an empty `data` with `eof`. A `fileId` outside the Session, or a name that is not one component, is `not_found` for reads and writes and `invalid` for a name `put` or `import` receives. +`path` is absolute on the Session's resource node; `bytes` is the stored length. `offset` at the file size answers an empty `data` with `eof`; an offset above the size is clamped to the size before the page read, because FileStorage refuses an offset above it with `invalid`. A `fileId` outside the Session, or a name that is not one component, is `not_found` for reads and writes and `invalid` for a name `put` or `import` receives. ### Errors @@ -98,7 +98,7 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `import` | Open the source, check size, copy through FileStorage into a temporary file, commit ownership | The temporary file is removed; no owned row | The copy completes or is abandoned; the sweep removes what no row owns | As `put` | Source and temporary file by FileStorage; rows by SessionFiles | | `write` | Resolve the file id, write the new bytes through FileStorage under the same path, keep the row | Before the replacement: the old bytes stay | The write completes or is abandoned | As `put` | File and path by FileStorage; row by SessionFiles | | `read` | Resolve the file id, read one page at the offset; an offset at or past the end is an empty page | The page stops; nothing changes | The read stops | Pending reads end `closed` | FileStorage | -| `remove` | Resolve the file id; an absent or foreign id answers success; remove the directory entry through FileStorage, delete the row | None | The call ends | Rows stay for the next generation | File and row by SessionFiles | +| `remove` | Resolve the file id; an absent or foreign id answers success; remove the directory entry through FileStorage, delete the row | None | The call ends | A new call is refused `closed`; an admitted removal finishes | File and row by SessionFiles | | `register` | Check the Session, record the path the caller resolved | None | The row stays; a later Session delete removes it | Rows stay for the next generation | SessionFiles | | `owns` | Resolve the path against the owner's directory, check the output row, else the file id row | The resolution stops | Nothing to release | Pending calls end `closed` | SessionFiles | | `ownedPaths` | Read both ownership rows, map file ids to the directory | None | Nothing to release | Rows stay | SessionFiles | diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 032db4db00..0f1cff4480 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -175,7 +175,7 @@ None. The client methods (`session.rename`, `sessions.list`, `session.delete`, ` - [Resource faces §5, §5.1 and §5.2](../resource-faces.md): the `store`/`timelineStore` split, the admission and drain steps, the Session row operations, the Rust `Store` binding and the metadata and association rows. - [Service faces §3.3 and §3.4](../service-faces.md): the `sessionStore` row and the `store` and `timelineStore` rows. - [Resource owner operations](../contracts/resource-owner-operations.md): the `SessionStore → sqliteStorage` rows and the Session row paragraphs. -- [Session title metadata](../appserver/session-title-metadata.md): the `readMetadata` and `setTitle` shapes. +- [Session title metadata](../appserver/session-title-metadata.md): the `title` and `setTitle(id, change)` shapes. - [SessionTitle](SessionTitle.md): the paragraph that writes a title under an expected revision. ## Verification @@ -209,7 +209,7 @@ Material uncertainty: a process death during the caller's removal step leaves th | §4 rule 8 | No infrastructure change; requirements are listed below. | | §4 rule 9 | The store publishes no Timeline fact of its own; the attached worktree stays a process fact. | | §7.2 ids and values | Requests and replies are data; the title change and the worktree removal step cross as callbacks by reference. No object crosses. | -| §7.2 one public face | The service is marked on the SessionStore type under the existing `store` name; `Store`, `SessionMetadata` and `WorktreeAssociations` do not exist beside it. | +| §7.2 one public face | The `store` face is the owner's own hand-written `HostDispatch` on `SessionStore`; `Store`, `SessionMetadata` and `WorktreeAssociations` do not exist beside it. | | §7.2 caller mechanisms | The exclusion, the title admission and the record settlement stay inside the owner; callers handle business errors only. | | ADR 002 D1 | Process scope: the Session row set and its records outlive a Session. | | ADR 002 D2 | No wiring plugin: one service on the owner type. | @@ -416,7 +416,10 @@ impl SessionStore { } } -#[rutis::service(name = "store")] +/// The `store` face is a hand-written `HostDispatch` on the owner: one provider, one method table. +/// `invoke` decodes one request object, calls the method and returns the reply; `setTitle` calls +/// `set_title` eagerly before returning its wait, so a wire caller that drops the reply still +/// commits the write. The marked-service spelling of the other three owners does not apply here. impl SessionStore { pub async fn create( &self, @@ -457,6 +460,30 @@ impl SessionStore { // ... } } +impl rutis_bridge::session::HostDispatch for SessionStore { + fn methods(&self) -> Option<serde_json::Value> { + Some(serde_json::json!({ + "create":"async", "delete":"async", "fork":"async", "creationRecord":"async", + "owner":"async", "hasRecords":"async", "sessionConfig":"async", "catalog":"async", + "query":"async", "grants":"async", "addGrant":"async", "removeGrant":"async", + "setLanguage":"async", "title":"async", "setTitle":"async", + "associateWorktree":"async", "worktrees":"async", "worktreeUsages":"async", + "sessionsUnder":"async", "removeWorktree":"async", + "removeUnregisteredDirectory":"async" + })) + } + + fn invoke( + &self, + method: &str, + args: rutis_bridge::session::Value, + ) -> rutis_bridge::session::Reply { + // Decode one request object, call the method, return its reply. `setTitle` calls + // `set_title` eagerly here, before the reply future is returned. + let _ = (method, args); + todo!() + } +} ``` The remaining operations follow the same shape: one request object, one reply object, the caller's `Ctx` where the operation is bound to the calling row, and `CancelledFn` only where the operation waits on a read. diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 3cd8387e1f..7d6f87cf7b 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -383,7 +383,7 @@ Registered with `sessionMethods` (Session, namespace `session.rename`) with one | Service | Method | Kind | Request | Reply and errors | | --- | --- | --- | --- | --- | | SessionStore `store` | `title` | async | `{id}` | `{revision, title: {text, source: "auto" \| "manual"} \| null}`; errors `not_found`, `closed`, `storage` ([SessionStore](SessionStore.md)) | -| SessionStore `store` | `setTitle` | async | `{sessionId}` plus a change that receives `{revision, title}` and returns the next title or `null` | `{revision}`; errors `rejected`, `not_found`, `storage`. The call is the handover; after a commit SessionStore emits the title notice | +| SessionStore `store` | `setTitle` | async | `{id}` plus a change that receives `{revision, title}` and returns the next title or `null` | `{revision}`; errors `rejected`, `not_found`, `closed`, `storage`. The call is the handover; after a commit SessionStore emits the title notice | | SessionStore (S5b) | title notice | Session broadcast notice (C6 record, §9) | — | `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}` on the Session's broadcast channel; no sequence number, not replayed | | `AuxiliaryModel` (the profile's model-selection owner) | `complete` | async | `{model: {providerId, modelId}, request: {system, messages: [{role: "user", content: text}]}}`, optional `cancelled: () => Promise<void>` ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)) | `{text, stopReason, usage}`; rejects with the existing error code/message. Resolve the cancellation reference on timeout or closing and await the original call's settlement | @@ -413,7 +413,7 @@ omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remain | Check | `store.title({id})`: the change decides from the current title and revision; a `rejected` change discards | | Read | The four field queries in §0.1 share published T >= N. No adopted eligible input/text means no title (A8/A10). | | Generate | Route and fall back under §3.3 within the shared 30 s budget (A4); normalize the first line, remove quotes and trailing punctuation, collapse whitespace, cut at `maxLength`, trim again | -| Write | `setTitle({sessionId}, change)` where the change returns the generated title or `null`; a `rejected` change discards | +| Write | `setTitle({id}, change)` where the change returns the generated title or `null`; a `rejected` change discards, and `closed` retries on the replacement generation | | Timeline | No writes, no Dispatcher registration, no `StateCell` | | Reload / unload | Cancel before store handover; the owner settles an admitted mutation. Events in the gap are not replayed | @@ -505,7 +505,7 @@ auxiliary binding use the owner contracts in §0. The optional service contract | --- | --- | | Namespace `session.rename` registered with `sessionMethods` | The Session part calls `methods.register(ctx, "session.rename", Vec<MethodDecl>, handler)` on a `Key<SessionMethods>` dependency | | Published branch properties | Required `Key<TreeCommands>`; `TreeCommands::query("main", TimelineQuery)` with branch scope, `include_publishing: false` and one-row `QuerySelect::Fields` results. Configuration paths are `data.settings.providerId` and `data.settings.modelId`. | -| Title metadata | `SessionMetadataService::read` and `SessionMetadataService::set_title` | +| Title metadata | `store.title` and `store.setTitle(id, change)` | | Auxiliary call | `AuxiliaryModel.0.complete` with its cancellation token | | Optional generation | `ctx.get_at(&host_key("sessionTitleGenerator"))` at use; `HostDispatch.generate` with a cancellable callback promise, using the request/reply types exported by `dim-session-title` | | Session broadcast listener | Listener on `session_channel(session_id)` for `Event` records, removed by `ctx.effect` | @@ -513,7 +513,7 @@ auxiliary binding use the owner contracts in §0. The optional service contract ```rust // the `store` face; `setTitle` stays on the hand-written method table -async fn read(&self, session_id: &str) -> Result<SessionMetadata, MetadataError>; +async fn title(&self, id: &str) -> Result<SessionMetadata, StoreError>; // NotFound | Closed | Storage fn set_title(&self, id: &str, change: ChangeFn) -> impl Future<Output = Result<u64, StoreError>>; // Rejected | NotFound | Closed | Storage; the call is the handover pub struct SessionMetadata { pub revision: u64, pub title: Option<Title> } diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index b74b1321e3..c49d9d3476 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -737,9 +737,9 @@ The owners that read node files or start node processes, and the operations they | §1, ADR 002 D1 | Each face belongs to the part that owns the resource or the state; consumers stay in their own scope. No new Capability on the control side | | §4 rule 1 | Command events are not added. A background command's fact is still `exec/started`/`exec/ended` on its branch, written by its owner | | §4 rule 2 | A handoff keeps its fact on the branch and its process with the provider; nothing is handed to a second owner | -| §4 rule 3 | No before callback and no commit-time I/O. `timelineStore.append` is the one operation allowed inside the caller's commit lock because it queues without I/O and does not wait; completion arrives through `commits`, after the commit and outside every lock. Every other face operation is outside the lock | +| §4 rule 3 | No before callback and no commit-time I/O. Admission is the Session store's internal step, not a face operation: the store queues the batch inside its own commit path without I/O and does not wait; completion arrives through `commits`, after the commit and outside every lock. Every face operation is outside the caller's commit lock | | §4 rule 4 | Core, assembly and the Timeline carry no remote-execution or engine branch; the provider is chosen by deployment | -| §4 rule 5 | No batch semantics change: `append` admits one atomic batch, and the completion notification carries the same commit and publish boundary the callback does today | +| §4 rule 5 | No batch semantics change: the store admits one atomic batch in its own path, and the completion notification carries the same commit and publish boundary the callback does today | | §4 rule 6 | File content and command output reach the model only through tool results, as they do today | | §4 rule 7 | Consumers use the faces; they read no provider internals, and the providers use only their own host facilities | | §4 rule 8 | The faces add no Timeline, Dispatcher or event-format change. One runtime requirement is unmet: [#861](https://github.com/arcships/dim/issues/861), per-call resolution of a Session's process-scope service by its resource node. It is the dim runtime's, solved with rutis's current capability; no requirement is raised to rutis ([overview §6.3](overview.md#63-multiple-nodes), [principles §4 rule 8](../architecture/rust-agent/principles.md)) | From e5f59450894e8c11468071ab11704f01c0e80e1a Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 14:10:23 +0800 Subject: [PATCH 10/19] docs(storage): align the read handshake and the title service names --- docs/design/plugins/SessionFiles.md | 2 +- docs/design/plugins/SessionTitle.md | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md index 48dce3cd02..4fc9d1c81b 100644 --- a/docs/design/plugins/SessionFiles.md +++ b/docs/design/plugins/SessionFiles.md @@ -76,7 +76,7 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `remove` | Remove one Session file and its ownership row; an absent or foreign file answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal during close | `node_unavailable`, `closed`, `storage` | | `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `storage` | -`path` is absolute on the Session's resource node; `bytes` is the stored length. `offset` at the file size answers an empty `data` with `eof`; an offset above the size is clamped to the size before the page read, because FileStorage refuses an offset above it with `invalid`. A `fileId` outside the Session, or a name that is not one component, is `not_found` for reads and writes and `invalid` for a name `put` or `import` receives. +`path` is absolute on the Session's resource node; `bytes` is the stored length. `offset` at the file size answers an empty `data` with `eof`; an offset above the size is clamped to the size before the page read, because FileStorage refuses an offset above it with `invalid`. The rule is stated once in both documents: at `size` an empty page with `eof`, above `size` `invalid` at FileStorage; this owner clamps so its own callers keep the empty page their client contract states. A `fileId` outside the Session, or a name that is not one component, is `not_found` for reads and writes and `invalid` for a name `put` or `import` receives. ### Errors diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 7d6f87cf7b..76c99955fe 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -36,7 +36,7 @@ only outcome and duration. | Boundary | Current contract and Ready decision | | --- | --- | -| Observation | Read the Session id from `sessionIdentity`, the creation configuration from `sessionConfig` and closing from `sessionLifecycle` ([plugin contract](../plugin-contract.md#9-requirements-raised-to-mechanism-owners) R2), then the records on its Session's `session/{sessionId}` channel. C4 broadcast #180 is delivered; #63/#168 are closed. | +| Observation | Read the Session id, the creation configuration and closing from SessionScope's `identity`, `config` and `closing` ([#2093](https://github.com/arcships/dim/pull/2093), target, pending; [plugin contract](../plugin-contract.md#9-requirements-raised-to-mechanism-owners) R2), then the records on its Session's `session/{sessionId}` channel. C4 broadcast #180 is delivered; #63/#168 are closed. | | Timeline reads | Use the Session’s branch query facade on `main`, with a fixed published cutoff. Read only the adopted input identity, its user content or Goal objective, and the adopted model fields (§0.1). | | Configuration | Existing named Settings and row source declaration, user scope only (A.3/A12). Read settings.read({source:"session-title",scope:"user"}) at each decision and use its validated/defaulted document directly. | | Metadata/notice | The process `store` face provides `title` and `setTitle(id, change)`; `setTitle` commits the title the change returns and answers the revision, with errors `rejected`/`not_found`/`storage` ([SessionStore](SessionStore.md)); the v3 list fields are `title`/`titleSource`/`titleRevision`. After each commit SessionStore calls `session_broadcast::notify`, and Rpc forwards the record to attached v3 clients as `session.notice {sessionId, source, kind, data}` (C6 #49/#85, [Session broadcast notices](../appserver/session-notices.md)). | @@ -72,8 +72,8 @@ it does not start an asynchronous initialization job. Its creation configuration The plugin depends on the existing public Rust Settings and `store` bindings; it does not expose or alter their implementations. Plugin behavior and cross-plugin title flows live in this crate's tests and use the public client and host APIs. App Server tests have no dependency on this crate and install no title plugin implicitly. The part injects its required dependencies: the process services -`settings`, `store` and `auxiliaryModel`, and the Session services branch queries, `sessionIdentity`, -`sessionConfig`, `sessionLifecycle` and `sessionMethods`. The optional `sessionTitleGenerator` +`settings`, `store` and `auxiliaryModel`, and the Session services branch queries, SessionScope's +`identity`, `config`, `activated` and `closing`, and `sessionMethods` ([#2093](https://github.com/arcships/dim/pull/2093), target, pending). The optional `sessionTitleGenerator` is read by name when used, without injection or a readiness gate, under the [required/optional binding contract](../rutis-usage.md#3-services-by-name). The product assembly installs the native @@ -125,7 +125,7 @@ flowchart LR | Part | Scope | Depends on | Provides | | --- | --- | --- | --- | | `session-title` | Process | Settings and part registry | Registers the Settings source and Session part | -| `SessionTitle` | Session | Session services `sessionIdentity`, `sessionConfig`, `sessionLifecycle` and `sessionMethods`; Session branch queries; process Settings, the title operations `store` and required `auxiliaryModel` (a profile without an owner of model selection keeps the row Pending); optional `sessionTitleGenerator` read at use | Registers session.rename with sessionMethods | +| `SessionTitle` | Session | Session services SessionScope's `identity`, `config`, `activated` and `closing`, and `sessionMethods` ([#2093](https://github.com/arcships/dim/pull/2093), target, pending); Session branch queries; process Settings, the title operations `store` and required `auxiliaryModel` (a profile without an owner of model selection keeps the row Pending); optional `sessionTitleGenerator` read at use | Registers session.rename with sessionMethods | Dependencies stay in the Session or enclosing process. Session observation, branch queries and Settings supply observation, field reads and configuration; S5b supplies title metadata and C6 the notices; the profile's model-selection owner supplies the named auxiliary operation. The plugin's row registers its source in its `apply`. Real provider reloads cancel the row's work (ADR 002 D3); SessionStore index reload does not. Business data changes never reload the plugin (D4). @@ -407,7 +407,7 @@ omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remain | Step | Path | | --- | --- | -| Listen | The Session's copy of the part listens to its Session's `session/{sessionId}` from `apply`, filters main input/applied, registers an owned task and returns; `sessionLifecycle.closing()` or copy cleanup ends owned work | +| Listen | The Session's copy of the part listens to its Session's `session/{sessionId}` from `apply`, filters main input/applied, registers an owned task and returns; SessionScope's `closing()` or copy cleanup ends owned work | | Eligibility | C4 creation snapshot: `interactive !== false && collaborationRole === "leader"` for generation; native omission means true. A requested initial title (`initialTitle`, §3.4) is written for interactive and non-interactive Sessions alike: it needs no model, and it is the caller's own text | | Trigger | On `input/applied` at `N`: skip if not eligible, disabled, in flight or failed attempts ≥ 3 (A5); otherwise start a generation task owned by the plugin's lifetime | | Check | `store.title({id})`: the change decides from the current title and revision; a `rejected` change discards | @@ -504,7 +504,7 @@ auxiliary binding use the owner contracts in §0. The optional service contract | Neutral | Rust | | --- | --- | | Namespace `session.rename` registered with `sessionMethods` | The Session part calls `methods.register(ctx, "session.rename", Vec<MethodDecl>, handler)` on a `Key<SessionMethods>` dependency | -| Published branch properties | Required `Key<TreeCommands>`; `TreeCommands::query("main", TimelineQuery)` with branch scope, `include_publishing: false` and one-row `QuerySelect::Fields` results. Configuration paths are `data.settings.providerId` and `data.settings.modelId`. | +| Published branch properties | The Session's `timelineTree` service: `read({line: "main", from?, through, fields, limit})` with the published cutoff, which answers `{through, rows}` ([#2092](https://github.com/arcships/dim/pull/2092), target, pending). Configuration paths are `data.settings.providerId` and `data.settings.modelId`. | | Title metadata | `store.title` and `store.setTitle(id, change)` | | Auxiliary call | `AuxiliaryModel.0.complete` with its cancellation token | | Optional generation | `ctx.get_at(&host_key("sessionTitleGenerator"))` at use; `HostDispatch.generate` with a cancellable callback promise, using the request/reply types exported by `dim-session-title` | From be6e4ee898f79494d2dffe8a9765eff1c10ef113 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 14:53:46 +0800 Subject: [PATCH 11/19] docs(storage): answer the round-five ledger and the round-six decisions The store face is one hand-written HostDispatch on SessionStore; the "service is marked" wording is gone from the contract and resource faces. Titles keep only setTitle {id} plus the change callback: the revision-check diagrams, expected-revision labels and conflict retries are removed from SessionTitle and the title metadata doc, which now use title and add closed to the error tables. The associateWorktree request uses {id} in service faces, resource faces and worktree access, and the supersede list records them. Refs #2018 Refs #2015 --- .../appserver/session-title-metadata.md | 6 ++--- docs/design/plugins/SessionStore.md | 3 ++- docs/design/plugins/SessionTitle.md | 23 ++++++++++--------- docs/design/resource-faces.md | 6 ++--- docs/design/service-faces.md | 2 +- docs/design/worktree-access.md | 2 +- 6 files changed, 22 insertions(+), 20 deletions(-) diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index d6c98d3138..14527b7de9 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -131,13 +131,13 @@ adds no asynchronous wrapper before handover, cancellation point, read, or secon +-- BEGIN IMMEDIATE ---------------------------> revision of S | no Session: not_found, rollback | change refuses: rejected, rollback - | write r+1 and T + | write the next revision and T +-- COMMIT ------------------------------------> committed, or storage | committed only: | notify(S, {SessionStore, title, - | {title, titleSource, titleRevision: r+1}}) -------------------> Notice + | {title, titleSource, titleRevision: next}}) ------------------> Notice | end its turn - <---- {revision: r+1} ----+ + <---- {revision: next} ---+ ``` `notify` runs after the commit and before the next write takes its turn, so the notices of one Session reach its diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 0f1cff4480..0037b35c10 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -176,6 +176,7 @@ None. The client methods (`session.rename`, `sessions.list`, `session.delete`, ` - [Service faces §3.3 and §3.4](../service-faces.md): the `sessionStore` row and the `store` and `timelineStore` rows. - [Resource owner operations](../contracts/resource-owner-operations.md): the `SessionStore → sqliteStorage` rows and the Session row paragraphs. - [Session title metadata](../appserver/session-title-metadata.md): the `title` and `setTitle(id, change)` shapes. +- [Resource faces §4.2 and §5](../resource-faces.md), [service faces §4.8](../service-faces.md), [worktree access §4](../worktree-access.md): the `associateWorktree` request uses `{id, repository, root, subtree}`. - [SessionTitle](SessionTitle.md): the paragraph that writes a title under an expected revision. ## Verification @@ -225,7 +226,7 @@ Material uncertainty: a process death during the caller's removal step leaves th ## Binding appendix -The service is marked on the `SessionStore` type; the wire name stays `store`. `Store` the wrapper, `SessionMetadata` and `WorktreeAssociations` no longer exist. `caller: &Ctx` is rutis's caller parameter: the dispatch fills it from the calling row, so no caller sends or names a row. `CancelledFn` is the binding's cancellation argument. +The `store` face is one hand-written `HostDispatch` on `SessionStore`; the wire name stays `store`. `setTitle` is admitted in `invoke` before its reply future is returned, so a wire caller that drops the reply still commits. `Store` the wrapper, `SessionMetadata` and `WorktreeAssociations` no longer exist. `caller: &Ctx` is rutis's caller parameter: the dispatch fills it from the calling row, so no caller sends or names a row. `CancelledFn` is the binding's cancellation argument. ```rust use dim_agent_capabilities::host::CancelledFn; diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 76c99955fe..69f8246849 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -39,7 +39,7 @@ only outcome and duration. | Observation | Read the Session id, the creation configuration and closing from SessionScope's `identity`, `config` and `closing` ([#2093](https://github.com/arcships/dim/pull/2093), target, pending; [plugin contract](../plugin-contract.md#9-requirements-raised-to-mechanism-owners) R2), then the records on its Session's `session/{sessionId}` channel. C4 broadcast #180 is delivered; #63/#168 are closed. | | Timeline reads | Use the Session’s branch query facade on `main`, with a fixed published cutoff. Read only the adopted input identity, its user content or Goal objective, and the adopted model fields (§0.1). | | Configuration | Existing named Settings and row source declaration, user scope only (A.3/A12). Read settings.read({source:"session-title",scope:"user"}) at each decision and use its validated/defaulted document directly. | -| Metadata/notice | The process `store` face provides `title` and `setTitle(id, change)`; `setTitle` commits the title the change returns and answers the revision, with errors `rejected`/`not_found`/`storage` ([SessionStore](SessionStore.md)); the v3 list fields are `title`/`titleSource`/`titleRevision`. After each commit SessionStore calls `session_broadcast::notify`, and Rpc forwards the record to attached v3 clients as `session.notice {sessionId, source, kind, data}` (C6 #49/#85, [Session broadcast notices](../appserver/session-notices.md)). | +| Metadata/notice | The process `store` face provides `title` and `setTitle(id, change)`; `setTitle` commits the title the change returns and answers the revision, with errors `rejected`/`not_found`/`closed`/`storage` ([SessionStore](SessionStore.md)); the v3 list fields are `title`/`titleSource`/`titleRevision`. After each commit SessionStore calls `session_broadcast::notify`, and Rpc forwards the record to attached v3 clients as `session.notice {sessionId, source, kind, data}` (C6 #49/#85, [Session broadcast notices](../appserver/session-notices.md)). | | Auxiliary request | The profile's model-selection owner implements AuxiliaryModel and its named `auxiliaryModel.complete` HostDispatch/catalog binding: Provider in the product profile, ConfiguredModels in the model-config profile. Inject it through ordinary C4 dependencies; credentials stay with that owner ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)). | | Policies | A1–A12 define the first implementation. Appendix D requires public-flow acceptance; documentation CI alone is not runtime acceptance. | @@ -84,7 +84,7 @@ The fixed snapshot ends at returned T, not necessarily at N. Its first adopted e supplies text. With model=null, the latest ContextConfiguredData.settings in that snapshot supplies providerId/modelId; without an adopted model, generation uses the excerpt fallback in §3.3 instead of the profile's current default. -The sequence diagrams in this appendix predate the `setTitle` change callback and show `setTitle(expected revision, title)`; the target call is `setTitle(id, change)` ([SessionStore](SessionStore.md)). +The sequence diagrams show the change callback: `setTitle(id, change)`; the owner serializes the writes and answers the new revision ([SessionStore](SessionStore.md)). Cancellation before setTitle handover stops work without writing. The handover is the setTitle call itself: from then on SessionStore settles its own atomic operation, and a lost reply does not authorize @@ -147,7 +147,7 @@ flowchart TB CC -->|"Session model"| MEM CONF --> MEM CFG --> MEM - MEM -->|"setTitle, expected revision"| MD + MEM -->|"setTitle(id, change)"| MD classDef new fill:#d3f9d8,stroke:#2b8a3e,color:#000 ``` @@ -174,7 +174,7 @@ sequenceDiagram ST->>Queries: select first adopted eligible id, its text and model at fixed T >= N ST->>Gen: generate from adopted input Gen-->>ST: title or excerpt fallback - ST->>Meta: setTitle(expected r, auto) + ST->>Meta: setTitle(id, change auto) Meta-->>SB: title notice ``` @@ -192,8 +192,8 @@ sequenceDiagram CLI->>Rpc: session.rename sessionId, title Rpc->>ST: resolve Session, sessionMethods call ST->>Meta: metadata, revision r - ST->>Meta: setTitle(expected r, manual) - Meta-->>ST: revision r+1 + ST->>Meta: setTitle(id, change manual) + Meta-->>ST: revision + 1 Note over Meta: title notice on the Session broadcast ST-->>Rpc: title, titleSource manual, revision ``` @@ -256,7 +256,7 @@ sequenceDiagram Note over ST: apply, Session published ST->>Meta: metadata: revision 0? ST->>ST: rename's text rule, then maxLength - ST->>Meta: setTitle(expected 0, manual) + ST->>Meta: setTitle(id, change manual) Meta-->>ST: revision 1 Note over Meta: title notice on the Session broadcast ``` @@ -281,10 +281,10 @@ sequenceDiagram participant R as rename participant Meta as SessionStore metadata G->>Meta: metadata, revision r, no title - R->>Meta: setTitle(expected r, manual) - Meta-->>R: r+1 - G->>Meta: setTitle(expected r, auto) - Meta-->>G: conflict + R->>Meta: setTitle(id, change manual) + Meta-->>R: revision + 1 + G->>Meta: setTitle(id, change auto) + Meta-->>G: rejected Note over G: automatic title discarded ``` @@ -449,6 +449,7 @@ omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remain | Settings read fails | Automatic: no write, diagnostic, failure counted; rename: `storage_failed`. No fallback document | | `setTitle` `rejected` on automatic write | Discarded (diagnostic) | | `setTitle` `storage` | Automatic: failure counted; rename: `storage_failed` | +| `setTitle` `closed` | Rename: `service_reloading`; the attempt is retried on the replacement generation. Automatic: the attempt ends | | Unknown Session on rename | `session_not_found` | | SessionTitle reloading | Before handover: service_reloading, no rename. After handover/lost reply: read metadata; do not infer no commit or repeat the write | | Cancellation | Before handover abort the auxiliary call and discard; after store admission, S5b owns the atomic outcome | diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index c49d9d3476..920038bc2c 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -467,7 +467,7 @@ The order is fixed, and the Session part is the only participant that both waits `recognize` only when its own view does not already cover the path. 2. The node answers the resolution, the node facts, and either a `worktree` candidate or a `discoveryError`. -3. A candidate goes to `store.associateWorktree {sessionId, repository, root, subtree}`. That +3. A candidate goes to `store.associateWorktree {id, repository, root, subtree}`. That operation writes the directory record and the usage association together and answers `{}` only after both commit, deduplicated by repository and root and by Session and directory. A failed write is a `discoveryError` for the caller: the range is not published, and the user can still @@ -697,8 +697,8 @@ read-only access. Superseded by [the SessionStore contract](plugins/SessionStore.md). The Session repository operations, the title and association operations, the worktree removal and the error kinds are -defined there; the Rust `Store` binding type no longer exists and the service is marked on the -store owner. +defined there; the Rust `Store` binding type no longer exists and the face is the owner's +hand-written `HostDispatch`. ## 6. Provider, binding, and the owners that use each operation diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index e34eff2573..b32f6b9691 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -310,7 +310,7 @@ skillsConfig.get() -> {instructions?} -- Skills 的 factory 文本;null 表示内置 collaborationConfig.get() -> {leaderDescription?, memberDescription?} -- Collaboration 的 factory 文本;null 表示内置 -store.associateWorktree {sessionId, repository, root, subtree} -> {} +store.associateWorktree {id, repository, root, subtree} -> {} -> error {code: failed, message} -- 路径按 §1 是 UTF-8 字符串;一次写入仍由 SessionStore 的原子事务保证 ``` diff --git a/docs/design/worktree-access.md b/docs/design/worktree-access.md index d3fa6631e6..4675d4ddd9 100644 --- a/docs/design/worktree-access.md +++ b/docs/design/worktree-access.md @@ -192,7 +192,7 @@ exec cwd=/repo-wt -> Known root -> Existing command approval 删除语义不适用于用户代码。两者均不能直接作为 worktree 记录使用。 - **Needed:** SessionStore 拥有目录记录、原子去重关联写入和 Session 删除时的解除关联; 目录候选不因最后一条使用关联被删而消失。它把写暴露为进程数据面 - `store.associateWorktree {sessionId, repository, root, subtree}`,路径是 UTF-8 + `store.associateWorktree {id, repository, root, subtree}`,路径是 UTF-8 字符串;Rust 消费者调用同一个方法,不直接读写表。 - **Ordering impact:** 关联写入不产生 Timeline 事实;与删除串行协调,已删除或正在删除的 Session 不能被迟到写入重新关联。native 格式改变须由存储所有者作独立格式决定,遵守 From eb4ec4fdb5321d5f8b2c307098699b04e859bb75 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 14:56:13 +0800 Subject: [PATCH 12/19] docs(storage): finish the title wording SessionTitle: the revision-check sentences and diagram labels are replaced by the change callback, the A.4 listen step starts on activated(), and closed maps to service_reloading. The title metadata doc names title everywhere, and its binding paragraph no longer calls read. Refs #2018 Refs #2015 --- .../design/appserver/session-title-metadata.md | 18 +++++++++--------- docs/design/plugins/SessionTitle.md | 8 ++++---- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index 14527b7de9..2b73b65c96 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -43,7 +43,7 @@ protocol version. ---------------------------- -------------------------------------------------------------- SessionTitle (Session part) SessionStore (existing plugin) inject 'store' store (HostDispatch) - read --------------------------> read -> metadata() ------------------+ + title -------------------------> title -> metadata() ------------------+ setTitle ----------------------> setTitle -> set_title() | | v title writer: one write at a time ---> SqliteStorage @@ -108,8 +108,8 @@ The `store` face, process scope, control node only, no instance key, provided by ### 4.2 Rust -Rust consumers inject the `store` owner and call `title`/`set_title`. The pre-migration binding was `SessionMetadataService`, the typed binding of `sessionMetadata`; the target calls -`read` and `set_title`. The binding is the existing dispatcher, published at both its typed key +Rust consumers inject the `store` owner and call `title`/`set_title`; the target operations are +`title` and `set_title`. The binding is the existing dispatcher, published at both its typed key and `host_key("store")` delegate directly to the same SessionStore owner. The existing `SessionMetadata` reply type is unchanged. @@ -213,8 +213,8 @@ Rpc never calls `setTitle` and gains no method. How each error reaches clients: | Event | Title | | --- | --- | | Session created | None, revision 0; no row is written | -| Load, unload, close, restart | Unchanged: the title is stored with the Session's rows, not with its instance. `read` and `setTitle` work on a Session that is not loaded; their notices are dropped, as nobody listens | -| `session.delete` (S5c) | Removed in S5c's single delete transaction, before the Session record. Afterwards `read` and `setTitle` fail `not_found` | +| Load, unload, close, restart | Unchanged: the title is stored with the Session's rows, not with its instance. `title` and `setTitle` work on a Session that is not loaded; their notices are dropped, as nobody listens | +| `session.delete` (S5c) | Removed in S5c's single delete transaction, before the Session record. Afterwards `title` and `setTitle` fail `not_found` | | Creation rollback | The same transaction as a delete; it removes a row that a racing write committed | | `session.fork` (S5c) | Not copied ([SessionTitle A7](../plugins/SessionTitle.md#appendix-e-assumptions)): the fork starts untitled at revision 0 | | SessionStore or SqliteStorage reload | Settles as in §6. Consumers of `store` reload with SessionStore ([ADR 002](../../adr/002-plugin-scope.md) D3), which SessionTitle §1 accepts. SessionStore reloads only with SqliteStorage, which has no dependencies | @@ -262,7 +262,7 @@ CREATE TABLE session_metadata (session_id TEXT NOT NULL PRIMARY KEY REFERENCES a `settings_documents` belongs to Settings. Columns added to `agent_sessions` change its stored SQL, so they need a new version as well, and they would mix a mutable value into the creation record. - **Why one row per Session.** Only the current title and revision are read. No decision uses earlier titles. -- **Index.** The primary key serves `read`, `setTitle`, the list join and the delete. No other index. +- **Index.** The primary key serves `title`, `setTitle`, the list join and the delete. No other index. | Store found | Action at startup, in the existing admission transaction (`IMMEDIATE`, before writable PRAGMAs) | | --- | --- | @@ -283,7 +283,7 @@ after the upgrade commits (S5a's log line, with the version the store came from) | --- | --- | | Identity | `dyn HostDispatch` at `host_key("store")`, provided by SessionStore; `register_shared("store")` in App Server's service catalog, beside `sessions` and `settings` | | Use | A C4 Session part declares `inject: ['store']` and calls `ctx.use('store')`, the path `settings` takes from a Session part ([settings-owner fixture](../../../runtime/fixtures/settings-owner.ts)). Types are in [npm/plugin.d.ts](../../../npm/plugin.d.ts) | -| Modes | `read` and `setTitle` are both `async` | +| Modes | `title` and `setTitle` are both `async` | | Writer | The service carries no caller identity, as for `settings` (AGENTS.md rule 11). SessionTitle is the title's one writer by design ([SessionTitle §2](../plugins/SessionTitle.md#2-data-and-state)); other packages only read | | Reload | A consuming row reloads with SessionStore. SessionStore reloads only with SqliteStorage, so no directory part that never reloads is needed, unlike `sessions`, whose index reloads with Settings ([sessions D1](sessions-service.md#3-decisions)) | | Missing provider | A daemon without a native store has no SessionStore, so a row that injects `store` stays Pending under the existing rules; native Sessions continue | @@ -330,12 +330,12 @@ None. S5b uses C6's `notify`, the existing service catalog and `HostDispatch`, a ## 16. Acceptance (flow tests) -1. `setTitle` commits and returns the next revision; `read` returns it. Two v3 clients attached over IPC and +1. `setTitle` commits and returns the next revision; `title` returns it. Two v3 clients attached over IPC and WebSocket each receive exactly one `session.notice` per commit, in commit order, with `data` equal to the list's title fields. A rejected change and an unknown Session announce nothing. 2. Concurrent writers: every commit is announced once, in increasing `titleRevision` order. 3. A clear (`null`) commits a revision with no title and announces nulls. -4. `read` and `setTitle` of a Session that was never created, or was deleted: `not_found`. +4. `title` and `setTitle` of a Session that was never created, or was deleted: `not_found`. 5. A failed transaction (a disposable store with a failing trigger): `storage`, no notice, state unchanged; the next write at the same revision commits. 6. A `setTitle` call whose caller awaits the reply and then drops it, while the write is held before its transaction, diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 69f8246849..e2dff01b20 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -223,7 +223,7 @@ selection, persistence or fallback. Its only method is async `generate(request, After an unavailable or failed service call, SessionTitle uses the adopted model through `auxiliaryModel`. A missing model, auxiliary error, empty normalized output or the shared 30 s -generation deadline uses the input excerpt as a fallback title: collapse whitespace, trim and apply the configured Unicode length bound while preserving punctuation, and write through the same revision-checked +generation deadline uses the input excerpt as a fallback title: collapse whitespace, trim and apply the configured Unicode length bound while preserving punctuation, and write through the same change metadata operation with source `auto`. Account-service failure alone does not consume one of the three failed attempts that cannot complete a metadata write. Session closing or explicit cancellation never falls back. The deadline includes both generation paths; timing out cancels and joins the active call before @@ -288,7 +288,7 @@ sequenceDiagram Note over G: automatic title discarded ``` -The revision check is the recheck: a manual title always wins. +The change sees the current title: a manual title always wins. | Scenario | Order | Outcome | Owner | | --- | --- | --- | --- | @@ -329,7 +329,7 @@ The first eligible input's text is sent only to the generation paths selected by | Rule | How this document complies | | --- | --- | -| Principles §4 rule 1 (commands for others' state) | The title is SessionStore's process-level state with no Timeline; SessionTitle changes it only through SessionStore's typed `setTitle`, and SessionStore decides through its revision check (principles §4 rule 9). | +| Principles §4 rule 1 (commands for others' state) | The title is SessionStore's process-level state with no Timeline; SessionTitle changes it only through SessionStore's typed `setTitle`, and SessionStore serializes the writes; a manual title always wins inside the change (principles §4 rule 9). | | Principles §4 rule 2 (handover) | SessionTitle reads an input only after its handover (`input/applied`) and never acts on the input itself. | | Principles §4 rule 3 (before callbacks only) | No intervention before a write; rename rules are checked by SessionTitle's own method, not at an entry. | | Principles §4 rule 4 (no business meaning in core) | The delivered C6 Session broadcast notice in §9 is a generic record for any owner of process-level Session state. | @@ -407,7 +407,7 @@ omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remain | Step | Path | | --- | --- | -| Listen | The Session's copy of the part listens to its Session's `session/{sessionId}` from `apply`, filters main input/applied, registers an owned task and returns; SessionScope's `closing()` or copy cleanup ends owned work | +| Listen | The Session's copy of the part starts observing on SessionScope's `activated()` (the Session is published), listens to its Session's `session/{sessionId}`, filters main input/applied, registers an owned task and returns; `closing()` or copy cleanup ends owned work | | Eligibility | C4 creation snapshot: `interactive !== false && collaborationRole === "leader"` for generation; native omission means true. A requested initial title (`initialTitle`, §3.4) is written for interactive and non-interactive Sessions alike: it needs no model, and it is the caller's own text | | Trigger | On `input/applied` at `N`: skip if not eligible, disabled, in flight or failed attempts ≥ 3 (A5); otherwise start a generation task owned by the plugin's lifetime | | Check | `store.title({id})`: the change decides from the current title and revision; a `rejected` change discards | From f723d8536798cf9fc7a7a52ebd8b58c96ea3a4a8 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 15:37:27 +0800 Subject: [PATCH 13/19] docs(storage): link the owner contracts from the architecture tree The five owners have no architecture page of their own, so their contracts stay in the design tree: the architecture README names each of them, and the Attachments pages link the SessionFiles contract instead of the retired session-files interface. Refs #2018 Refs #2015 --- docs/architecture/rust-agent/plugins/Attachments.md | 2 +- docs/architecture/rust-agent/plugins/README.md | 2 +- docs/design/plugins/Attachments.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/architecture/rust-agent/plugins/Attachments.md b/docs/architecture/rust-agent/plugins/Attachments.md index 3ba42a0584..9e26a49cc1 100644 --- a/docs/architecture/rust-agent/plugins/Attachments.md +++ b/docs/architecture/rust-agent/plugins/Attachments.md @@ -11,7 +11,7 @@ The model reads that path with `read` like any file. Design: | Service | Purpose | | --- | --- | | `S:SessionIdentity` | The Session a put stores for; Rpc already resolved it from `sessionId`. | -| `P:SessionFiles` | SessionStore's `sessionFiles` data face (§9 of its owner contract). In this graph it is a graph-only fixture that stores nothing. | +| `P:SessionFiles` | SessionStore's `sessionFiles` data face ([SessionFiles](../../../design/plugins/SessionFiles.md)). In this graph it is a graph-only fixture that stores nothing. | | `S:SessionMethods` | Register the `attachment` namespace from `apply`, until this part unloads. | ## Method diff --git a/docs/architecture/rust-agent/plugins/README.md b/docs/architecture/rust-agent/plugins/README.md index 1fd80891c6..cca2233885 100644 --- a/docs/architecture/rust-agent/plugins/README.md +++ b/docs/architecture/rust-agent/plugins/README.md @@ -52,7 +52,7 @@ App Server optional plugins are outside this local-execution profile. [Web](../. The product also installs [ImageUnderstanding](../../image-understanding.md) next to Modality; its Session part consumes the process target and auxiliary-model services outside this local-execution profile. -Process infrastructure rows are also outside this local-execution index. [UiExtensions and UiResources](../../client-ui-extensions.md) own client UI content and Session file publications. `UiHost` owns UI leaves: per leaf, a `UiLeaf` plugin whose life is the rutis session with the interactive `dimcode` process. Its contract is [Tui design §3.6](../../../design/plugins/Tui.md#36-ui-registry-and-ui-leaves) and its current assembly is in the generated [App Server services](../generated/app-server/services.md). The leaf runs its own `Tui` in the CLI's client tree; it is not a local-execution capability. The language runtimes' connection rows, `session-node` and `py`, are process infrastructure too: each starts its runtime and mounts the rutis session its foreign rows run on ([How Dim uses rutis A.4](../../../design/rutis-usage.md#a4-runtimes-and-sessions)). +The session storage owners are outside this local-execution index; their contracts are [SessionStore](../../../design/plugins/SessionStore.md), [SessionFiles](../../../design/plugins/SessionFiles.md), [ManagedWorktrees](../../../design/plugins/ManagedWorktrees.md), [SqliteStorage](../../../design/plugins/SqliteStorage.md) and [SessionTitle](../../../design/plugins/SessionTitle.md). Process infrastructure rows are also outside this local-execution index. [UiExtensions and UiResources](../../client-ui-extensions.md) own client UI content and Session file publications. `UiHost` owns UI leaves: per leaf, a `UiLeaf` plugin whose life is the rutis session with the interactive `dimcode` process. Its contract is [Tui design §3.6](../../../design/plugins/Tui.md#36-ui-registry-and-ui-leaves) and its current assembly is in the generated [App Server services](../generated/app-server/services.md). The leaf runs its own `Tui` in the CLI's client tree; it is not a local-execution capability. The language runtimes' connection rows, `session-node` and `py`, are process infrastructure too: each starts its runtime and mounts the rutis session its foreign rows run on ([How Dim uses rutis A.4](../../../design/rutis-usage.md#a4-runtimes-and-sessions)). ## Reading and maintaining these pages diff --git a/docs/design/plugins/Attachments.md b/docs/design/plugins/Attachments.md index a79c2fcca0..6d4fd79cdb 100644 --- a/docs/design/plugins/Attachments.md +++ b/docs/design/plugins/Attachments.md @@ -107,7 +107,7 @@ alone grants no access. Attachment methods are user actions under | Owner | Requirement | Ordering impact | | --- | --- | --- | -| SessionStore | [Path import and authorized bounded reads](../appserver/session-files.md#9-interface), using one owner through native and wire bindings | Reply after file and ownership commit; fork/delete preserve live ownership | +| SessionFiles | [Path import and bounded page reads](SessionFiles.md), using one owner through native and wire bindings | Reply after file and ownership commit; fork/delete preserve live ownership | | WebEntry / Rpc | [HTTP reception](../web-workspace.md#session-file-http-api) and local-only path admission | Temporary file remains available through import settlement | | ModelProvider / Aimux | A.4 and [request execution](../../architecture/rust-agent/plugins/ModelProvider.md#durable-images-at-model-execution) | Resolve images after effective-context and capability selection | From 512b24001652033895c2e040f95e3e93ab42ef4a Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 17:11:03 +0800 Subject: [PATCH 14/19] docs(storage): point superseded sections at the owner contracts The paragraphs this PR supersedes in resource faces, service faces, resource-owner-operations, session-title-metadata, SessionTitle, worktree-management and worktree-access become one-line pointers; their headings stay. The Supersedes lists match the changed sections. SessionStore.fork reads the source body and decides the target text under the fork exclusion, and the target body and rows are written by the last batch transaction. The contract names the process-face query and sessionConfig with {id}. ManagedWorktrees maps each store refusal to its own answer and the caller's next step. The setTitle example drops the cancellation argument the binding does not take. Refs #2018 Refs #2015 --- .../appserver/session-title-metadata.md | 126 ++---------------- .../contracts/resource-owner-operations.md | 6 +- docs/design/plugins/ManagedWorktrees.md | 2 +- docs/design/plugins/SessionStore.md | 22 +-- docs/design/plugins/SessionTitle.md | 10 +- docs/design/plugins/SqliteStorage.md | 6 +- docs/design/resource-faces.md | 105 ++------------- docs/design/service-faces.md | 12 +- docs/design/worktree-access.md | 2 +- docs/design/worktree-management.md | 33 +---- 10 files changed, 46 insertions(+), 278 deletions(-) diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index 2b73b65c96..458ffd92ea 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -1,6 +1,6 @@ # SessionStore title metadata -The [SessionStore contract](../plugins/SessionStore.md) supersedes the title interface: `store.title` reads the title with its source and revision, and `store.setTitle(id, change)` takes the caller's change, serializes the write, commits the returned title and announces it. The revision is the owner's; the interface has no `expectedRevision`. The data, notice, list and sequence paragraphs below describe the stored title and remain in force. +The [SessionStore contract](../plugins/SessionStore.md) supersedes the title interface: `store.title` reads the title with its source and revision, and `store.setTitle(id, change)` takes the caller's change, serializes the write, commits the returned title and announces it. The revision is the owner's; the interface has no `expectedRevision`. The data, notice and list paragraphs below describe the stored title and remain in force. Status: Implemented in roadmap item S5b ([#60](https://github.com/arcships/dim/issues/60), [#96](https://github.com/arcships/dim/pull/96)), after C6 ([#49](https://github.com/arcships/dim/issues/49), @@ -19,16 +19,12 @@ channel ([C6](session-notices.md)), and Rpc shows the title in protocol v3 Sessi - **Data.** A revision counter (0 means never written) and either no title or a title `{text, source}` with source `auto` or `manual`. Clearing keeps the counter, so a revision never repeats. -- **Write.** `setTitle {id}` plus a change callback that receives the current `{revision, title}` and returns the next - title or its own refusal. SessionStore serializes the write, commits the returned title as the next revision and - answers it; failures are `rejected`, `not_found` or `storage`. The call is the handover: SessionStore admits the - write when called, unless it is closing, and settles it itself; dropping the call only loses the reply. +This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). - **Notice.** After each commit, `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}`, in commit order. - **Lists.** Protocol v3 `session.summaries` entries carry `title`, `titleSource` and `titleRevision`. -- **Binding.** The process service `store` (`title`, `setTitle`), provided by SessionStore, reaches TypeScript through - the existing service catalog. +This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). - **Lifecycle.** A delete removes the title in S5c's delete transaction; a fork does not copy it (SessionTitle A7); a restart keeps it. Reading or writing a title never loads the Session. - **Format.** Native store v16: one new table, upgraded in place from v15, and from v13 through v15's step. @@ -84,81 +80,16 @@ protocol version. ## 4. Operations ### 4.1 Language-neutral (ADR 002 D5) - -The `store` face, process scope, control node only, no instance key, provided by SessionStore. - -| Method | Mode | Request | Reply value | Errors | -| --- | --- | --- | --- | --- | -| `title` | async | `{id}` | `{revision, title: {text, source} \| null}` | `not_found`, `closed`, `storage` | -| `setTitle` | async | `{id}` plus the change callback | `{revision}`: the committed revision | `rejected`, `not_found`, `closed`, `storage` | - -- Replies use one envelope, `{ok: true, value}` or `{ok: false, error: {code, message}}`, as `settings` does. -- Neither method loads the Session. `title` reads committed state and does not wait for the title writer (§5). -- The change returns the next title or `null` to clear; the owner stores what the change returns. A caller's change - decides the manual-title rule and the clear, so an omission never erases a user's title. -- A malformed call (unknown method, not exactly one request object, an unknown field, a wrong type or a missing - field) is a bridge error, as for `settings`: it is a caller's programming error, not an outcome of the write. - -| Code | When | State after | -| --- | --- | --- | -| `not_found` | The store holds no record of the Session: never created, deleted, or rolled back. A stored Session that is closed or not loaded is found | Unchanged | -| `rejected` | The change refused with its own `code` and `message`; the manual-title rule is the change's | Unchanged, no notice. Act on the change's code | -| `storage` | The transaction or the file write failed | Unchanged, no notice | -| `closed` | The call arrived after SessionStore started closing (§6) | Unchanged, no notice; retry on the replacement generation | +This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). ### 4.2 Rust - -Rust consumers inject the `store` owner and call `title`/`set_title`; the target operations are -`title` and `set_title`. The binding is the existing dispatcher, published at both its typed key -and `host_key("store")` delegate directly to the same SessionStore owner. -The existing `SessionMetadata` reply type is unchanged. - -`set_title` is a regular function returning the owner's wait future. Calling it admits the write -immediately, before that future is polled; dropping the future loses only the reply. The binding -adds no asynchronous wrapper before handover, cancellation point, read, or second title writer. +This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). ## 5. setTitle sequence - -```text - caller SessionStore SQLite Session channel - ------ ----------------------------------------------- ----------------- --------------- - setTitle(S, C) ----> SessionStore closing? -> closed at once, nothing written - admit: start the write task <== handover (the call) - | (SessionStore owns the task; dropping the - | call from here on only loses the reply) - | wait for its turn at the title writer - | (one write at a time) - +-- BEGIN IMMEDIATE ---------------------------> revision of S - | no Session: not_found, rollback - | change refuses: rejected, rollback - | write the next revision and T - +-- COMMIT ------------------------------------> committed, or storage - | committed only: - | notify(S, {SessionStore, title, - | {title, titleSource, titleRevision: next}}) ------------------> Notice - | end its turn - <---- {revision: next} ---+ -``` - -`notify` runs after the commit and before the next write takes its turn, so the notices of one Session reach its -channel in commit order. It never runs under the SQLite connection lock: listener code does not run under the database -lock (the rule in [timeline.rs](../../../crates/dim-app-server/src/storage/timeline.rs)). +This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). ## 6. Handover, cancellation and settlement - -This settles the boundary that SessionTitle §0 left to S5b. - -| Point | Rule | -| --- | --- | -| Before the call | The caller's own work. Cancelling it before the call writes nothing | -| The call | The handover is SessionStore receiving the call: before it returns, `setTitle` admits the write and starts it as SessionStore's own task, or, once SessionStore is closing, fails `closed` without writing. In Rust `set_title` is a plain function that does this and returns a future of the reply. That future only awaits the task, so dropping it detaches the reply, never the write. The named service calls it inside `invoke`, so a JavaScript call is handed over once the host receives it | -| After the call | SessionStore settles the write itself: it commits and announces, or fails and writes nothing. Dropping the call, unloading the calling row or losing the reply neither cancels nor undoes it. `setTitle` has no cancel action | -| Lost reply | The caller reads with `title`. It does not repeat the write blindly: a second change would commit another revision ([SessionTitle Appendix C](../plugins/SessionTitle.md#appendix-c-errors-and-recovery)) | -| SessionStore unload | Its disposer first stops admission: from then on a call fails `closed` at once and writes nothing. It then waits until every admitted write, the one in its turn and those waiting for theirs, has committed and announced or failed. Only then does it close Session files and the Timeline writer, and SqliteStorage, which unloads after SessionStore, closes the connection. The notices follow C6 delivery: once the Session is no longer loaded, nobody listens and they are dropped. Nothing is retried after a reload | - -Rejected: a cancel action that works until the transaction starts. It would only move the uncertainty, since a caller -that drops the call still has to read to learn the outcome; and a JavaScript caller cannot cancel a host call in rutis -([sessions §2](sessions-service.md#2-spike-findings), finding 5). +This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). ## 7. The title notice @@ -220,17 +151,7 @@ Rpc never calls `setTitle` and gains no method. How each error reaches clients: | SessionStore or SqliteStorage reload | Settles as in §6. Consumers of `store` reload with SessionStore ([ADR 002](../../adr/002-plugin-scope.md) D3), which SessionTitle §1 accepts. SessionStore reloads only with SqliteStorage, which has no dependencies | ## 10. Timing and conflicts - -| Scenario | Outcome | -| --- | --- | -| Two changes in flight | The owner serializes them; the second change sees the first title and decides; a refusal announces nothing | -| Writes to different Sessions | Run one at a time by the one title writer; each commits in its own transaction | -| `setTitle` and `session.delete` | The store's write transactions order them: a commit first is removed by the delete; a delete first makes the write `not_found` | -| `setTitle` and `session.fork` | Independent: the fork copies no title | -| `setTitle` and Timeline appends | Independent rows; each uses its own transaction on the one store connection | -| Notice and list read on one connection | §8: the higher `titleRevision` wins | -| `setTitle` with no client attached | Committed; the notice is dropped; the next list shows the title | -| The same text written again | Commits a new revision and announces it ([SessionTitle Appendix B](../plugins/SessionTitle.md#appendix-b-full-conflict-table): a duplicate rename rewrites) | +This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). ## 11. Storage format @@ -308,7 +229,7 @@ SessionTitle gate. | Rule | How this design complies | | --- | --- | -| [Principles](../../architecture/rust-agent/principles.md) §4 rule 1 (commands for others' state) | The title is SessionStore's process state, outside any Timeline. Others change it only through SessionStore's typed `setTitle`, and SessionStore decides through its revision check | +| [Principles](../../architecture/rust-agent/principles.md) §4 rule 1 (commands for others' state) | The title is SessionStore's process state, outside any Timeline. Others change it only through SessionStore's typed `setTitle`, and the change decides the next title while the owner serializes the writes | | §4 rule 2 (handover) | The handover is explicit: the call (§6). Before it the caller can cancel; after it only SessionStore settles the write | | §4 rule 3 (before callbacks) | Not applicable: no before callback | | §4 rule 4 (no business meaning in core) | SessionStore stores text and source without interpreting them; the notice is C6's generic record; Rpc copies the fields | @@ -381,31 +302,4 @@ fixture](../../../runtime/fixtures/session-metadata.ts); items 6 and 12 hold the | D14 | Admission at the call; unload stops admission, then waits for every admitted write | Admitting a write when it takes its turn, and failing the writes still waiting at unload (the first implementation) | That left a handed-over write without a definite admission: whether it ran depended on whether its task reached the title writer before the disposer did, and a call that arrived during unload was neither refused nor admitted until the write in progress ended. Admitting at the call makes both the handover and the refusal immediate. Titles are written rarely, so waiting for the admitted ones is short. Session files' puts are admitted the same way | ## Appendix A. Rust binding - -In `dim_app_server::storage`: - -```rust -#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum TitleSource { Auto, Manual } -#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct Title { pub text: String, pub source: TitleSource } -#[derive(Clone, PartialEq, Eq, Serialize)] -pub struct SessionMetadata { pub revision: u64, pub title: Option<Title> } -/// The title fields of a v3 Session list entry and the title notice's data. -#[derive(Clone, Default, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct TitleFields { pub title: Option<String>, pub title_source: Option<TitleSource>, pub title_revision: u64 } -#[serde(tag = "code", rename_all = "snake_case")] -pub enum StoreError { Rejected { reason: String, message: String }, NotFound { message: String }, Closed, Storage { message: String } } - -impl SessionStore { - pub async fn title(&self, id: &str) -> Result<SessionMetadata, StoreError>; - /// Admits and starts the write when called, or fails `Closed` once - /// SessionStore is closing: the call is the handover. Dropping the - /// returned future loses only the reply; the hand-written method table - /// calls this plain fn eagerly, so a wire caller that drops the reply still commits. - pub fn set_title(&self, id: &str, change: ChangeFn) - -> impl Future<Output = Result<u64, StoreError>> + Send + 'static; -} -``` +This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index ca7dd6e3b4..71e3664836 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -33,11 +33,7 @@ Superseded by the owner contracts. The Agent records belong to [Agents and Colla ### Credential values in replies -The Provider and Settings owners' record operations return the stored fields their contracts name ([Provider](https://github.com/arcships/dim/pull/2096), [Settings](https://github.com/arcships/dim/pull/2094)). A stored secret reference is returned as a reference; Provider resolves it through its configured secret host and obtains managed OAuth credentials from their existing owner. - -Provider's record read returns inline credentials only in the projection its contract names, and its business replies omit them. Settings' document read and import return the complete stored document, including original values in `mcp-secrets`; its replace answers the committed version. MCP reads its credential document through Settings and uses it to establish connections. The business API `settings.read` serves declared sources and excludes the native `mcp-secrets` document. - -The exception is scoped to the Provider and Settings owners' own operations, not to `sqliteStorage`: the engine's row operations are its crate-private implementation and are not callable by plugins. +This section is superseded by the Provider and Settings contracts ([#2096](https://github.com/arcships/dim/pull/2096), [#2094](https://github.com/arcships/dim/pull/2094)). ## Settings diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md index 8e5fb52a4a..bdfb4af0bb 100644 --- a/docs/design/plugins/ManagedWorktrees.md +++ b/docs/design/plugins/ManagedWorktrees.md @@ -118,7 +118,7 @@ None. `worktree.list`, `worktree.remove` and `worktree.prune` keep their request ## Supersedes -- [Managed worktrees](../worktree-management.md) §5: the list/remove/prune composition under the store's removal operations and the branch rule for a never-adopted worktree. §3 and §4 remain the source for creation and the directory records. +- [Managed worktrees](../worktree-management.md) §5: the removal paragraph is replaced by a pointer to this contract. ## Verification diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 0037b35c10..0e6370d2c4 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -15,6 +15,7 @@ SessionStore owns: - **Worktree records.** A recorded directory, its last-use time and the Session associations that point into it. - **The Session exclusion.** One lock that keeps creation, fork, deletion, association and worktree removal from observing each other's partial state. - **The Timeline storage engine.** The admitted batch queue, the grouped commit, paging, snapshots and release, executed over the Session rows. `timelineStore` publishes the same engine per Session; the Session face belongs to SessionScope. +- **The Session reads.** `query` and `sessionConfig` exist only on the process `store`; both take `{id}` and serve loaded and unloaded Sessions. No Session-scoped or `timelineStore` operation carries them. Callers keep: @@ -30,7 +31,7 @@ Callers keep: | --- | --- | --- | | Create an admitted Session and its optional worktree association | No: the rows, the owner row, the main branch, the catalog row and the association are one transaction; a partial write would publish a Session without its rows or an association without its Session | `create` | | Close a Session, then remove its output directories and rows | No: output removal, visible rows and Timeline rows must run under the Session exclusion and in this order; a caller composing them could delete a row a concurrent creation still names | `delete` | -| Copy a source Session's rows at a cut, deciding the target text from the source's exact text | No: the source text must be read and the target text written in one transaction, and the lifecycle owner's decision must run under the fork's exclusion | `fork` with a text callback | +| Copy a source Session's rows at a cut, deciding the target text from the source's exact text | No: the source body must be read and the target text decided under the fork's exclusion, and the target body and rows are written by the last batch transaction | `fork` with a text callback | | Read a stored Session's creation origin and leader link for an attach reply | No: the caller has no row access | `creationRecord` | | Read the Agent that owns a stored Session before its delete notice | No: the caller has no row access | `owner` | | Ask whether an id has stored rows without loading a Session | No: the check spans five tables | `hasRecords` | @@ -79,7 +80,7 @@ let change: ChangeFn = Arc::new(move |current: TitleState| { let next = decide(current.revision, current.title.as_ref(), &text); // business rules Box::pin(async move { Ok(next) }) }); -let next = store.setTitle(SetTitle { id }, change, cancelled).await?; +let next = store.setTitle(SetTitle { id }, change).await?; ``` ManagedWorktrees removes a directory: the owner holds the exclusion while the caller's Git step removes the root, and deletes or keeps the record by that step's result. @@ -113,7 +114,7 @@ Every operation takes one request object and answers one reply object. Writes ar | `hasRecords` | Whether an id has any stored row | `{id}` | `{exists}` | None | `closed`, `storage` | | `sessionConfig` | A stored Session's decoded configuration | `{id}` | `{config?}` | None | `not_found`, `closed`, `storage` | | `catalog` | One stored Session page | `{request, agent?, version, hosts, closed}` | the stored page | While the page is read | `invalid`, `cancelled`, `closed`, `storage` | -| `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not) | `{scope, query, page?}` | the query result | While the page is read | `storage`, `cancelled`, `closed` | +| `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not) | `{id, query, page?}` | the query result | While the page is read | `storage`, `cancelled`, `closed` | | `grants` | The Session's grant set | `{id}` | `{grants}` | None | `closed`, `storage` | | `addGrant` | Add one grant, never downgrading a write grant | `{id, path, kind, mode}` | `{}` | None | `not_found`, `invalid`, `closed`, `storage` | | `removeGrant` | Remove one grant; an absent grant counts as removed | `{id, path}` | `{}` | None | `closed`, `storage` | @@ -150,7 +151,7 @@ When a change, text or removal callback refuses, the operation answers `rejected | --- | --- | --- | --- | --- | --- | | `create` | Validate the id, take the exclusion, validate the workspace, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller keeps the id it supplied and decides whether to publish or delete the Session | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | | `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove visible and Timeline rows, schedule the file sweep | Before the first commit: every row stays. After: the steps run to their end | The work continues under the owner's task; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | -| `fork` | Take the exclusion, read the source text, call `text`, copy in bounded transactions with the returned text, write the target row, commit | Before the first copy; a refused text step copies nothing | The copy continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | +| `fork` | Take the exclusion, read the source body, call `text`, copy in bounded transactions, write the target body and target rows in the last batch transaction, commit | Before the first copy; a refused text step copies nothing | The copy continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | | `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | | `catalog`, `query` | One consistent read under the caller's token | The read stops; no partial page | Nothing to release | Pending reads end `cancelled`; a new call ends `closed` | SessionStore | | `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | @@ -172,12 +173,13 @@ None. The client methods (`session.rename`, `sessions.list`, `session.delete`, ` ## Supersedes -- [Resource faces §5, §5.1 and §5.2](../resource-faces.md): the `store`/`timelineStore` split, the admission and drain steps, the Session row operations, the Rust `Store` binding and the metadata and association rows. -- [Service faces §3.3 and §3.4](../service-faces.md): the `sessionStore` row and the `store` and `timelineStore` rows. -- [Resource owner operations](../contracts/resource-owner-operations.md): the `SessionStore → sqliteStorage` rows and the Session row paragraphs. -- [Session title metadata](../appserver/session-title-metadata.md): the `title` and `setTitle(id, change)` shapes. -- [Resource faces §4.2 and §5](../resource-faces.md), [service faces §4.8](../service-faces.md), [worktree access §4](../worktree-access.md): the `associateWorktree` request uses `{id, repository, root, subtree}`. -- [SessionTitle](SessionTitle.md): the paragraph that writes a title under an expected revision. +- [Resource faces §5, §5.1, §5.2 and §9(6)](../resource-faces.md): the `store`/`timelineStore` split, the admission and drain steps, the Session rows, the Rust `Store` binding and the face names. +- [Resource faces §4.2](../resource-faces.md): the `associateWorktree` sentence. +- [Service faces §3.2, §3.3 and §3.4](../service-faces.md): the `worktreeAssociations` row, the `sessionStore` row and the `timelineStore` row. +- [Resource owner operations](../contracts/resource-owner-operations.md): the `sessionStore` row and the Native storage section. +- [Session title metadata](../appserver/session-title-metadata.md): §1 Write and Binding, §4.1, §4.2, §5, §6, §10 and Appendix A. +- [SessionTitle](SessionTitle.md): the metadata/notice row, the A.4 Write row and the Appendix G title metadata row. +- [Worktree access §4](../worktree-access.md): the `associateWorktree` sentence. ## Verification diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index e2dff01b20..7cef4071e3 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -39,7 +39,7 @@ only outcome and duration. | Observation | Read the Session id, the creation configuration and closing from SessionScope's `identity`, `config` and `closing` ([#2093](https://github.com/arcships/dim/pull/2093), target, pending; [plugin contract](../plugin-contract.md#9-requirements-raised-to-mechanism-owners) R2), then the records on its Session's `session/{sessionId}` channel. C4 broadcast #180 is delivered; #63/#168 are closed. | | Timeline reads | Use the Session’s branch query facade on `main`, with a fixed published cutoff. Read only the adopted input identity, its user content or Goal objective, and the adopted model fields (§0.1). | | Configuration | Existing named Settings and row source declaration, user scope only (A.3/A12). Read settings.read({source:"session-title",scope:"user"}) at each decision and use its validated/defaulted document directly. | -| Metadata/notice | The process `store` face provides `title` and `setTitle(id, change)`; `setTitle` commits the title the change returns and answers the revision, with errors `rejected`/`not_found`/`closed`/`storage` ([SessionStore](SessionStore.md)); the v3 list fields are `title`/`titleSource`/`titleRevision`. After each commit SessionStore calls `session_broadcast::notify`, and Rpc forwards the record to attached v3 clients as `session.notice {sessionId, source, kind, data}` (C6 #49/#85, [Session broadcast notices](../appserver/session-notices.md)). | +| Metadata/notice | This row is superseded by [the SessionStore contract](SessionStore.md#operations); the v3 list fields are `title`/`titleSource`/`titleRevision`, and Rpc forwards the notice as `session.notice {sessionId, source, kind, data}` (C6 #49/#85, [Session broadcast notices](../appserver/session-notices.md)). | | Auxiliary request | The profile's model-selection owner implements AuxiliaryModel and its named `auxiliaryModel.complete` HostDispatch/catalog binding: Provider in the product profile, ConfiguredModels in the model-config profile. Inject it through ordinary C4 dependencies; credentials stay with that owner ([S4 §4.3](../appserver/auxiliary-model.md#43-named-binding)). | | Policies | A1–A12 define the first implementation. Appendix D requires public-flow acceptance; documentation CI alone is not runtime acceptance. | @@ -413,7 +413,7 @@ omits `maxOutputTokens`, using S4's existing model limit; the 30 s budget remain | Check | `store.title({id})`: the change decides from the current title and revision; a `rejected` change discards | | Read | The four field queries in §0.1 share published T >= N. No adopted eligible input/text means no title (A8/A10). | | Generate | Route and fall back under §3.3 within the shared 30 s budget (A4); normalize the first line, remove quotes and trailing punctuation, collapse whitespace, cut at `maxLength`, trim again | -| Write | `setTitle({id}, change)` where the change returns the generated title or `null`; a `rejected` change discards, and `closed` retries on the replacement generation | +| Write | This row is superseded by [the SessionStore contract](SessionStore.md#operations); a `rejected` change discards, and `closed` retries on the replacement generation | | Timeline | No writes, no Dispatcher registration, no `StateCell` | | Reload / unload | Cancel before store handover; the owner settles an admitted mutation. Events in the gap are not replayed | @@ -506,17 +506,13 @@ auxiliary binding use the owner contracts in §0. The optional service contract | --- | --- | | Namespace `session.rename` registered with `sessionMethods` | The Session part calls `methods.register(ctx, "session.rename", Vec<MethodDecl>, handler)` on a `Key<SessionMethods>` dependency | | Published branch properties | The Session's `timelineTree` service: `read({line: "main", from?, through, fields, limit})` with the published cutoff, which answers `{through, rows}` ([#2092](https://github.com/arcships/dim/pull/2092), target, pending). Configuration paths are `data.settings.providerId` and `data.settings.modelId`. | -| Title metadata | `store.title` and `store.setTitle(id, change)` | +| Title metadata | This row is superseded by [the SessionStore contract](SessionStore.md#operations) | | Auxiliary call | `AuxiliaryModel.0.complete` with its cancellation token | | Optional generation | `ctx.get_at(&host_key("sessionTitleGenerator"))` at use; `HostDispatch.generate` with a cancellable callback promise, using the request/reply types exported by `dim-session-title` | | Session broadcast listener | Listener on `session_channel(session_id)` for `Event` records, removed by `ctx.effect` | | Generation task | Spawned under `ctx.effect` | ```rust -// the `store` face; `setTitle` stays on the hand-written method table -async fn title(&self, id: &str) -> Result<SessionMetadata, StoreError>; // NotFound | Closed | Storage -fn set_title(&self, id: &str, change: ChangeFn) - -> impl Future<Output = Result<u64, StoreError>>; // Rejected | NotFound | Closed | Storage; the call is the handover pub struct SessionMetadata { pub revision: u64, pub title: Option<Title> } pub struct Title { pub text: String, pub source: TitleSource } // Auto | Manual // AuxiliaryModel (the profile's model-selection owner) diff --git a/docs/design/plugins/SqliteStorage.md b/docs/design/plugins/SqliteStorage.md index b5919b5ec0..224ede8899 100644 --- a/docs/design/plugins/SqliteStorage.md +++ b/docs/design/plugins/SqliteStorage.md @@ -107,10 +107,10 @@ None. The `storage.report` client method keeps its request, reply and error shap ## Supersedes -- [Resource owner operations](../contracts/resource-owner-operations.md): the Native storage section — the `SessionStore → sqliteStorage` rows, the Settings and Provider storage tables and the `sqliteStorage` public face. -- [Resource faces §5](../resource-faces.md): the `sqliteStorage` paragraph of the `store`/`timelineStore` section. +- [Resource owner operations](../contracts/resource-owner-operations.md): the Native storage section. +- [Resource faces §6](../resource-faces.md): the `sqliteStorage` row. - [Service faces §3.4](../service-faces.md): the `sqliteStorage` row. -- [Native storage format](../appserver/native-storage-format.md): the paragraphs that describe the public storage face. +- [Native storage format](../appserver/native-storage-format.md): the SQLite owner operations note. ## Rule check diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 920038bc2c..7be0586799 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -18,7 +18,7 @@ Resource and state operations use these public data faces: | `execHost` | `start`, `wait`, `kill`, `settle`, `output`, `tail`, `removeOutputDirectory`, `shell`, `write`, `resize`, `info`, `confined`, `configured` | the process owner | #1295 | | `fsHost` | tool family: `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`; storage family: `stat`, `readBytes`, `openRead`, `readAt`, `closeRead`, `lock`, `unlock`, `backup`, `createDirectory`, `replace`, `list`, `remove` | the file-operations owner | #1297 | | `store` | Session-row repository operations (§5.2) | the process state owner | #1298 | -| `timelineStore` | Timeline operations and completion notifications (§5.1) | the Session state owner | #1298 | +| `timelineStore` | This row is superseded by [the SessionStore contract](plugins/SessionStore.md). | — | #1298 | ```text @@ -467,7 +467,7 @@ The order is fixed, and the Session part is the only participant that both waits `recognize` only when its own view does not already cover the path. 2. The node answers the resolution, the node facts, and either a `worktree` candidate or a `discoveryError`. -3. A candidate goes to `store.associateWorktree {id, repository, root, subtree}`. That +3. A candidate is recorded through the Session store's association operation ([SessionStore](plugins/SessionStore.md)). That operation writes the directory record and the usage association together and answers `{}` only after both commit, deduplicated by repository and root and by Session and directory. A failed write is a `discoveryError` for the caller: the range is not published, and the user can still @@ -602,96 +602,10 @@ Operation refusals are not in this table: they arrive as the tool result's own ` code the operation already uses, so one code vocabulary serves the local and the remote path. ## 5. `store` and `timelineStore` - -The repository and Timeline operations are the Session store's, defined in -[the SessionStore contract](plugins/SessionStore.md): process `store` provides the repository -operations and the Timeline reads for callers outside a Session, and Session-scoped -`timelineStore` is the same owner's Timeline face, bound at the Session instance by SessionScope. -`createSession`, `releaseSession`, `rollbackSession` and `append` are the store's own creation and -commit paths, not operations of that face. - -| Family | Operations | -| --- | --- | -| Timeline (`timelineStore`) | `sessionConfig`, `head`, `branches`, `readPage`, `readSegments`, `query`, `trace`, `batchEnd`, `batchEndAt`, `saveSnapshot`, `latestSnapshot` | -| Timeline completion (`timelineStore`) | `commits`, `closeCommits`; notifications `{subscriptionId, batchId, branchId, through, result}` | -| Session rows (`store`) | The repository operations in [SessionStore](plugins/SessionStore.md) | -| Worktree association (`store`) | `associateWorktree`; [service faces](service-faces.md) §4.8 | +This section is superseded by [the SessionStore contract](plugins/SessionStore.md). ### 5.1 Ordered admission and durable completion - -Admission and release are the Session store's own steps, not operations of the `timelineStore` -face. The store's `create`, `fork`, `delete` and its internal commit path assign each batch its -place in the Session's single writer queue, drain accepted batches before a release and roll back -a prepared creation ([SessionStore](plugins/SessionStore.md)). The face carries the reads and the -completion notifications below. - -The store's admission is synchronous and ordered, and completion is a notification in branch -sequence order: - -```text -admission (owner step) batch -> queued in call order -commits {sessionId} (async) - -> {subscriptionId} -notification {subscriptionId, batchId, branchId, through, result: "committed" | {code, message}} -``` - -- `commits` registers the caller's completion listener and answers a subscription id. The - provider then delivers one notification per accepted batch, after that batch is durable or has - failed, **in branch sequence order**. `through` is the inclusive sequence of the batch's last - event on `branchId`. It advances the durable watermark only when `result` is `"committed"`. -- A failed batch is reported with its `batchId` and error, and refuses later admissions for that - Session with a storage error until the store releases it. The failure is not delivered twice. -- A Session's close waits for the store's release, which answers only after every accepted batch - has completed or failed, so a caller that closes a Session knows no write is still in flight. -- `closeCommits {subscriptionId}` ends a listener; the caller's unload ends it too. -- A remote consumer reads history (`readPage`, `query`, `trace`, and the completion - notifications); it does not admit a batch, because the store is provided where the Session - state is. - -#### Binding shapes and lifecycle - -The Timeline 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: -[{branchId,from,through}]}` returns `{segments}` in request order, using the existing shared read -scope. Each stored record is `{event,trace,batchEnd}` using the canonical event and trace data. -The Rust `TimelineStore::read(key, range)` convenience corresponds to one interval of -`readSegments`, returning that segment directly. The native binding preserves backend overrides; -it does not introduce a separate wire operation or replace an override with fallback probes. -`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 of [SessionStore](plugins/SessionStore.md) and -keeps that canonical reply. - -`saveSnapshot {sessionId,branchId,snapshot}` returns `{}`. `sessionConfig {sessionId}` returns -`{config}`. `latestSnapshot {sessionId,branchId,through,interpreter}` returns `{snapshot}`. -App Server creation/deletion retain the repository and lifecycle obligations the contract states. - -Snapshots retain their canonical fields (`sequence`, `event_id`, `interpreter`, `state`), optional -acceleration semantics and owner validation. Domain errors preserve `{code,message}` using -`invalid`, `closed`, `cancelled` or `storage`; parsing rejects malformed requests at the boundary. - -The bridge binding of `commits` is `commits({sessionId}, listener) -> {subscriptionId}`. The caller -must declare `timelineStore`; the owner registers the listener with that calling row before -returning, and the row's unload withdraws it. Register before the store admits the batches to -observe; there is no replay of earlier admissions. `closeCommits` withdraws it explicitly and is -idempotent. Each listener receives only its requested Session's completions, tagged with its own -subscription id. A slow or failed observer does not delay durable completion or release, and -ending observation never cancels a write or the native publication callback. The calling row must -belong to the runtime in which the provider installed the binding; sharing the native binding -with another runtime does not connect that runtime's listeners to the provider's completion bus. - -The native binding keeps the store's synchronous admission and its existing publish callback. -Its notification `batchId` is the JSON encoding of `[branchId, through]`, the batch identity -already known at admission; local data calls preserve their supplied `batchId`. This identifier -is notification correlation only, with no additional durable fact or lookup. A refused admission -produces no completion notification. The one backend callback keeps native publication -synchronous, then enqueues observation on rutis's existing ordered asynchronous bus. Release -drains that backend's writes and callbacks; it does not wait for observers to finish. -Foreign-language rows in the provider runtime may observe and read; a separate runtime has -read-only access. +This section is superseded by [the SessionStore contract](plugins/SessionStore.md). ### 5.2 Session rows @@ -706,8 +620,8 @@ hand-written `HostDispatch`. | --- | --- | --- | | `hostPlatform` | `execHost` | The provider and its Rust binding: `ProcessTree`, `PtyProcessTree`, temporary directories and shell preparation are its internals, reached through the operations | | `fileStorage` | `fsHost` | The provider and its binding: roots, leases, generations and one validated path component per open are its internals | -| `sqliteStorage` | `sqliteStorage.storageReport({})` | SQLite file, WAL and reclaimable bytes ([native storage](appserver/native-storage-format.md)). Session repository operations belong to `store`. | -| `timelineStore` | `timelineStore` | Session-scoped Timeline operations; the `TimelineStore` trait is its native binding | +| `sqliteStorage` | This row is superseded by [the SqliteStorage contract](plugins/SqliteStorage.md). | — | +| `timelineStore` | This row is superseded by [the SessionStore contract](plugins/SessionStore.md). | — | For the owners below, Rust callers use a thin binding over the operations — a direct in-process call rather than JSON — and none of them publishes a second API: there is no owner @@ -797,11 +711,8 @@ No other requirement is raised: the text is the file operation's own (line numbers, previews, image blocks). A command returns records, and the control side composes the tool result, because the task identity, the background policy and the output-path registration are its. -6. **Repository face names.** `store` names the Session-row repository operations and the - Timeline reads for callers outside a Session; `timelineStore` is the same owner's Timeline - face bound at the Session instance by SessionScope. One owner, two scope bindings - ([SessionStore](plugins/SessionStore.md)); `createSession`, `releaseSession`, - `rollbackSession` and `append` are the owner's own steps. +6. **Repository face names.** This section is superseded by [the SessionStore contract](plugins/SessionStore.md). + 7. **Root identity form.** The Session passes the opaque `rootIdentity` back to the provider. The provider owns its platform form and comparison. 8. **Retained task records.** Settlement is explicit (§3.8). If a long-lived local provider wants a diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index b32f6b9691..a6cf31af28 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -91,14 +91,14 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `scheduleJobs` | `scheduleJobs.call(JobRequest)` | 按 [Scheduler](plugins/Scheduler.md#a2-tool-schedule) 的 flat `JobRequest`/`JobReply`,与 `wakeups` 同一批次([#1396](https://github.com/arcships/dim/pull/1396))。 | | `wakeups` | `wakeups.create/list/cancel` | 形状按 [Scheduler](plugins/Scheduler.md#102-methods-and-tool) §10.2。 | | `loops` | `loops.start/next/list/stop` | 形状按 [Scheduler](plugins/Scheduler.md#126-interfaces) §12.6;`start`、`next`、`stop` 是迁改,`list` 是读取。投递 pass、恢复与 `settle_delivering` 不在此面。 | -| `sessionFiles` | `sessionFiles.put/import/write/read/register/owns/remove/owned_paths` | 形状按 [SessionFiles](plugins/SessionFiles.md);服务标注在所有者类型上。 | +| `sessionFiles` | 本节由 [SessionFiles 契约](plugins/SessionFiles.md) 取代。 | 本节由 [SessionFiles 契约](plugins/SessionFiles.md) 取代。 | | `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。 | | `sessionLanguage` | `sessionLanguage.get()` | 形状见 §4.8。 | | `skillsConfig` | `skillsConfig.get()` | 形状见 §4.8。 | | `collaborationConfig` | `collaborationConfig.get()` | 形状见 §4.8。 | -| `worktreeAssociations` | 已并入 `store.associateWorktree` | 见 [SessionStore](plugins/SessionStore.md)。 | +| `worktreeAssociations` | 本节由 [SessionStore 契约](plugins/SessionStore.md) 取代。 | 本节由 [SessionStore 契约](plugins/SessionStore.md) 取代。 | | `toolSourcesView` | `toolSourcesView.get/observe` | 同一 ToolRegistry owner 的独立只读观察面;贡献注册仍由 `toolRegistry` 负责,见 [工具贡献 §7.5](../architecture/rust-agent/tool-contributions.md#75-服务接口)。 | 宿主读取端口的数据面(§4.10)包括 `executionSettingsHost`、`toolchainSourceHost`、`promptSuggestionSettingsHost`。模型选择与列表统一由 `providerService` 提供;调用方和配置见[进程操作](contracts/process-owner-operations.md);其余读取端口沿用现名。 @@ -113,7 +113,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `settingsService` | `settings` | GoalBranch 的取消契约见 §4.1。 | | `modelHost` | `modelHost` | 完整模型请求直接调用所选配置的执行入口;辅助请求使用 `providerService.complete`。 | | `loader` | `rutis/loader` | 插件管理走数据面 | -| `sessionStore` | `store`、`sessionFiles`、`timelineStore` | 已退役:绑定读取与标题、关联、worktree 记录都是 `store` 的操作,见 [SessionStore](plugins/SessionStore.md) | +| `sessionStore` | 本节由 [SessionStore 契约](plugins/SessionStore.md) 取代。 | 本节由 [SessionStore 契约](plugins/SessionStore.md) 取代。 | | `treeCommands`、`timelineTreeControl` | `timelineTree` | 分支操作直接调用 Session 的树;不保留别名 | ### 3.4 对象/句柄:拆成操作加 id @@ -125,8 +125,8 @@ 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` | 连接与事务 | 公开面只剩 `storageReport` 与离线操作;Settings、Provider、Agent 记录与 Timeline 事务是各数据所有者的私有实现([SqliteStorage](plugins/SqliteStorage.md))。 | -| `timelineStore` | 连接与批次 | Session 仓储自己的 Timeline 面,由 SessionScope 在 Session 实例上绑定([SessionStore](plugins/SessionStore.md)):`sessionConfig`/`commits`、`closeCommits`(按分支序的完成通知)/`head`/`branches`/`readPage`/`readSegments`/`query`/`trace`/`batchEnd`/`batchEndAt`/`saveSnapshot`/`latestSnapshot`;`createSession`/`releaseSession`/`rollbackSession`/`append` 是所有者内部步骤 | +| `sqliteStorage` | 本节由 [SqliteStorage 契约](plugins/SqliteStorage.md) 取代。 | 本节由 [SqliteStorage 契约](plugins/SqliteStorage.md) 取代。 | +| `timelineStore` | 本节由 [SessionStore 契约](plugins/SessionStore.md) 取代。 | 本节由 [SessionStore 契约](plugins/SessionStore.md) 取代。 | | `promptSourcesBranch` | 分支 prompt 装配 | 按 #1292 确认公共操作与装配内部职责。 | 这些行按当前对象形状分组。前四行的数据契约由 [resource and store data faces](resource-faces.md) 定义(#1295/#1297/#1298)。其余行按 #1292 逐批确定操作面。 @@ -248,7 +248,7 @@ workflowRuns.call(RunRequest) ### 4.5 `sessionFiles` -按 owner 契约 [SessionFiles](plugins/SessionFiles.md) 暴露 `sessionFiles`;服务标注在所有者类型上,不另设包装类型。 +本节由 [SessionFiles 契约](plugins/SessionFiles.md) 取代。 文件导入、分块读取、归属操作的参数、回复、错误及取消语义均由 §9.1 定义。文件传输使用按路径导入与有界读取操作。 diff --git a/docs/design/worktree-access.md b/docs/design/worktree-access.md index 4675d4ddd9..5d2597bb10 100644 --- a/docs/design/worktree-access.md +++ b/docs/design/worktree-access.md @@ -192,7 +192,7 @@ exec cwd=/repo-wt -> Known root -> Existing command approval 删除语义不适用于用户代码。两者均不能直接作为 worktree 记录使用。 - **Needed:** SessionStore 拥有目录记录、原子去重关联写入和 Session 删除时的解除关联; 目录候选不因最后一条使用关联被删而消失。它把写暴露为进程数据面 - `store.associateWorktree {id, repository, root, subtree}`,路径是 UTF-8 + Session store 的关联操作([SessionStore](plugins/SessionStore.md)),路径是 UTF-8 字符串;Rust 消费者调用同一个方法,不直接读写表。 - **Ordering impact:** 关联写入不产生 Timeline 事实;与删除串行协调,已删除或正在删除的 Session 不能被迟到写入重新关联。native 格式改变须由存储所有者作独立格式决定,遵守 diff --git a/docs/design/worktree-management.md b/docs/design/worktree-management.md index ef639049bc..90aeccc2be 100644 --- a/docs/design/worktree-management.md +++ b/docs/design/worktree-management.md @@ -105,38 +105,7 @@ agent 工具,不经过 Permission 批准,也从不服务给配对设备的 `--force`)或未登记的目录一律不选。删除前逐项复核 Git 登记、根未变与内容干净,先预览再按确认删除;apply 携带预览的 task id,只删除用户看到的集合,单个候选失败时保留其记录并继续其余候选。保留项逐条给出原因。 选择语义与交互沿用 [session cleanup](cli-commands.md#session-deletion-and-cleanup),不新增第二套。 -- **排斥**:删除分两步。已登记的 remove 与 prune 经由 SessionStore 的 `store.removeWorktree` 操作:它在会话存储 - 所有权锁内复核关联与存储中的 Session cwd;未登记的 remove 经由 `store.removeUnregisteredDirectory`:它在同一把锁内 - 复核目录记录中没有根在该目录或其下的条目、存储中没有 Session 的 cwd 在该目录或其下。两个操作随后把要删的规范化路径 - 登记进内存的“正在删除”集合,放锁。调用方传入的删除步骤(`git worktree remove`、`cleanup_unregistered_root`、未登记目录 - 的检查与递归删除)在本次请求自己的任务里前台完成,失败照样返回给调用方,记录只在删除成功后删除。删除结束时同一个任务把路径 - 移出集合;外层请求被取消也不会提前移出,集合只在内存里,进程崩溃后半删的目录仍可按 task id 再删一次。 -- **正在删除**:集合只拦与登记路径相同、在其上或在其下的操作:`session.create` 与 `sessions.launch` 的 cwd、 - `store.fork` 配置里的 cwd、`associate_worktree` 的根、同一路径的再次删除,以及同一目录的记录删除 - (`store.removeWorktreeDirectory`)都被拒绝(`worktree.remove` 报 `worktree_in_use`);`worktree.create` 在 - 同一把锁内拿选中的目录与集合比对,命中就换一个 `<task-id>`,所以登记期间不会在同一路径建出目录。 - 父路径方向也拒绝,因为它的内容正在被删(例如任务目录下的仓库),这期间不在其上新建 Session。删除结束后被删的目录 - 自然通不过创建与关联的目录检查。不相关路径的创建、分叉、删除与关联不再等删除;复核之后也不会出现指向已删根的 - 新 Session 或关联。 -- **正在创建**:`worktree.create` 选中目录之后、建目录之前,在同一把锁内把选中的规范化路径登记进“正在创建”集合, - 与“正在删除”对称。登记由创建自己的任务持有,只随创建结束而释放(目录记录与使用关联写入之后,或失败清除把它交接成“正在删除”之后), - 删除方移不掉它;集合同样只在内存里。`store.removeWorktree` 与 `store.removeUnregisteredDirectory` 在锁内 - 登记“正在删除”时与这个集合双向比对,命中(路径相同、在其上或在其下)即以 `worktree_in_use` 拒绝,所以创建通过 - 目录检查之后、把 worktree 交给 Session 之前落进来的删除不会删到正在创建的 worktree。创建自己的失败清除(撤回目录与分支) - 在同一把锁内把这条登记直接交接成“正在删除”,中间没有空档,所以撤回既不会被自己的登记挡住,也不会被另一条在同一路径上 - 通过检查的创建插进去。创建成功时登记在目录记录写入后释放,同一路径随后可正常删除;两条创建撞上同一路径时 - 后一条换一个 `<task-id>`。 -- **未登记目录的复核**:由 ManagedWorktrees 提供的删除步骤在删除前用文件系统检查复核目录仍是管理根下的普通目录、 - 它的直接子目录仍是管理根内的普通目录,以及删除范围内每个目录都没有 `.git` 条目(目录、gitdir 文件或符号链接,含悬空链接; - 遍历不跟随符号链接,不起 Git 子进程),不满足就拒绝。 -- **非 force 的删除**:只删检查记录下来的空直接子目录和任务目录本身,逐个按名字从已打开的目录句柄删除(Unix 的 `unlinkat`); - 任务目录或子目录在检查后被换成符号链接时删除以 `worktree_in_use` 失败,不会删到管理根外。Windows 没有既能只删空目录、 - 又能守住管理根边界的现成原语,所以非 Unix 平台上未登记目录的非 force 删除直接以 `worktree_in_use` 拒绝并提示 `--force`; - `--force` 用标准库的 `remove_dir_all`,它按目录句柄遍历、不跟随树内的 reparse point。 -- **时间上限**:锁只跨越复核与登记,没有慢步骤。删除本身没有时间上限:`git worktree remove` 有 30 秒超时, - 递归删除按目录内容多少决定,这是已知限制。 - 可证明的使用只有记录与存储中的 cwd;其余使用不可证明,由预览、确认和 worktree-access §4 的删除授权承担。 -- Session 删除和 `session cleanup` 不删除也不报告遗留的 worktree;`worktree list` 是查看它们的唯一入口。 +- **排斥**:本节由 [ManagedWorktrees 契约](plugins/ManagedWorktrees.md) 取代。 ## 6. 影响面 From 39ee21671cc77c77875088b9a7c4efeadef067f0 Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 17:29:37 +0800 Subject: [PATCH 15/19] docs(storage): answer the pre-review findings SessionStore restores the timelineStore operation contract (reads, completion subscriptions, notification shape, watermark and release rules) and keeps the query read scope. create/fork/delete hand over to owner tasks; duplicate create, missing fork source and second removal have results; associateWorktree dedupes; removeUnregisteredDirectory keeps the lock after the caller leaves. SessionFiles adds releaseSession and states the put cancellation and the close endings. SqliteStorage separates the offline functions from the service face. ManagedWorktrees keeps the published worktree_* codes, never deletes a branch on an unregistered removal and answers keptBranch. The remaining main-tree paragraphs that describe these owners point at the contracts, and the zh mirrors follow for the title and session-files interfaces. Refs #2018 Refs #2015 --- .../appserver/session-deletion-and-fork.md | 4 +- docs/design/overview.md | 2 +- docs/design/plugin-contract.md | 2 +- docs/design/plugins/ManagedWorktrees.md | 52 ++++++------ docs/design/plugins/SessionFiles.md | 17 ++-- docs/design/plugins/SessionStore.md | 81 +++++++++++++++---- docs/design/plugins/SqliteStorage.md | 34 ++++---- docs/design/resource-faces.md | 2 +- docs/design/service-faces.md | 5 +- docs/typescript-plugin-authoring.md | 2 +- docs/zh/design/appserver/session-files.md | 26 +----- docs/zh/design/overview.md | 2 +- docs/zh/design/plugin-contract.md | 2 +- docs/zh/design/plugins/SessionTitle.md | 30 +++---- 14 files changed, 147 insertions(+), 114 deletions(-) diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index adad6399f9..4706b42f14 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -846,8 +846,8 @@ path (`TimelineStore::rollback_session`) calls the same row removal as `delete_s ### Worktree association port -SessionStore provides the process service `worktreeAssociations` to the Session file-facts owner. -The operation is the data face `associate {sessionId, repository, root, subtree}`, all paths as +This section is superseded by [the SessionStore contract](../plugins/SessionStore.md): the association is +`store.associateWorktree {id, repository, root, subtree}`, all paths as UTF-8 strings, with the same atomicity and errors as §17; a Rust caller calls the same method. The file-access contract owns the directory definition, containing repository common directory and worktree root. The port writes usage only and performs no Git discovery or authorization. diff --git a/docs/design/overview.md b/docs/design/overview.md index 7ad843b331..296573bfcb 100644 --- a/docs/design/overview.md +++ b/docs/design/overview.md @@ -505,7 +505,7 @@ A **supplement** adds services, methods or configuration. A **change** alters ex | Transport, Connection | Change | `EntryHost` with upgrade authenticators; `ConnectionEntry {name, deviceId}` | RemoteGateway | | Agents | Supplement | The `sessions` service ([sessions service](appserver/sessions-service.md)); `SessionConfig.interactive`; `launch` with a policy capped by the starter, `LaunchRequest.agent` optional (absent: Agents' default profile; request `model` over the profile's model); creation from another Session's cut ([deletion and fork](appserver/session-deletion-and-fork.md#6-fork)); `session.agent.update` and `session.agent.get` through Agents' Session entry, resolving an exact profile ID for prompt/model adoption and reading back the profile a branch adopted | Scheduler, Workflow, fork, `/agent` | | Collaboration | Change | Member model: the user's [subagent model policy](subagent-model-policy.md) (`agent`: the profile's model, else the default selection; `inherit`; `fixed`); [member permission inheritance and tool-approval routing](subagent-tool-approval.md): new native members sample the requesting branch's current policy; pending member approvals reach that branch as adopted inputs, with leader decision tools under its Approval and Permission and [user review of the original action](cli-commands.md#subagent-tool-approval) (#29, #257); member providers by kind (`collaborationMembers:<kind>`, looked up per call) for members that are not dim Sessions, whose asks use the same member-approval route; the `agent` tool keeps its existing risk classification ([ExternalAgent §9.2](plugins/ExternalAgent.md#92-collaboration-member-providers)) | ExternalAgent | -| SessionStore | Supplement | Title metadata with revision checks, written only through `setTitle`, with a Session broadcast notice on change (owners of process-level state emit such notices) (S5b, implemented: the `sessionMetadata` service, [title metadata](appserver/session-title-metadata.md)); deletion and cleanup; fork (copies facts before the cut) (S5c, implemented: [deletion and fork](appserver/session-deletion-and-fork.md)); Session files on the resource node, shared on fork and deleted with the last owner (S5a, implemented: the `sessionFiles` service, [session files](appserver/session-files.md)); `session_grants` rows, removed with the Session and never copied to a fork ([ADR 012](../adr/012-session-grants.md)) | SessionTitle, Attachments, fork, SessionGrants | +| SessionStore | Supplement | This row is superseded by [the SessionStore contract](plugins/SessionStore.md) and [the SessionFiles contract](plugins/SessionFiles.md): `store.title`/`setTitle(id, change)` with a Session broadcast notice, deletion and cleanup, fork, Session files, and the `session_grants` rows ([ADR 012](../adr/012-session-grants.md)) | SessionTitle, Attachments, fork, SessionGrants | | Settings | Supplement | S8a (Rust, implemented): one or more named business sources per owner, each holding one document type; no subscription API of its own: a committed write emits the rutis event `settings.changed` `{source, scope, revision}` on `settings/<source>`, for user and project scope, without the body, and a newly authorized project emits `settings.project_authorized`; validation and defaults only at the Settings boundary; additive `user/<source>` rows under the v13 `settings_documents` contract (D4). S8b (with C4, implemented): the language-neutral `settings` service with JSON Schema, defaults, allowed scopes and user-only fields declared on C4 rows; management methods `settings.read`/`settings.update`/`settings.sources`/`settings.projects`; no credential service (§6.4) | Every plugin with business configuration, including user-written Scheduler jobs (source `schedule`) and Workflow definitions (source `workflow`) | | Provider | Supplement | Validation and mapping of advertised effort/tier preferences against the captured adopted model configuration; `AuxiliaryModel` service: `complete(model, request)`, one non-streaming call outside any Session, with the model passed by the caller from its own configuration ([design](appserver/auxiliary-model.md)); proposed [Desktop/CLI management supplement](appserver/provider-management.md) for safe connection edits, model lifecycle and client-only preferences; non-conversational connections per Modality category | `/effort`, `/fast`, SessionTitle, Modality | | `pluginFiles` (`PluginFilesPlugin`) | Supplement | Binary read and write and a format version ([trusted plugin storage](../../crates/dim-app-server/README.md#trusted-plugin-storage)); code location unchanged | Scheduler, Workflow, Modality, RemoteGateway, PluginManager, ExternalAgent | diff --git a/docs/design/plugin-contract.md b/docs/design/plugin-contract.md index 1d34d18338..db925e3841 100644 --- a/docs/design/plugin-contract.md +++ b/docs/design/plugin-contract.md @@ -107,7 +107,7 @@ R4). This table says what each name Dim defines is for. | --- | --- | --- | --- | --- | | `sessions` | process | Agents | yes | Start or drive another Session | | `sessionPermissions` | process | Agents | yes | Marked `#[rutis::service]` | -| `sessionMetadata` | process | SessionStore | yes | SessionTitle is the title's one writer | +| `store` | process | SessionStore | yes | Title, grants, language, worktree records and associations; the contract is [SessionStore](plugins/SessionStore.md) | | `settings` | process | Settings | yes | Business configuration | | `auxiliaryModel` | process | the profile's model-selection owner | yes | Auxiliary model requests | | `pluginFiles` | process | host | yes, when the host supplies a root | A process part's own files | diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md index bdfb4af0bb..fb75c4fdd7 100644 --- a/docs/design/plugins/ManagedWorktrees.md +++ b/docs/design/plugins/ManagedWorktrees.md @@ -67,11 +67,11 @@ for candidate in confirmed(&preview) { | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `create` | Allocate a task id and make a Git worktree and branch for a Session creation | `{source, base?, branch?}` | `{taskId, repository, root, subtree, branch, base}` | Between Git calls and before the branch is created; a cancelled creation removes its empty task directory | `unavailable`, `invalid`, `branch_exists`, `git`, `interrupted` | -| `discard` | Settle a created worktree that the Session creation did not adopt | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `in_use`, `git`, `closed`, `storage` | -| `list` | Managed worktrees with Git state and Session use | `{}` | `{worktrees}` | While the views are built | `unavailable`, `closed`, `storage` | -| `pruneSelection` | Candidates a prune would delete and the kept ones with reasons | `{olderThanMs?, keep?, force}` | `{candidates, kept}` | While the selection is built | `invalid`, `unavailable`, `closed`, `storage` | -| `remove` | Remove one managed worktree, or an unregistered directory, with its record | `{taskId, force}` | `{removed}` | Before the Git removal; after it starts the removal completes or reports `git` | `invalid`, `not_found`, `in_use`, `git`, `closed`, `storage` | +| `create` | Allocate a task id and make a Git worktree and branch for a Session creation | `{source, base?, branch?}` | `{taskId, repository, root, subtree, branch, base}` | Between Git calls and before the branch is created; a cancelled creation removes its empty task directory | `worktree_unavailable`, `worktree_invalid`, `worktree_branch_exists`, `worktree_git_failed`, `worktree_interrupted` | +| `discard` | Settle a created worktree that the Session creation did not adopt | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `worktree_in_use`, `worktree_git_failed`, `worktree_interrupted`, `worktree_store_failed` | +| `list` | Managed worktrees with Git state and Session use | `{}` | `{worktrees}` | While the views are built | `worktree_unavailable`, `worktree_interrupted`, `worktree_store_failed` | +| `pruneSelection` | Candidates a prune would delete and the kept ones with reasons | `{olderThanMs?, keep?, force}` | `{candidates, kept}` | While the selection is built | `worktree_invalid`, `worktree_unavailable`, `worktree_interrupted`, `worktree_store_failed` | +| `remove` | Remove one managed worktree, or an unregistered directory, with its record; an unregistered removal keeps the branch and reports it | `{taskId, force}` | `{removed, keptBranch?}` | Before the Git removal; after it starts the removal completes or reports `worktree_git_failed` | `worktree_invalid`, `worktree_not_found`, `worktree_in_use`, `worktree_git_failed`, `worktree_interrupted`, `worktree_store_failed` | `create` returns a value; `discard` and `remove` take the task id. No object crosses. The preparation table is the owner's generation state: a reload drops it, and `discard` for a task id the generation did not create answers `unknown_preparation`; the directory is then an unregistered directory that `remove` handles. @@ -79,18 +79,19 @@ for candidate in confirmed(&preview) { ### Errors +The wire codes are the published `worktree_*` codes (`crates/dim-app-server/src/worktrees.rs:85-108`); `unknown_preparation` is the only internal code. + | Kind | What the caller does next | | --- | --- | -| `unavailable` | The daemon has no managed root or the source is not a usable Git worktree; the caller refuses the worktree request | -| `invalid` | Fix the request: an unknown task id form, both or neither of older-than and keep, a path that is not a plain managed directory | -| `branch_exists` | The requested branch already exists; choose another branch | -| `not_found` | No recorded or unregistered directory has the task id | -| `in_use` | A Session still uses the directory, or its content is not removable without `force`; the caller reports the blocker | -| `git` | Git refused the operation; the caller reports the message and keeps the directory and the report | -| `interrupted` | The call was stopped; a creation's partial state is cleaned, a removal is retried | +| `worktree_unavailable` | The daemon has no managed root or the source is not a usable Git worktree; the caller refuses the worktree request | +| `worktree_invalid` | Fix the request: an unknown task id form, both or neither of older-than and keep, a path that is not a plain managed directory | +| `worktree_branch_exists` | The requested branch already exists; choose another branch | +| `worktree_not_found` | No recorded or unregistered directory has the task id | +| `worktree_in_use` | A Session still uses the directory, or its content is not removable without `force`; the caller reports the blocker | +| `worktree_git_failed` | Git refused the operation; the caller reports the message and keeps the directory and the report | +| `worktree_interrupted` | The call was stopped or the generation closed; a creation's partial state is cleaned, a removal is retried on the replacement generation | | `unknown_preparation` | The preparation ended with the generation; the directory is unregistered and `remove` handles it | -| `storage` | A record read or write failed; the caller reports the failure and keeps the record | -| `closed` | This generation is unloading; call the replacement generation | +| `worktree_store_failed` | A record read or write failed; the caller reports the failure and keeps the record | ### Flows @@ -100,7 +101,7 @@ for candidate in confirmed(&preview) { | `discard` | Look up the preparation, `store.removeWorktree(directory, remove)`, delete the branch; the record may be absent | No cancellation; the cleanup is the owner's | The preparation ends with the row; the directory is unregistered | The table drops with the generation; the directory stays unregistered | Directory and branch by ManagedWorktrees; record by the store | | `list` | Read the records and associations, join Git state per directory, add unregistered directories | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | | `pruneSelection` | `list`, then apply age, keep and force rules per candidate | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | -| `remove` | Resolve the record or the unregistered directory; a recorded one goes through `store.removeWorktree(directory, remove)`, an unregistered one through `store.removeUnregisteredDirectory(root, remove)`: the store checks and holds the exclusion, this owner removes the Git worktree or the directory, the store deletes or keeps the record | Before the Git removal; a started removal completes or reports `git`; the store keeps the record | The callback ends with the row; the store keeps the record | An in-flight removal ends; the store keeps the record unless the Git step succeeded | Directory by ManagedWorktrees; record by the store | +| `remove` | Resolve the record or the unregistered directory; a recorded one goes through `store.removeWorktree(directory, remove)`, an unregistered one through `store.removeUnregisteredDirectory(root, remove)`: the store checks and holds the exclusion, this owner removes the Git worktree or the directory, the store deletes or keeps the record; a branch is never deleted on an unregistered removal and its name is answered in `keptBranch` | Before the Git removal; a started removal completes or reports `worktree_git_failed`; the store keeps the record | The callback ends with the row; the store keeps the record | An in-flight removal ends; the store keeps the record unless the Git step succeeded | Directory by ManagedWorktrees; record by the store | A process death between `create` and `store.create` leaves an unregistered directory; `list` reports it and `remove` deletes it after the operator names the task id. A process death during the removal step leaves the record; the next `list` reports the directory as missing or no longer registered, and `remove` cleans the record. @@ -109,7 +110,8 @@ A process death between `create` and `store.create` leaves an unregistered direc - A branch is kept when `remove` deletes an adopted worktree: committed content must not disappear with the directory. Only the default `dim/<taskId>` branch of a never-adopted worktree is deleted with the directory. - `discard` is not cancellable: a cancelled Session creation still has to settle what the owner made. A store refusal (`closed` or `storage`) leaves the directory and branch in place; the caller reports it. The preparation is dropped with the generation, so the directory is unregistered and `remove` by task id is the retry path on the replacement generation. - Unregistered directories are never pruned: the owner has no record to age, so only an explicit `remove` by task id deletes them. -- A branch outlives a creation that was never adopted: a process death between `create` and `store.create` leaves the branch. `remove` on an unregistered directory deletes the directory and, when the owner created the default `dim/<taskId>` branch for a worktree that was never adopted, deletes that branch too; an explicit branch from the request is retained and reported, so a name the operator chose is never deleted. +- The preparation table exists because a created worktree has no record until the Session adopts it: the task id is the only handle a caller keeps after its own state is lost or reloaded, so `discard` settles by id instead of by a value the caller may no longer hold. +- A branch outlives a creation that was never adopted: a process death between `create` and `store.create` leaves the branch. `remove` on an unregistered directory never deletes a branch; it answers the branch the directory was on in `keptBranch`, and the operator deletes it with Git. The preparation table is gone by then, so the owner cannot tell a default `dim/<taskId>` branch from one the operator named; never deleting is the only decidable rule. - Git is the owner's process resource: the owner starts each call, bounds it (10s read, 30s write) and reaps it on cancellation. ## Client-visible changes @@ -219,25 +221,23 @@ pub struct RemoveWorktreeReply { #[serde(tag = "code", rename_all = "snake_case")] pub enum WorktreeError { #[error("{message}")] - Unavailable { message: String }, + WorktreeUnavailable { message: String }, #[error("{message}")] - Invalid { message: String }, + WorktreeInvalid { message: String }, #[error("{message}")] - BranchExists { message: String }, + WorktreeBranchExists { message: String }, #[error("{message}")] - NotFound { message: String }, + WorktreeNotFound { message: String }, #[error("{message}")] - InUse { message: String }, + WorktreeInUse { message: String }, #[error("{message}")] - Git { message: String }, + WorktreeGitFailed { message: String }, #[error("{message}")] - Interrupted { message: String }, + WorktreeInterrupted { message: String }, #[error("{message}")] UnknownPreparation { message: String }, #[error("{message}")] - Closed { message: String }, - #[error("{message}")] - Storage { message: String }, + WorktreeStoreFailed { message: String }, } impl PublicService for ManagedWorktrees {} diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md index 4fc9d1c81b..e1bf333517 100644 --- a/docs/design/plugins/SessionFiles.md +++ b/docs/design/plugins/SessionFiles.md @@ -71,10 +71,11 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, path, bytes}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, content}`, `content` is base64 | `{fileId, path, bytes}` | Before the replacement; the old bytes stay | `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `read` | One page of a Session file, at most 64 KiB | `{sessionId, fileId, offset}` | `{data, eof}`, `data` is base64 and `eof` is true exactly when it is empty | While the page is read; nothing changes | `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | -| `register` | Record a caller-owned output path for the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `storage` | +| `register` | Record a caller-owned output path for the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `closed`, `storage` | | `owns` | Whether a path or file id belongs to the Session | `{sessionId, path}` | `{owned}` | While the path is resolved | `node_unavailable`, `cancelled`, `closed`, `storage` | | `remove` | Remove one Session file and its ownership row; an absent or foreign file answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal during close | `node_unavailable`, `closed`, `storage` | -| `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `storage` | +| `releaseSession` | Delete every ownership row of a deleted Session and schedule the sweep; a repeated call succeeds | `{sessionId}` | `{}` | None; the owner completes the release | `closed`, `storage` | +| `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `closed`, `storage` | `path` is absolute on the Session's resource node; `bytes` is the stored length. `offset` at the file size answers an empty `data` with `eof`; an offset above the size is clamped to the size before the page read, because FileStorage refuses an offset above it with `invalid`. The rule is stated once in both documents: at `size` an empty page with `eof`, above `size` `invalid` at FileStorage; this owner clamps so its own callers keep the empty page their client contract states. A `fileId` outside the Session, or a name that is not one component, is `not_found` for reads and writes and `invalid` for a name `put` or `import` receives. @@ -86,7 +87,7 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `too_large` | Treat the file as not storable; store a smaller representation or refuse the attachment | | `not_found` | The Session has no such file, the file belongs to another Session, or the Session no longer exists; the caller refuses the request | | `node_unavailable` | The Session's resource node cannot be reached; retry later or report the node as unavailable | -| `cancelled` | Nothing was committed; the caller stops | +| `cancelled` | The reservation and any copy are left to the sweep; no ownership row was committed, and the caller stops | | `closed` | This generation is unloading; call the replacement generation | | `storage` | The store or the file system failed; the caller reports the failure and keeps its own copy | @@ -99,9 +100,10 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `write` | Resolve the file id, write the new bytes through FileStorage under the same path, keep the row | Before the replacement: the old bytes stay | The write completes or is abandoned | As `put` | File and path by FileStorage; row by SessionFiles | | `read` | Resolve the file id, read one page at the offset; an offset at or past the end is an empty page | The page stops; nothing changes | The read stops | Pending reads end `closed` | FileStorage | | `remove` | Resolve the file id; an absent or foreign id answers success; remove the directory entry through FileStorage, delete the row | None | The call ends | A new call is refused `closed`; an admitted removal finishes | File and row by SessionFiles | -| `register` | Check the Session, record the path the caller resolved | None | The row stays; a later Session delete removes it | Rows stay for the next generation | SessionFiles | +| `releaseSession` | Delete every ownership row of the Session, schedule the sweep; the bytes are deleted outside the transaction | None | The release continues under the owner's task | A new call is refused `closed`; an admitted release finishes | Rows by SessionFiles; bytes by the sweep | +| `register` | Check the Session, record the path the caller resolved | None | The row stays; a later Session delete removes it | A new call is refused `closed`; rows stay for the next generation | SessionFiles | | `owns` | Resolve the path against the owner's directory, check the output row, else the file id row | The resolution stops | Nothing to release | Pending calls end `closed` | SessionFiles | -| `ownedPaths` | Read both ownership rows, map file ids to the directory | None | Nothing to release | Rows stay | SessionFiles | +| `ownedPaths` | Read both ownership rows, map file ids to the directory | None | Nothing to release | A new call is refused `closed`; rows stay | SessionFiles | A Session delete releases this owner's rows before the sweep runs; the sweep deletes bytes no row owns. Files another Session owns are never removed by one Session's delete. @@ -111,7 +113,7 @@ A Session delete releases this owner's rows before the sweep runs; the sweep del - The generation is the store's generation: a stale writer cannot commit into a Session that a newer store generation created. - `read` pages by offset instead of opening a read id: the callers (Attachments' `attachment.read`, the web download, image materialization) already page by offset, and a read id would put its release on every error path. - `register` records a path the caller resolved and owns the root of: WorkspaceTools and HostPlatform have two different output roots, and the owner cannot decide which root a path belongs to without depending on both. -- `write` and `remove` serve MCP result files ([#2022](https://github.com/arcships/dim/pull/2101)): a result file is rewritten as the child reports progress and removed when the child's result is discarded. +- `write` and `remove` serve MCP result files ([#2101](https://github.com/arcships/dim/pull/2101)): a result file is rewritten as the child reports progress and removed when the child's result is discarded. - The ownership rows live in the engine's database but belong to this owner: the engine executes the transaction, SessionFiles decides when it commits. ## Client-visible changes @@ -123,6 +125,7 @@ None. `read` keeps the offset page and the 64 KiB bound; `put` and `import` keep - [Session files §9.1](../appserver/session-files.md#91-language-neutral-adr-002-d5): the operation table, the paging note, the register root rule and the paragraph that says SessionStore offers no operation that changes or removes one file. - [Service faces §3.2](../service-faces.md): the `sessionFiles` row. - [Resource faces §4.6](../resource-faces.md): the Session files paragraph. +- [Overview](../overview.md): the SessionStore row's Session files clause. ## Verification @@ -164,7 +167,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -1. **FileStorage (#2016): the operations this owner calls.** `root_path`, `read` with `{offset, length}` and `{data, eof, size}`, `write` with its `source` and `privateReadOnly`, `import` with `max_bytes` and `privateReadOnly`, `create_directory`, `list` and `remove` exist in [FileStorage's contract](https://github.com/arcships/dim/pull/2080) at head `7224c0cd4`. The owner reads the store directory's root with `root_path`; the host registers the native store directory as a root, and a comment on #2016 records the dependency. +1. **FileStorage (#2016): the operations this owner calls.** `root_path`, `read` with `{offset, length}` and `{data, eof, size}`, `write` with its `source` and `privateReadOnly`, `import` with `max_bytes` and `privateReadOnly`, `create_directory`, `list` and `remove` exist in [FileStorage's contract](https://github.com/arcships/dim/pull/2080) at head `2a312945c`. The owner reads the store directory's root with `root_path`; the host registers the native store directory as a root, and a comment on #2016 records the dependency. 2. **Service type placement (#2015): a process owner in the app server.** The owner type is in `dim-app-server`, where the engine and the rows are; callers in plugin crates cannot depend on the app server. The request and reply types are plain data in `dim-agent-capabilities::host`, and callers outside the crate call the operations by the `sessionFiles` name. If the maintainers decide every process face must be annotated on a type plugin crates can name, the type moves to a shared crate; a comment on #2015 states the requirement. ## Binding appendix diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 0e6370d2c4..74e21c9a9e 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -15,7 +15,7 @@ SessionStore owns: - **Worktree records.** A recorded directory, its last-use time and the Session associations that point into it. - **The Session exclusion.** One lock that keeps creation, fork, deletion, association and worktree removal from observing each other's partial state. - **The Timeline storage engine.** The admitted batch queue, the grouped commit, paging, snapshots and release, executed over the Session rows. `timelineStore` publishes the same engine per Session; the Session face belongs to SessionScope. -- **The Session reads.** `query` and `sessionConfig` exist only on the process `store`; both take `{id}` and serve loaded and unloaded Sessions. No Session-scoped or `timelineStore` operation carries them. +- **The Session reads.** `sessionConfig {id}` and `query {scope, query, page?}` exist only on the process `store` and serve loaded and unloaded Sessions. `query` keeps the read scope: `scope` carries the Session key, the committed `through` cutoff and the branch segments, and `page.after` is checked against the same binding. No Session-scoped or `timelineStore` operation carries them. Callers keep: @@ -98,7 +98,7 @@ store.removeWorktree(Directory { repository, root }, remove, cancelled.clone()). ### Dependencies -The engine's crate-private transaction operations for every row read and write and for the Timeline batches; the engine's public face is the capacity read. The file owner `sessionFiles` for the Session file steps a delete releases. Neither dependency crosses back into SessionStore. The assembly provides both; deployment chooses the instance. +The engine's crate-private transaction operations for every row read and write and for the Timeline batches; the engine's public face is the capacity read. The file owner `sessionFiles` for the `releaseSession` step a delete calls. Neither dependency crosses back into SessionStore. The assembly provides both; deployment chooses the instance. ### Operations @@ -106,39 +106,67 @@ Every operation takes one request object and answers one reply object. Writes ar | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `create` | Write one admitted Session and its optional worktree association | `{id, config, agentId, protocolVersion, leader?, origin, worktree?}` | `{}` | Before the transaction starts; a dropped future does not undo a commit | `invalid`, `workspace_missing`, `closed`, `storage` | +| `create` | Write one admitted Session and its optional worktree association | `{id, config, agentId, protocolVersion, leader?, origin, worktree?}` | `{}` | Before the transaction starts; a dropped future does not undo a commit | `invalid`, `workspace_missing`, `rejected` (reason `exists`), `closed`, `storage` | | `delete` | Remove a closed Session's output, visible rows and Timeline rows | `{id}` | `{hadRows}` | Before the first step; after the first commit the steps run to their end | `invalid`, `closed`, `storage` | -| `fork` | Copy a source's rows at a cut, with the target text decided from the source text under the fork's exclusion | `{source, id, at}` + `text` | `{}` | Before the first transaction; the callback's future is dropped | `invalid`, `rejected`, `closed`, `storage` | +| `fork` | Copy a source's rows at a cut, with the target text decided from the source text under the fork's exclusion | `{source, id, at}` + `text` | `{}` | Before the first transaction; the callback's future is dropped | `invalid`, `not_found`, `rejected`, `closed`, `storage` | | `creationRecord` | One Session's origin and leader link | `{id}` | `{origin, leader?}` | None | `not_found`, `closed`, `storage` | | `owner` | The Agent that owns a stored Session | `{id}` | `{agentId?}` | None | `closed`, `storage` | | `hasRecords` | Whether an id has any stored row | `{id}` | `{exists}` | None | `closed`, `storage` | | `sessionConfig` | A stored Session's decoded configuration | `{id}` | `{config?}` | None | `not_found`, `closed`, `storage` | | `catalog` | One stored Session page | `{request, agent?, version, hosts, closed}` | the stored page | While the page is read | `invalid`, `cancelled`, `closed`, `storage` | -| `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not) | `{id, query, page?}` | the query result | While the page is read | `storage`, `cancelled`, `closed` | +| `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not) | `{scope, query, page?}`; `scope` is `{key:{sessionId,branchId}, through, segments}` | `{result, next}` | While the page is read | `invalid`, `storage`, `cancelled`, `closed` | | `grants` | The Session's grant set | `{id}` | `{grants}` | None | `closed`, `storage` | | `addGrant` | Add one grant, never downgrading a write grant | `{id, path, kind, mode}` | `{}` | None | `not_found`, `invalid`, `closed`, `storage` | | `removeGrant` | Remove one grant; an absent grant counts as removed | `{id, path}` | `{}` | None | `closed`, `storage` | | `setLanguage` | Write the reply language into the stored configuration | `{id, language?}` | `{}` | None | `not_found`, `invalid`, `closed`, `storage` | | `title` | The title, its source and its committed revision | `{id}` | `{revision, title?: {text, source}}` | None | `not_found`, `closed`, `storage` | | `setTitle` | Commit the title the caller's change returns and announce it; the owner serializes writes | `{id}` + `change` | `{revision}` | The reply may be dropped; the admitted write is not cancelled | `not_found`, `rejected`, `closed`, `storage` | -| `associateWorktree` | Record a verified directory and the Session's subtree in one commit | `{id, repository, root, subtree}` | `{}` | None | `not_found`, `invalid`, `closed`, `storage` | +| `associateWorktree` | Record a verified directory and the Session's subtree in one commit; the same Session+directory association replaces the subtree | `{id, repository, root, subtree}` | `{}` | None | `not_found`, `invalid`, `closed`, `storage` | | `worktrees` | Recorded directories, with their last use when known | `{}` | `{directories}` | None | `closed`, `storage` | | `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `closed`, `storage` | | `sessionsUnder` | Stored Sessions whose workspace is a root or lies under it | `{root}` | `{sessionIds}` | None | `invalid`, `closed`, `storage` | -| `removeWorktree` | Remove one recorded directory under the Session exclusion, with the caller's own removal step | `{repository, root}` + `remove` | `{removed}` | The caller's step ends; the record stays | `invalid`, `in_use`, `rejected`, `closed`, `storage` | -| `removeUnregisteredDirectory` | Remove a directory no record names, under the Session exclusion, with the caller's own removal step | `{root}` + `remove` | `{removed}` | The caller's step runs to its end; no record is involved | `invalid`, `in_use`, `rejected`, `closed`, `storage` | +| `removeWorktree` | Remove one recorded directory under the Session exclusion, with the caller's own removal step | `{repository, root}` + `remove` | `{removed}` | The caller's step ends; the record stays | `invalid`, `not_found`, `in_use`, `rejected`, `closed`, `storage` | +| `removeUnregisteredDirectory` | Remove a directory no record names, under the Session exclusion, with the caller's own removal step | `{root}` + `remove` | `{removed}` | The caller's step runs to its end; no record is involved | `invalid`, `not_found`, `in_use`, `rejected`, `closed`, `storage` | -`worktree` in `create` and `associateWorktree` is `{repository, root, subtree}`: absolute UTF-8 paths, `subtree` inside `root`. The caller passes paths it already resolved; the owner re-checks that each is absolute, UTF-8 and, for an association, that the root still is a directory. +`worktree` in `create` and `associateWorktree` is `{repository, root, subtree}`: absolute UTF-8 paths, `subtree` inside `root`, and no `.` or `..` component. The caller passes paths it already resolved; the owner re-checks that each is absolute, UTF-8, has no relative component and, for an association, that the root still is a directory. + +#### Timeline face + +`timelineStore` is the same owner's Session-scoped Timeline face; SessionScope installs the binding at the Session instance (#2093). This contract owns the spellings. The face carries the line reads and the completion subscriptions; `createSession`, `releaseSession`, `rollbackSession` and `append` are the store's own creation and commit steps, and `sessionConfig`/`query` are the process `store` reads. + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `head` | A branch's last committed sequence | `{sessionId, branchId}` | `{sequence}` | None | `invalid`, `not_found`, `closed`, `storage` | +| `branches` | The branch set with its heads | `{sessionId}` | `{branches:[{info, sequence}]}` | None | `invalid`, `not_found`, `closed`, `storage` | +| `readPage` | One page of a branch's stored events | `{sessionId, branchId, after, limit, through}` | `{events}` | Before the reply | `invalid`, `not_found`, `cancelled`, `closed`, `storage` | +| `readSegments` | Several branch intervals in request order | `{sessionId, segments:[{branchId, from, through}]}` | `{segments}` | Before the reply | `invalid`, `not_found`, `cancelled`, `closed`, `storage` | +| `trace` | One stored trace at a position | `{sessionId, branchId, sequence}` | `{trace}` | None | `invalid`, `not_found`, `closed`, `storage` | +| `batchEnd` | Validate a batch boundary | `{sessionId, branchId, sequence}` | `{}` | None | `invalid`, `not_found`, `closed`, `storage` | +| `batchEndAt` | The containing batch's end sequence | `{sessionId, branchId, sequence}` | `{sequence}` | None | `invalid`, `not_found`, `closed`, `storage` | +| `saveSnapshot` | Store an acceleration snapshot | `{sessionId, branchId, snapshot}` | `{}` | None | `invalid`, `not_found`, `closed`, `storage` | +| `latestSnapshot` | The newest snapshot at or before a position | `{sessionId, branchId, through, interpreter}` | `{snapshot}` | None | `invalid`, `not_found`, `closed`, `storage` | +| `commits` | Register a completion listener for a Session | `{sessionId}` + `listener` | `{subscriptionId}` | The caller's unload withdraws it; an admitted batch is not replayed | `invalid`, `not_found`, `closed`, `storage` | +| `closeCommits` | Withdraw a completion listener; idempotent | `{subscriptionId}` | `{}` | None | `invalid`, `closed` | + +`readPage`'s `limit` is a target event count; the final complete atomic batch may exceed it. `through` is an inclusive committed sequence; a read never returns unpublished events. `readSegments` replies in request order with `{event, trace, batchEnd}` records. + +The completion notification is `{subscriptionId, batchId, branchId, through, result: "committed" | {code, message}}`, delivered after the batch is durable or has failed, in branch sequence order. `through` is the inclusive sequence of the batch's last event on `branchId`; it advances the durable watermark only for `"committed"`. A failed batch is reported once with its `batchId`, and later admissions for that Session are refused `storage` until the store releases it. A listener registered after a batch is admitted does not observe that batch; there is no replay. A slow observer never delays completion or release. + +Flows: + +- Admission is the store's internal step. A Session close waits for the store's release, which answers only after every admitted batch settled. +- The owner registers a listener with the calling row before returning; the row's unload withdraws it. +- `commits` and `closeCommits` on a closing generation answer `closed`; a pending read ends `closed`. ### Errors | Kind | What the caller does next | | --- | --- | -| `invalid` | Fix the request: an id that is not one path component, a relative or non-UTF-8 path, a subtree outside the root, an unknown language code, an invalid catalog cursor | +| `invalid` | Fix the request: an id that is not one path component, a relative or non-UTF-8 path or a `.`/`..` component, a subtree outside the root, an unknown language code, an invalid catalog cursor. A `removeUnregisteredDirectory` root that lies under a registered directory answers `invalid`; call `removeWorktree` for it | | `workspace_missing` | The creation's `cwd` no longer is a directory; the caller reports the failed creation and discards the worktree | -| `not_found` | No stored Session has the id; the caller decides whether that is a business error or an answer | +| `not_found` | No stored Session has the id, a fork source has no rows, or a removal has no matching record or directory; the caller decides whether that is a business error or an answer. A second removal answers `not_found` and does not call the removal step | | `in_use` | A Session association or a stored workspace still names the directory; delete that Session or refuse the removal | -| `rejected` | The caller's change, text or removal step refused with its own `code` and `message`; nothing was written and the caller acts on that code | +| `rejected` | The caller's change, text or removal step refused with its own `code` and `message`; nothing was written and the caller acts on that code. `create` with an id that already has rows answers reason `exists`; the caller reads the id instead of retrying | | `cancelled` | The caller stopped the read; nothing changed | | `closed` | This generation is unloading; call the replacement generation | | `storage` | The store failed; the caller reports the failure and keeps the Session or worktree for a retry | @@ -150,14 +178,14 @@ When a change, text or removal callback refuses, the operation answers `rejected | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `create` | Validate the id, take the exclusion, validate the workspace, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller keeps the id it supplied and decides whether to publish or delete the Session | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | -| `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove visible and Timeline rows, schedule the file sweep | Before the first commit: every row stays. After: the steps run to their end | The work continues under the owner's task; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | -| `fork` | Take the exclusion, read the source body, call `text`, copy in bounded transactions, write the target body and target rows in the last batch transaction, commit | Before the first copy; a refused text step copies nothing | The copy continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | +| `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove visible and Timeline rows, call `sessionFiles.releaseSession` | Before the handover: every row stays. After: the owner task runs to its end; dropping the caller's future does not stop it | The owner task continues; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | +| `fork` | Take the exclusion, read the source body, call `text`, copy in bounded transactions, write the target body and target rows in the last batch transaction, commit | Before the handover; a refused text step copies nothing | The owner task continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | | `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | | `catalog`, `query` | One consistent read under the caller's token | The read stops; no partial page | Nothing to release | Pending reads end `cancelled`; a new call ends `closed` | SessionStore | | `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | | `setTitle` | Admit the write behind earlier admitted writes, read the current title, call `change` under the serialization, write the returned title as revision + 1, commit, announce, answer the revision | Dropping the reply never cancels the admitted write; a change that refuses leaves the title unchanged | The change callback is revoked before it returns; the admitted write fails and the title stays | Close stops admission, waits for every admitted write | SessionStore; the change computes only | | `removeWorktree` | Validate the paths, take the exclusion, check associations and stored workspaces, call `remove`, delete the record on success, release | The removal step refuses with its own code (for example `cancelled`); the record stays | The callback ends; the record stays; the exclusion releases | New calls are refused `closed`; an in-flight removal ends, and the record stays unless the step succeeded | Directory by the caller; record by SessionStore | -| `removeUnregisteredDirectory` | Validate the root, take the exclusion, check stored workspaces under it, call `remove`, release | The removal step refuses with its own code; nothing changes | The callback ends; the exclusion releases | New calls are refused `closed`; an in-flight removal ends | Directory by the caller; exclusion by SessionStore | +| `removeUnregisteredDirectory` | Validate the root, take the exclusion, check stored workspaces under it, run the removal step as the owner's task, release | The removal step refuses with its own code; nothing changes | The owner task continues to the end and the exclusion is not released to the caller | New calls are refused `closed`; the running removal finishes and keeps the lock until it ends | Directory by the caller; exclusion by SessionStore | ## Exceptions with reasons @@ -166,6 +194,8 @@ When a change, text or removal callback refuses, the operation answers `rejected - `setTitle` runs the caller's change under the owner's serialization: the change only computes the next title from the current title and revision, and returns its own refusal; the reply may be lost, so the caller re-reads rather than assumes failure. - `removeWorktree` runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. The exclusion has no time bound: a recursive forced deletion of an unregistered directory may run to its end, and `removeUnregisteredDirectory` uses the same exclusion for a directory no record names. - `owner` answers the Agent id for a delete notice; the Agent directory's own records are not returned here. +- `associateWorktree` dedupes the directory record by `(repository, root)`: a repeated association for the same Session and directory replaces the subtree and updates its last use, and a new directory inserts one record. A retry after a lost reply therefore leaves one record and the caller's latest subtree. +- `setTitle`'s change runs inside the owner's serialization and must not call `store` operations that take the same lock; it computes the next title only. ## Client-visible changes @@ -180,6 +210,12 @@ None. The client methods (`session.rename`, `sessions.list`, `session.delete`, ` - [Session title metadata](../appserver/session-title-metadata.md): §1 Write and Binding, §4.1, §4.2, §5, §6, §10 and Appendix A. - [SessionTitle](SessionTitle.md): the metadata/notice row, the A.4 Write row and the Appendix G title metadata row. - [Worktree access §4](../worktree-access.md): the `associateWorktree` sentence. +- [TypeScript plugin authoring](../../typescript-plugin-authoring.md): the title row (`sessionMetadata`, revision-checked `setTitle`). +- [Plugin contract](../plugin-contract.md): the `sessionMetadata` process-name row. +- [Session deletion and fork](../appserver/session-deletion-and-fork.md): the Worktree association port paragraph. +- [Overview](../overview.md): the SessionStore row. +- [Resource faces §1](../resource-faces.md): the `store` and `timelineStore` rows. +- [Service faces §4.8](../service-faces.md): the `associateWorktree` code block. ## Verification @@ -192,6 +228,7 @@ Flow tests on the owner: - The change receives the current title, its source and revision; a change that returns `Rejected` leaves the title and revision unchanged; concurrent changes commit in admission order and each announces its revision; a dropped reply still commits and announces; close waits for the admitted write. - `removeWorktree` answers `in_use` while an association or a stored workspace remains; a failed or cancelled removal keeps the record; a successful removal deletes it; a concurrent creation waits for the removal and then either associates with the surviving directory or fails on the missing workspace. - A call in flight when the generation closes ends `closed`; a dropped callback keeps the record. +- A dropped `delete` or `fork` future still runs to its end on the owner task: the delete leaves rows and output consistent, and a fork never becomes visible half-copied. Material uncertainty: a process death during the caller's removal step leaves the record; the directory state is Git's, and a later `worktrees`/`remove` reconciles the pair. Review checks that no caller treats `rejected` as success. @@ -226,6 +263,9 @@ Material uncertainty: a process death during the caller's removal step leaves th 2. **SessionScope (#2025): `timelineStore` ownership aligned.** This owner owns the Timeline operations and the `timelineStore` face; SessionScope binds that face at the Session instance. The face does not carry `createSession`, `releaseSession`, `rollbackSession` or `append`; those belong to the store's own creation and commit paths. The process `store.query` and `store.sessionConfig` are the same engine's reads for callers outside a Session (loaded or not) and keep one implementation. A comment on #2025 records the alignment. + +The delivery part maps the current codes to these kinds: `creationRecord`, `title` and `associateWorktree` move from `closed` to `not_found`; a worktree removal conflict moves from `invalid` to `in_use`; a missing `cwd` moves from `invalid` to `workspace_missing`; `delete` answers `hadRows` instead of `removed`. + ## Binding appendix The `store` face is one hand-written `HostDispatch` on `SessionStore`; the wire name stays `store`. `setTitle` is admitted in `invoke` before its reply future is returned, so a wire caller that drops the reply still commits. `Store` the wrapper, `SessionMetadata` and `WorktreeAssociations` no longer exist. `caller: &Ctx` is rutis's caller parameter: the dispatch fills it from the calling row, so no caller sends or names a row. `CancelledFn` is the binding's cancellation argument. @@ -237,6 +277,15 @@ use std::future::Future; use dim_agent_types::grant::{GrantKind, GrantMode, SessionGrant}; use rutis::Ctx; +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SessionOrigin { + Client, + Acp, + Internal, + Automation, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Worktree { @@ -274,7 +323,7 @@ pub struct CreateSession { pub agent_id: String, pub protocol_version: u32, pub leader: Option<String>, - pub origin: dim_agent_types::SessionOrigin, + pub origin: SessionOrigin, pub worktree: Option<Worktree>, } diff --git a/docs/design/plugins/SqliteStorage.md b/docs/design/plugins/SqliteStorage.md index 224ede8899..5622153979 100644 --- a/docs/design/plugins/SqliteStorage.md +++ b/docs/design/plugins/SqliteStorage.md @@ -55,24 +55,34 @@ None. The assembly provides the store; deployment chooses its instance. Offline ### Operations +`storageReport` is the only service operation on the `sqliteStorage` face. + | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `storageReport` | The store's own file bytes, WAL bytes and reclaimable bytes | `{}` | `{databaseBytes, walBytes, reclaimableBytes}` | None | `closed`, `storage` | -| `backup` | Copy a closed store and its sidecar files into an archive | the database path and the destination | `{}` | None; the tool runs alone | `owned`, `format`, `storage` | -| `restore` | Write a store from an archive produced by `backup` into a destination that does not exist | the archive and the destination | `{}` | None; the tool runs alone | `format`, `storage` | -| `vacuum` | Remove the content rows no stored reference reaches and reclaim the file's free pages | the database path | the removed rows, content bytes and sizes | None; the tool runs alone | `owned`, `format`, `storage` | -`storage.report` is the client method registered through `managementMethods`; the registration point calls `storageReport` and is not a second operation. The transaction operations the data owners use are private to the storage crate and are listed in their owners' contracts. +`storage.report` is the client method registered through `managementMethods`; the registration point calls `storageReport` and is not a second operation. + +### Offline operations (not service) + +These are the owner's Rust functions for the CLI, the migration tool and the operator. They do not cross the service face, take no request object and are not in the catalog. + +| Function | Intent | Input | Reply | Exclusion | Errors | +| --- | --- | --- | --- | --- | --- | +| `backup` | Copy a closed store and its sidecar files into an archive | the database path and the destination | `{}` | the store's file lease | `owned`, `format`, `storage` | +| `restore` | Write a store from an archive into a destination that does not exist | the archive and the destination | `{}` | the destination must not exist | `format`, `storage` | +| `vacuum` | Remove content rows no stored reference reaches and reclaim free pages | the database path | the removed rows, content bytes and sizes | the store's file lease | `owned`, `format`, `storage` | + +The transaction operations the data owners use are private to the storage crate and are listed in their owners' contracts. ### Errors +The face answers `storage` or `closed` only; the offline functions answer their own `owned`, `format` or `storage` in the section above. + | Kind | What the caller does next | | --- | --- | -| `storage` | The read or the offline operation failed; the caller reports its own failure | -| `owned` | Another process holds the file's lease; wait for it to exit and retry the offline operation | -| `format` | The file is not the current format; open it with the daemon that upgrades it, or with a matching version | - -The engine answers no business error: a missing row, a stale version or a refused change is the data owner's, expressed by that owner's operation. +| `storage` | The read failed; the caller reports its own failure | +| `closed` | This generation is unloading; call the replacement generation | ### Flows @@ -164,10 +174,6 @@ pub struct Capacity { pub enum StorageError { #[error("{message}")] Storage { message: String }, - #[error("{message}")] - Owned { message: String }, - #[error("{message}")] - Format { message: String }, #[error("the store is unloading")] Closed, } @@ -186,4 +192,4 @@ impl SqliteStorage { } ``` -`backup_store`, `restore_store` and `vacuum_store` remain the owner's functions with the signatures the CLI and the migration tool use; they take the same lease and are not service operations. +`backup_store`, `restore_store` and `vacuum_store` remain the owner's functions with the signatures the CLI and the migration tool use; they are not service operations, and their `owned`/`format` errors belong to those functions, not to `StorageError`. diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index 7be0586799..2c37a7ece8 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -17,7 +17,7 @@ Resource and state operations use these public data faces: | --- | --- | --- | --- | | `execHost` | `start`, `wait`, `kill`, `settle`, `output`, `tail`, `removeOutputDirectory`, `shell`, `write`, `resize`, `info`, `confined`, `configured` | the process owner | #1295 | | `fsHost` | tool family: `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`; storage family: `stat`, `readBytes`, `openRead`, `readAt`, `closeRead`, `lock`, `unlock`, `backup`, `createDirectory`, `replace`, `list`, `remove` | the file-operations owner | #1297 | -| `store` | Session-row repository operations (§5.2) | the process state owner | #1298 | +| `store` | This row is superseded by [the SessionStore contract](plugins/SessionStore.md). | — | #1298 | | `timelineStore` | This row is superseded by [the SessionStore contract](plugins/SessionStore.md). | — | #1298 | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index a6cf31af28..5c7a7f7a60 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -250,7 +250,7 @@ workflowRuns.call(RunRequest) 本节由 [SessionFiles 契约](plugins/SessionFiles.md) 取代。 -文件导入、分块读取、归属操作的参数、回复、错误及取消语义均由 §9.1 定义。文件传输使用按路径导入与有界读取操作。 +文件导入、分块读取与归属操作的参数、回复、错误及取消语义见 [SessionFiles 契约](plugins/SessionFiles.md)。 进程内绑定和 wire 的行为一致性由 `session_files_flow.rs` 与 `attachments_flow.rs` 验证。 @@ -311,8 +311,7 @@ skillsConfig.get() -> {instructions?} collaborationConfig.get() -> {leaderDescription?, memberDescription?} -- Collaboration 的 factory 文本;null 表示内置 store.associateWorktree {id, repository, root, subtree} -> {} - -> error {code: failed, message} - -- 路径按 §1 是 UTF-8 字符串;一次写入仍由 SessionStore 的原子事务保证 + -- 路径与错误见 [SessionStore 契约](plugins/SessionStore.md#operations) ``` - `agentConfig` 在 runtime 的 catalog 注册 shared instance;`SessionScope` 已经提供值,`get` 返回同一个快照。 配置快照直接使用所有者的数据定义,接收端允许未知字段;公开类型名称的迁移见[插件配置类型兼容性说明](../release/README.md#plugin-configuration-type-compatibility)。 diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index 0d1cf4d84d..59cb0c0ba0 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -40,7 +40,7 @@ provider and the methods it serves to other languages. This table says which to | Start or drive another Session | `sessions`, process | Implemented by Agents; all nine methods are typed. | | Publish events to subscribed branches | `eventHub`, process | Implemented by EventHub: `declare` and `publish`, served to the calling row. Inject it: the row loads only while EventHub runs and declares at `apply`. | | Read current branch permissions or host defaults | `sessionPermissions`, process | Generated from Agents: `permission({sessionId, branchId})` and `permissionDefaults({})`. | -| Read or set a Session's title | `sessionMetadata`, process | Implemented by SessionStore: `read` and the revision-checked `setTitle` ([title metadata](design/appserver/session-title-metadata.md)). SessionTitle is the title's one writer; other plugins only read. | +| Read or set a Session's title | `store`, process | This row is superseded by [the SessionStore contract](design/plugins/SessionStore.md#operations): `title` and `setTitle(id, change)`. SessionTitle is the title's one writer; other plugins only read. | | Read/update business configuration | `settings`, process | Owner registration, read/write and Settings event delivery implemented; a row registers its sources with `register` in its `apply`. | | Read/save Workflow definition files | `workflowFiles`, process | Generated `read/list/replace/createDirectory`; fixed project directories and the calling row's read-only packages ([contract](design/p6-p7-bindings.md#3-workflow-definition-files)). | | Offer model tools | `toolRegistry`, Session | A Session part registers each tool with `register` ([Session tools](#session-tools-and-client-methods)). | diff --git a/docs/zh/design/appserver/session-files.md b/docs/zh/design/appserver/session-files.md index 683a8799b7..3cb5ce3802 100644 --- a/docs/zh/design/appserver/session-files.md +++ b/docs/zh/design/appserver/session-files.md @@ -287,31 +287,7 @@ CREATE INDEX session_file_owners_by_file ON session_file_owners(file_id) ### 9.1 语言中立形式(ADR 002 D5) -`sessionFiles`,进程作用域,无实例键,由 SessionStore 提供。 - -| 方法 | 方式 | 请求 | 回复 | -| --- | --- | --- | --- | -| `put` | async | `{sessionId: string, name: string, content: string}`,`content` 是字节的 base64 | `{fileId: string, path: string, bytes: u64}` | -| `import` | async | `{sessionId: string, name: string, source: string}`;已授权的本地绝对源路径 | `{fileId: string, path: string, bytes: u64}` | -| `read` | async | `{sessionId: string, fileId: string, offset: u64}` | `{data: string, eof: bool}`;最多 64 KiB 字节的 base64,空块时 `eof` 为 true | -| `register` | async | `{sessionId: string, path: string}`(ADR 013) | `{}`;Session 不存在时为 `not_found` | -| `owns` | async | `{sessionId: string, path: string}` | `{owned: bool}` | -| `owned_paths` | async | `{sessionId: string}` | `{paths: string[]}`,一个 Session 文件目录及每条输出路径 | - -`sessionFiles` 是数据面:catalog 共享此名称,SessionStore 在 Rust 类型键和 -`host_key("sessionFiles")` 提供同一个 `SessionFiles` 绑定。原生调用直接进入 owner, -wire 调用在边界解码后调用同一组操作。 - -`import` 沿用 `put` 的 Session、名称、16 MiB 上限、pending/owned 事务、权限与取消规则。 -FileStorage 固定源文件并以 64 KiB 缓冲复制;源文件增长或截短时在发布前失败。 -调用方负责授权源路径访问。`read` 只读取指定 Session 拥有的不可变文件,其他 Session -的 fileId 返回 `not_found`。位于 EOF 或之后的偏移返回空块;放弃 wire 调用会取消它。 - -- `path` 是 Session 资源节点上的绝对路径,与 `read` 为该 Session 解析的结果一致;`bytes` 是保存的长度。 -- `register`、`owns` 和 `owned_paths` 是 ADR 013 的所有权接口。`register` 解析路径并在调用方把路径交给模型之前记录;`owns` 同时读取两张所有权表,ADR 014 把它读作写入的 Session 自有事实。 -- 取消是协议动作:调用方放弃调用,或发送桥接协议的取消请求。取消在 txn 2 之前有效;之后文件已提交,回复有效。 -- 错误是数据 `{code, message}`(§10)。 -- SessionStore 不提供修改、重命名或移除单个文件的操作。共享和释放只发生在 S5c 的分叉和删除事务内,它们是 SessionStore 自己的 Rust 步骤,不是服务方法。 +「本节由 [SessionFiles 契约](../../../design/plugins/SessionFiles.md) 取代。」 ### 9.2 Attachments 如何使用 diff --git a/docs/zh/design/overview.md b/docs/zh/design/overview.md index 25c3171d17..9b323be989 100644 --- a/docs/zh/design/overview.md +++ b/docs/zh/design/overview.md @@ -504,7 +504,7 @@ ADR 002 中记录的 HostPlatform exec shell 变更(作为业务配置在每 | Transport, Connection | 变更 | 带升级认证器的 `EntryHost`;`ConnectionEntry {name, deviceId}` | RemoteGateway | | Agents | 补充 | `sessions` 服务([sessions 服务](appserver/sessions-service.md));`SessionConfig.interactive`;策略以启动方为上限的 `launch`,`LaunchRequest.agent` 可选(缺省为 Agents 的默认 profile;请求的 `model` 优先于 profile 的模型);从另一个 Session 的切点创建([删除与分叉](appserver/session-deletion-and-fork.md#6-分叉));经 Agents 的 Session 入口提供 `session.agent.update` 与 `session.agent.get`,按精确 profile ID 解析并采纳提示词和模型,并读回分支采纳的 profile | Scheduler、Workflow、fork、`/agent` | | Collaboration | 变更 | 成员模型:由用户的[子 agent 模型策略](../../design/subagent-model-policy.md)决定(`agent`:profile 的模型,否则为默认选择;`inherit`;`fixed`);成员的审批请求作为一条 `input/message` 送到 leader 分支;leader 模型通过 Collaboration 的工具回答,这次工具调用经过 leader 的 Approval 与 Permission,Collaboration 通过 Approval 的公开 respond 操作写入回答(Approval 不变,#29);按类型的成员提供方(`collaborationMembers:<kind>`,每次调用查找),用于不是 dim Session 的成员,其询问走同一条成员审批路径;`agent` 工具保持现有风险分类([ExternalAgent §9.2](plugins/ExternalAgent.md#92-collaboration-成员提供方)) | ExternalAgent | -| SessionStore | 补充 | 带修订检查的标题元数据,只通过 `setTitle` 写入,变更时发出 Session 广播通知(进程级状态的所有者都发出这类通知)(S5b,已实现:`sessionMetadata` 服务,[标题元数据](appserver/session-title-metadata.md));删除与清理;fork(复制切点之前的事实)(S5c,已实现:[删除与分叉](appserver/session-deletion-and-fork.md));资源节点上的 Session 文件,fork 时共享,随最后一个所有者删除(S5a,已实现:`sessionFiles` 服务,[Session 文件](appserver/session-files.md)) | SessionTitle、Attachments、fork | +| SessionStore | 补充 | 「本行由 [SessionStore 契约](../../design/plugins/SessionStore.md) 与 [SessionFiles 契约](../../design/plugins/SessionFiles.md) 取代。」`store.title`/`setTitle(id, change)`、删除与清理、fork、Session 文件与 `session_grants` 行 | SessionTitle、Attachments、fork | | Settings | 补充 | S8a(Rust,已实现):每个所有者一个或多个具名业务来源,每个来源一种文档类型;没有自己的订阅接口:写入提交后在 `settings/<source>` 上发出 rutis 事件 `settings.changed` `{source, scope, revision}`,覆盖用户和项目作用域,不带文档内容;新授权的项目发出 `settings.project_authorized`;校验和默认值只在 Settings 边界应用;v13 `settings_documents` 契约下增量的 `user/<source>` 行(D4)。S8b(随 C4,已实现):语言中立的 `settings` 服务,在 C4 行上声明 JSON Schema、默认值、允许的作用域和仅限用户的字段;管理方法 `settings.read`/`settings.update`/`settings.sources`/`settings.projects`;不提供凭据服务(§6.4) | 每个有业务配置的插件,包括用户编写的 Scheduler 任务(来源 `schedule`)和 Workflow 定义(来源 `workflow`) | | Provider | 补充 | 基于捕获的已采纳模型配置,校验并映射已声明的 effort/tier 偏好;`AuxiliaryModel` 服务:`complete(model, request)`,在任何 Session 之外的一次非流式调用,模型由调用方从自己的配置中传入([设计](appserver/auxiliary-model.md));[Desktop/CLI 管理补充提案](appserver/provider-management.md):安全连接编辑、模型生命周期和仅供客户端采用的偏好;按 Modality 类别的非对话连接 | `/effort`、`/fast`、SessionTitle、Modality | | `pluginFiles`(`PluginFilesPlugin`) | 补充 | 二进制读写与格式版本([受信插件存储](../../../crates/dim-app-server/README.md#trusted-plugin-storage));代码位置不变 | Scheduler、Workflow、Modality、RemoteGateway、PluginManager、ExternalAgent | diff --git a/docs/zh/design/plugin-contract.md b/docs/zh/design/plugin-contract.md index 8798193f08..dd2cbb952a 100644 --- a/docs/zh/design/plugin-contract.md +++ b/docs/zh/design/plugin-contract.md @@ -96,7 +96,7 @@ process (root) process parts: storage, catalogs, connections, Ag | --- | --- | --- | --- | --- | | `sessions` | 进程 | Agents | 是 | 启动或驱动另一个 Session | | `sessionPermissions` | 进程 | Agents | 是 | 标记了 `#[rutis::service]` | -| `sessionMetadata` | 进程 | SessionStore | 是 | SessionTitle 是标题的唯一写入方 | +| `store` | 进程 | SessionStore | 是 | 标题、授权、语言、worktree 记录与关联;契约见 [SessionStore](../../design/plugins/SessionStore.md) | | `settings` | 进程 | Settings | 是 | 业务配置 | | `auxiliaryModel` | 进程 | 该配置中模型选择的所有者 | 是 | 辅助模型请求 | | `pluginFiles` | 进程 | 宿主 | 是,当宿主提供根目录时 | 进程部件自己的文件 | diff --git a/docs/zh/design/plugins/SessionTitle.md b/docs/zh/design/plugins/SessionTitle.md index 182fcc8832..142313ed7b 100644 --- a/docs/zh/design/plugins/SessionTitle.md +++ b/docs/zh/design/plugins/SessionTitle.md @@ -31,7 +31,7 @@ App Server 测试不依赖 SessionTitle,仅覆盖通用宿主行为。验证 | 观察 | 从 `sessionIdentity` 读取 Session id,从 `sessionConfig` 读取创建配置,从 `sessionLifecycle` 读取 closing([插件契约](../plugin-contract.md#9-向机制所有者提出的需求) R2),然后读取自身 Session 的 `session/{sessionId}` 通道记录。C4 广播 #180 已交付;#63/#168 已关闭。 | | 历史 | 使用已实现的进程 sessions.history,不读取私有 TimelineTree,也不使用分支(C5)绑定。 | | 配置 | 沿用具名 Settings 和原行来源声明,仅用户作用域(A.3/A12)。每次决定读取 settings.read({source:"session-title",scope:"user"}),直接使用已校验并补默认值的文档。 | -| 元数据/通知 | S5b #60/#96 定义进程服务 `sessionMetadata`(`read` 与 `setTitle`,都是异步)、它的错误 `conflict`/`not_found`/`storage`、交接点,以及 v3 列表字段 `title`/`titleSource`/`titleRevision`([标题元数据](../appserver/session-title-metadata.md));A.2 复述该合同。每次提交后 SessionStore 调用 `session_broadcast::notify`,Rpc 把记录以 `session.notice {sessionId, source, kind, data}` 转发给已附加的 v3 客户端(C6 #49/#85,[Session 广播通知](../appserver/session-notices.md))。名称、模式、交接和错误遵循 S5b。 | +| 元数据/通知 | 「本行由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代。」v3 列表字段为 `title`/`titleSource`/`titleRevision`;每次提交后 SessionStore 调用 `session_broadcast::notify`,Rpc 把记录以 `session.notice {sessionId, source, kind, data}` 转发给已附加的 v3 客户端(C6 #49/#85,[Session 广播通知](../appserver/session-notices.md))。 | | 辅助请求 | 该配置中模型选择的所有者已实现 AuxiliaryModel 及具名 `auxiliaryModel.complete` HostDispatch/catalog 绑定:产品配置里是 Provider,model-config 配置里是 ConfiguredModels。通过普通 C4 依赖注入;凭据仍归该所有者([S4 §4.3](../appserver/auxiliary-model.md#43-具名绑定))。 | | 策略 | A1–A12 定义首版实现。附录 D 要求公开流程验收;文档 CI 不表示运行时验收。 | @@ -48,9 +48,9 @@ atLeast 与 through,直接使用原生 HistoryPage/AgentEvent。S2 稳定目 沿用[插件绑定合同](../rutis-usage.md):插件的唯一一行注入 `partRegistry`, 注册 Session 部分,每个 Session 挂载一份副本。该部分注入 `sessionMethods`,并在 `apply` 中把 `session.rename` 注册到它;它不提供服务。 -插件仅依赖 Settings 与 sessionMetadata 的既有公开 Rust 绑定;历史回复在本插件的命名服务边界解析一次。插件行为与跨插件标题流程位于插件 crate 的 tests,使用公开客户端与宿主 API;App Server 测试不依赖该 crate,也不隐式安装标题插件。`apply` 读取 Session 标识和创建配置, +插件仅依赖 Settings 与 `store` 的既有公开 Rust 绑定;历史回复在本插件的命名服务边界解析一次。插件行为与跨插件标题流程位于插件 crate 的 tests,使用公开客户端与宿主 API;App Server 测试不依赖该 crate,也不隐式安装标题插件。`apply` 读取 Session 标识和创建配置, 登记观察/清理,不启动异步初始化任务;创建配置不可变。同一部分注入必需依赖:进程服务 -`sessions`、`settings`、`sessionMetadata` 和 `auxiliaryModel`,以及 Session 服务 `sessionIdentity`、 +`sessions`、`settings`、`store` 和 `auxiliaryModel`,以及 Session 服务 `sessionIdentity`、 `sessionConfig`、`sessionLifecycle` 和 `sessionMethods`。可选的 `sessionTitleGenerator` 遵循[必需/可选绑定契约](../rutis-usage.md#3-按名字的服务),在使用时按名字读取,不注入,也不影响 Ready。 产品装配独立于外语插件行安装原生插件。 @@ -96,7 +96,7 @@ flowchart LR | 部件 | 作用域 | 依赖 | 提供 | | --- | --- | --- | --- | | `session-title` | 进程 | Settings 和部件注册表 | 注册 Settings 来源及 Session 部分 | -| `SessionTitle` | Session | Session 服务 `sessionIdentity`、`sessionConfig`、`sessionLifecycle` 和 `sessionMethods`;进程 sessions 历史、Settings、标题元数据 `sessionMetadata`(S5b)和必需的 `auxiliaryModel`(提供者缺失使整行 Pending);按需读取可选的 `sessionTitleGenerator` | 把 session.rename 注册到 sessionMethods | +| `SessionTitle` | Session | Session 服务 `sessionIdentity`、`sessionConfig`、`sessionLifecycle` 和 `sessionMethods`;进程 sessions 历史、Settings、标题元数据 `store`(S5b)和必需的 `auxiliaryModel`(提供者缺失使整行 Pending);按需读取可选的 `sessionTitleGenerator` | 把 session.rename 注册到 sessionMethods | 依赖位于 Session 或外层进程。C4/S2/Settings 已提供观察、前缀读取和配置;S5b 提供标题元数据,C6 提供通知;该配置的模型选择所有者提供具名辅助模型操作。插件的行在其 apply 中登记来源。真实提供者重载会取消该行工作(ADR 002 D3),S2 索引重载不会。业务数据更新不重载插件(D4)。 @@ -169,7 +169,7 @@ sequenceDiagram ST-->>Rpc: title,titleSource manual,revision ``` -Rpc 与处理任何 Session 方法一样解析 Session,必要时加载它。遇到 `conflict` 时 SessionTitle 重新读取并重试,至多 3 次。 +Rpc 与处理任何 Session 方法一样解析 Session,必要时加载它。`rejected` 的 change 是 SessionTitle 自己的拒绝;操作者的标题在 change 内决定。 ### 3.3 生成分流与可选服务 @@ -199,7 +199,7 @@ SessionTitle 不接触凭据或 issuer,DimOAuth 不写 Session 元数据、不 `sessions.launch` 可以携带 `title`,即调用方已经知道的那个标签([sessions 服务 §6.1](../appserver/sessions-service.md#61-launch))。Agents 把它存进新 Session 的固定配置 `initialTitle`;标题的唯一写入者仍是 SessionTitle,因此调用方写下的标题从不直接到达存储。 -- **只写一次。** 只有在存储的 revision 为 0 时才写。之后的重命名或清空不会在重载时被撤销:配置里一直保留 `initialTitle`,而一旦已有标题,这一部分就跳过写入。`setTitle` 返回 `conflict` 表示别的写入者先给了标题,那个标题胜出。 +- **只写一次。** 只有在存储的 revision 为 0 时才写。之后的重命名或清空不会在重载时被撤销:配置里一直保留 `initialTitle`,而一旦已有标题,这一部分就跳过写入。change 看到当前标题,别的写入者先提交的标题在 change 内决定。 - **文本规则。** 就是 `session.rename` 的规则:去掉首尾空白;为空、含控制字符或行分隔符时什么都不写。长度按兜底标题的方式截到操作者的 `maxLength`,标点保留:`title_text` 去掉标点是因为它处理模型输出,而这段文本是调用方的。 - **时机。** 写入在 `apply` 之后、Session 发布之后,在部件自己的任务里进行,因此启动回复可能先到。标题通知发出后行上就有标题,与重命名走的是同一条路径。 - **对所有 Session。** 交互与非交互都一样:初始标题不需要模型,也不受生成资格的约束。生成保持原有门槛([§4](#4-时序与冲突));已有标题的 Session 本来就会被生成跳过。 @@ -215,7 +215,7 @@ sequenceDiagram R->>Meta: setTitle(expected r, manual) Meta-->>R: r+1 G->>Meta: setTitle(expected r, auto) - Meta-->>G: conflict + Meta-->>G: rejected Note over G: 自动标题被丢弃 ``` @@ -291,7 +291,7 @@ SessionTitle 使用这些已交付合同。 | 对序号、批次、中断、重载的影响 | 没有序号,不属于批次;不重放:重新订阅的客户端通过所有者的查询(`session.summaries`)读取当前状态;不受中断影响;发出方重载只会让通知停止。 | | 由谁实现,对应 issue | 运行时 C6 [#49](https://github.com/arcships/dim/issues/49),在 [#85](https://github.com/arcships/dim/pull/85) 实现:记录、`session_broadcast::notify` 和 Rpc 的 `session.notice`([Session 广播通知](../appserver/session-notices.md))。SessionStore 发出标题通知([S5b](../appserver/session-title-metadata.md),即[总体设计附录 B.2](../overview.md#b2-app-server-进程插件) 中的补充)。 | -**#4:无。** 观察沿用 Session 服务和 Session 通道;历史、Settings、`sessionMetadata` 和辅助模型均为进程服务。SessionTitle 不注入分支服务。 +**#4:无。** 观察沿用 Session 服务和 Session 通道;历史、Settings、`store` 和辅助模型均为进程服务。SessionTitle 不注入分支服务。 **模型选择所有者(S4):具名 `auxiliaryModel` 绑定。** Provider(产品)与 ConfiguredModels(model-config)将既有的 `AuxiliaryModel` 操作绑定为可供 C4 注入的服务([S4 §4.3](../appserver/auxiliary-model.md#43-具名绑定))。配置中没有这样的所有者时,普通的必需依赖让 SessionTitle 行保持 Pending。不需要 core 新机制。 @@ -313,8 +313,8 @@ SessionTitle 使用这些已交付合同。 | 服务 | 方法 | 类型 | 请求 | 回复与错误 | | --- | --- | --- | --- | --- | -| SessionStore `sessionMetadata`(S5b) | `read` | 异步 | `{sessionId}` | `{revision, title: {text, source: "auto" \| "manual"} \| null}`;错误 `not_found`、`storage`([S5b §4](../appserver/session-title-metadata.md#4-操作)) | -| SessionStore `sessionMetadata`(S5b) | `setTitle` | 异步 | `{sessionId, expectedRevision, title: {text, source} \| null}` | `{revision}`;错误 `conflict`、`not_found`、`storage`。调用即交接;提交后 SessionStore 发出标题通知 | +| SessionStore `store` | `title` | 异步 | `{id}` | `{revision, title: {text, source: "auto" \| "manual"} \| null}`;错误 `not_found`、`closed`、`storage`([SessionStore](../../../design/plugins/SessionStore.md#operations)) | +| SessionStore `store` | `setTitle` | 异步 | `{id}` 加 change 回调 | `{revision}`;错误 `rejected`、`not_found`、`closed`、`storage`。调用即交接;提交后 SessionStore 发出标题通知 | | SessionStore(S5b) | 标题通知 | Session 广播通知(C6 记录,§9) | — | 在该 Session 的广播频道上发出 `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}`;没有序号,不重放 | | `AuxiliaryModel`(该配置的模型选择所有者) | `complete` | 异步 | `{model: {providerId, modelId}, request: {system, messages: [{role: "user", content: 文本}]}}`,可选 `cancelled: () => Promise<void>`([S4 §4.3](../appserver/auxiliary-model.md#43-具名绑定)) | `{text, stopReason, usage}`;以既有错误码/message 拒绝。超时或 closing 时完成取消引用,并等待原调用结算 | @@ -339,10 +339,10 @@ Settings 来源 `session-title`,一个文档:`enabled: bool` 默认 `true` | 监听 | 该部分在每个 Session 的副本于 `apply` 中监听自身 Session 的 `session/{sessionId}`,筛选 main input/applied,登记自持任务后返回;`sessionLifecycle.closing()` 或副本清理结束自持工作 | | 资格 | C4 创建快照:`interactive !== false && collaborationRole === "leader"`(用于生成);原生省略值表示 true。创建时请求的初始标题(`initialTitle`,§3.4)对交互与非交互 Session 都写入:它不需要模型,文本属于调用方 | | 触发 | 收到位于 `N` 的 `input/applied` 时:若不具资格、已禁用、有在途生成或失败次数 ≥ 3(A5)则跳过;否则启动一个归属插件生命周期的生成任务 | -| 检查 | `sessionMetadata.read({sessionId})`:已有任何标题则跳过;记下 revision `r` | +| 检查 | `store.title({id})`:change 从当前标题与 revision 决定;`rejected` 时丢弃 | | 读取 | 既有 sessions.history 以 atLeast=N 固定已发布 T >= N,再按 through=T 分页 (S2 A.5)。选取第一条有 user 内容、或是 Goal 的 `goal:state` 记录 (含 objective),且 input/applied 的输入;没有该输入/文本则不生成 (A8/A10) | | 生成 | 按 §3.3 分流,在共享 30 秒预算内生成或兜底;取第一行、去除引号与末尾标点、折叠空白并按 maxLength 截断 | -| 写入 | `setTitle({sessionId, expectedRevision: r, title: {text, source: "auto"}})`;`conflict` 或 `not_found` 时丢弃 | +| 写入 | `setTitle({id}, change)`,change 返回生成的标题或 `null`;`rejected` 或 `closed` 时丢弃 | | Timeline | 不写入,不登记 Dispatcher,无 `StateCell` | | 重载 / 卸载 | 存储交接前取消,已接纳修改由所有者结算;间隙事件不重放 | @@ -356,7 +356,7 @@ Settings 来源 `session-title`,一个文档:`enabled: bool` 默认 `true` | 第一条输入在被应用前被撤回(`session.input.withdraw`) | input < withdraw < `input/deleted` | 从未被应用:不生成,文本从不发送;第一条被应用的符合条件的输入触发 | SessionTitle | | 第一条用户输入只含图片 | — | 无自动标题(A8) | SessionTitle | | 检查之前重命名 | rename < check | 已有标题:跳过 | SessionTitle | -| 生成期间重命名 | check (r) < rename (r+1) < write | `conflict`:自动标题被丢弃 | SessionStore revision | +| 生成期间重命名 | check (r) < rename (r+1) < write | `rejected`:自动标题被丢弃 | SessionStore revision | | 并发重命名 | revision 顺序 | 最后提交的重命名胜出 | SessionStore | | 重复的 `session.rename` | — | 重写相同文本 | SessionTitle | | 第一条之后的 Steer/Queue/Append 输入 | — | 从不进入摘录 | SessionTitle | @@ -376,7 +376,7 @@ Settings 来源 `session-title`,一个文档:`enabled: bool` 默认 `true` | --- | --- | | 模型错误、超时、空输出、策略不可用 | 输入文本兜底(§3.3);取消不降级 | | Settings 读取失败 | 自动:不写入、诊断、计入失败;重命名:`storage_failed`。不使用回退文档 | -| 自动写入时 `setTitle` 返回 `conflict` | 丢弃(诊断) | +| 自动写入时 `setTitle` 返回 `rejected` | 丢弃(诊断) | | `setTitle` 返回 `storage` | 自动:计入失败;重命名:`storage_failed` | | 重命名时 Session 未知 | `session_not_found` | | SessionTitle 正在重载 | 交接前:service_reloading,无重命名;交接后/回复丢失:读取元数据,不推断未提交,不重复写入 | @@ -439,7 +439,7 @@ A1–A12 是首版实现采用的策略。 | 生成任务 | 在 `ctx.effect` 下派生 | ```rust -// SessionMetadataService (S5b; named service `sessionMetadata`) +// SessionMetadataService (S5b; named service `store`) async fn read(&self, session_id: &str) -> Result<SessionMetadata, MetadataError>; fn set_title(&self, session_id: &str, expected_revision: u64, title: Option<Title>) -> impl Future<Output = Result<u64, MetadataError>>; // Conflict | NotFound | Storage; the call is the handover From 77471929e1a1646ae5feedd4880de3b7f0c72eba Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 17:50:56 +0800 Subject: [PATCH 16/19] docs(storage): answer the second pre-review removeWorktree accepts a directory without a record, so discard can settle a created worktree; the reply says whether a record was deleted. The write operations no longer take a cancellation token, and setTitle commits once its change runs. The timelineStore flows and the worktree read flows are stated. query keeps the full read scope, session_owners has one writer, the delivery maps every code and rename, and the zh mirrors point at the contracts. Refs #2018 Refs #2015 --- docs/design/appserver/session-notices.md | 2 +- .../appserver/session-title-metadata.md | 4 +- docs/design/overview.md | 2 +- docs/design/plugins/ManagedWorktrees.md | 12 +-- docs/design/plugins/SessionStore.md | 48 +++++---- docs/design/plugins/SessionTitle.md | 2 +- docs/zh/design/appserver/session-files.md | 2 +- .../appserver/session-title-metadata.md | 102 ++---------------- docs/zh/design/plugins/SessionTitle.md | 13 ++- 9 files changed, 53 insertions(+), 134 deletions(-) diff --git a/docs/design/appserver/session-notices.md b/docs/design/appserver/session-notices.md index 456c1a7d61..5b9a66e024 100644 --- a/docs/design/appserver/session-notices.md +++ b/docs/design/appserver/session-notices.md @@ -92,7 +92,7 @@ pub fn notify(ctx: &Ctx, session_id: &str, notice: SessionNotice); SessionStore's `setTitle` (S5b), for example, commits the new revision and then calls `notify(&ctx, session_id, SessionNotice { source: "SessionStore".into(), kind: "title".into(), data })` inside its serialization of title writes, where `data` is `{title, titleSource, titleRevision}` -([S5b §5, §7](session-title-metadata.md#7-the-title-notice)). +([SessionStore](../plugins/SessionStore.md#operations) and [S5b §7](session-title-metadata.md#7-the-title-notice)). ## 5. Rpc forwarding diff --git a/docs/design/appserver/session-title-metadata.md b/docs/design/appserver/session-title-metadata.md index 458ffd92ea..0588de21c3 100644 --- a/docs/design/appserver/session-title-metadata.md +++ b/docs/design/appserver/session-title-metadata.md @@ -13,18 +13,18 @@ fields. Consumer: SessionTitle. ## 1. Summary +The Write and Binding bullets are superseded by [the SessionStore contract](../plugins/SessionStore.md#operations); the Data, Notice, Lists, Lifecycle and Format bullets remain in force. + SessionStore keeps one title per Session with a per-Session revision. The title changes only through `setTitle`, whose change decides the next title under the owner's serialization. After each committed change SessionStore announces the new title on the Session's broadcast channel ([C6](session-notices.md)), and Rpc shows the title in protocol v3 Session lists. - **Data.** A revision counter (0 means never written) and either no title or a title `{text, source}` with source `auto` or `manual`. Clearing keeps the counter, so a revision never repeats. -This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). - **Notice.** After each commit, `{source: "SessionStore", kind: "title", data: {title, titleSource, titleRevision}}`, in commit order. - **Lists.** Protocol v3 `session.summaries` entries carry `title`, `titleSource` and `titleRevision`. -This section is superseded by [the SessionStore contract](../plugins/SessionStore.md#operations). - **Lifecycle.** A delete removes the title in S5c's delete transaction; a fork does not copy it (SessionTitle A7); a restart keeps it. Reading or writing a title never loads the Session. - **Format.** Native store v16: one new table, upgraded in place from v15, and from v13 through v15's step. diff --git a/docs/design/overview.md b/docs/design/overview.md index 296573bfcb..a0ebb696ca 100644 --- a/docs/design/overview.md +++ b/docs/design/overview.md @@ -242,7 +242,7 @@ sequenceDiagram ST->>ST: interactive leader Session without a title only ST->>PR: complete(model, adopted text) PR-->>ST: title - ST->>SS: typed write: title, source auto, revision check + ST->>SS: setTitle(id, change) SS-->>BC: title notice for clients ``` diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md index fb75c4fdd7..645736da22 100644 --- a/docs/design/plugins/ManagedWorktrees.md +++ b/docs/design/plugins/ManagedWorktrees.md @@ -68,10 +68,10 @@ for candidate in confirmed(&preview) { | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `create` | Allocate a task id and make a Git worktree and branch for a Session creation | `{source, base?, branch?}` | `{taskId, repository, root, subtree, branch, base}` | Between Git calls and before the branch is created; a cancelled creation removes its empty task directory | `worktree_unavailable`, `worktree_invalid`, `worktree_branch_exists`, `worktree_git_failed`, `worktree_interrupted` | -| `discard` | Settle a created worktree that the Session creation did not adopt | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `worktree_in_use`, `worktree_git_failed`, `worktree_interrupted`, `worktree_store_failed` | +| `discard` | Settle a created worktree that the Session creation did not adopt; the store's record may not exist yet | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `worktree_in_use`, `worktree_git_failed`, `worktree_interrupted`, `worktree_store_failed` | | `list` | Managed worktrees with Git state and Session use | `{}` | `{worktrees}` | While the views are built | `worktree_unavailable`, `worktree_interrupted`, `worktree_store_failed` | | `pruneSelection` | Candidates a prune would delete and the kept ones with reasons | `{olderThanMs?, keep?, force}` | `{candidates, kept}` | While the selection is built | `worktree_invalid`, `worktree_unavailable`, `worktree_interrupted`, `worktree_store_failed` | -| `remove` | Remove one managed worktree, or an unregistered directory, with its record; an unregistered removal keeps the branch and reports it | `{taskId, force}` | `{removed, keptBranch?}` | Before the Git removal; after it starts the removal completes or reports `worktree_git_failed` | `worktree_invalid`, `worktree_not_found`, `worktree_in_use`, `worktree_git_failed`, `worktree_interrupted`, `worktree_store_failed` | +| `remove` | Remove one managed worktree, or an unregistered directory, with its record; an unregistered removal keeps the branch, and `worktree.list` reports it | `{taskId, force}` | `{removed}` | Before the Git removal; after it starts the removal completes or reports `worktree_git_failed` | `worktree_invalid`, `worktree_not_found`, `worktree_in_use`, `worktree_git_failed`, `worktree_interrupted`, `worktree_store_failed` | `create` returns a value; `discard` and `remove` take the task id. No object crosses. The preparation table is the owner's generation state: a reload drops it, and `discard` for a task id the generation did not create answers `unknown_preparation`; the directory is then an unregistered directory that `remove` handles. @@ -98,20 +98,20 @@ The wire codes are the published `worktree_*` codes (`crates/dim-app-server/src/ | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `create` | Resolve the source and the Git roots, resolve the base, allocate a task id, `git worktree add -b`, canonicalize the root, check the subtree, return the value; the caller adopts it with `store.create` | Each Git call ends `interrupted`; an empty task directory this call made is removed; a created worktree is rolled back by the owner | The call ends `interrupted`; the rollback path runs | New calls are refused; an in-flight creation is rolled back or left as an unregistered directory | Git and the directory by ManagedWorktrees; the record by the store | -| `discard` | Look up the preparation, `store.removeWorktree(directory, remove)`, delete the branch; the record may be absent | No cancellation; the cleanup is the owner's | The preparation ends with the row; the directory is unregistered | The table drops with the generation; the directory stays unregistered | Directory and branch by ManagedWorktrees; record by the store | +| `discard` | Look up the preparation, `store.removeWorktree(directory, remove)` (the record may be absent; the step still runs), delete the branch | No cancellation; the cleanup is the owner's | The preparation ends with the row; the directory is unregistered | The table drops with the generation; the directory stays unregistered | Directory and branch by ManagedWorktrees; record by the store | | `list` | Read the records and associations, join Git state per directory, add unregistered directories | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | | `pruneSelection` | `list`, then apply age, keep and force rules per candidate | Before the reply | Nothing to release | Pending calls end `closed` | ManagedWorktrees | -| `remove` | Resolve the record or the unregistered directory; a recorded one goes through `store.removeWorktree(directory, remove)`, an unregistered one through `store.removeUnregisteredDirectory(root, remove)`: the store checks and holds the exclusion, this owner removes the Git worktree or the directory, the store deletes or keeps the record; a branch is never deleted on an unregistered removal and its name is answered in `keptBranch` | Before the Git removal; a started removal completes or reports `worktree_git_failed`; the store keeps the record | The callback ends with the row; the store keeps the record | An in-flight removal ends; the store keeps the record unless the Git step succeeded | Directory by ManagedWorktrees; record by the store | +| `remove` | Resolve the record or the unregistered directory; a recorded one goes through `store.removeWorktree(directory, remove)`, an unregistered one through `store.removeUnregisteredDirectory(root, remove)`: the store checks and holds the exclusion, this owner removes the Git worktree or the directory, the store deletes or keeps the record; a branch is never deleted on an unregistered removal and `worktree.list` reports the branch | Before the Git removal; a started removal completes or reports `worktree_git_failed`; the store keeps the record | The callback ends with the row; the store keeps the record | An in-flight removal ends; the store keeps the record unless the Git step succeeded | Directory by ManagedWorktrees; record by the store | A process death between `create` and `store.create` leaves an unregistered directory; `list` reports it and `remove` deletes it after the operator names the task id. A process death during the removal step leaves the record; the next `list` reports the directory as missing or no longer registered, and `remove` cleans the record. ## Exceptions with reasons -- A branch is kept when `remove` deletes an adopted worktree: committed content must not disappear with the directory. Only the default `dim/<taskId>` branch of a never-adopted worktree is deleted with the directory. +- A branch is kept when `remove` deletes a worktree: committed content must not disappear with the directory, and `worktree.list` reports it. - `discard` is not cancellable: a cancelled Session creation still has to settle what the owner made. A store refusal (`closed` or `storage`) leaves the directory and branch in place; the caller reports it. The preparation is dropped with the generation, so the directory is unregistered and `remove` by task id is the retry path on the replacement generation. - Unregistered directories are never pruned: the owner has no record to age, so only an explicit `remove` by task id deletes them. - The preparation table exists because a created worktree has no record until the Session adopts it: the task id is the only handle a caller keeps after its own state is lost or reloaded, so `discard` settles by id instead of by a value the caller may no longer hold. -- A branch outlives a creation that was never adopted: a process death between `create` and `store.create` leaves the branch. `remove` on an unregistered directory never deletes a branch; it answers the branch the directory was on in `keptBranch`, and the operator deletes it with Git. The preparation table is gone by then, so the owner cannot tell a default `dim/<taskId>` branch from one the operator named; never deleting is the only decidable rule. +- A branch outlives a creation that was never adopted: a process death between `create` and `store.create` leaves the branch. `remove` on an unregistered directory never deletes a branch; `worktree.list` reports it, and the operator deletes it with Git. The preparation table is gone by then, so the owner cannot tell a default `dim/<taskId>` branch from one the operator named; never deleting is the only decidable rule. - Git is the owner's process resource: the owner starts each call, bounds it (10s read, 30s write) and reaps it on cancellation. ## Client-visible changes diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 74e21c9a9e..099859befd 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -8,7 +8,7 @@ SessionStore owns the stored Session: its rows, its grants, its reply language, SessionStore owns: -- **The Session row set.** `agent_sessions`, `session_owners`, the main branch record, the catalog row and the Timeline rows that make a stored Session. Creation writes them in one transaction; deletion removes them in the owner's order. +- **The Session row set.** `agent_sessions`, `session_owners`, the main branch record, the catalog row and the Timeline rows that make a stored Session. Creation writes them in one transaction; deletion removes them in the owner's order. SessionStore writes `session_owners` inside its own create/delete transactions; Agents only reads it through `create`, `owner` and `hasRecords`, and its contract states the same split. - **Session grants.** The stored path, kind and mode set, with the rule that a read grant never downgrades a write grant. - **The stored reply language.** One member of the stored configuration record. - **Title revisions.** The revision counter and the stored title value, one writer at a time, announced after commit. @@ -56,9 +56,10 @@ Agents creates a Session; admission, protocol checks and the worktree creation h ```rust // `prepared` is the value ManagedWorktrees.create returned. -store.create(CreateSession { - id, config, agent_id, protocol_version, leader: None, origin, worktree: prepared, -}, cancelled).await?; +store.create(ctx, CreateSession { + id, config, agent_id, protocol_version, leader: None, origin, + worktree: Some(Worktree { repository: prepared.repository, root: prepared.root, subtree: prepared.subtree }), +}).await?; ``` Agents forks and deletes; both mistakes are the caller's to fix, and a concurrent deletion is not an error the caller retries. @@ -69,8 +70,8 @@ let text: TextFn = Arc::new(move |source: String| { let next = strip_initial_title(&source); // lifecycle owner's decision Box::pin(async move { Ok(next) }) }); -store.fork(ForkSession { source, id: fork, at }, text, cancelled).await?; -let removed = store.delete(DeleteSession { id }, cancelled).await?; +store.fork(ctx, ForkSession { source, id: fork, at }, text).await?; +let removed = store.delete(ctx, DeleteSession { id }).await?; ``` SessionTitle decides the next title from the current one; the owner serializes the decision and announces the committed revision. @@ -80,7 +81,7 @@ let change: ChangeFn = Arc::new(move |current: TitleState| { let next = decide(current.revision, current.title.as_ref(), &text); // business rules Box::pin(async move { Ok(next) }) }); -let next = store.setTitle(SetTitle { id }, change).await?; +let next = store.setTitle(ctx, SetTitle { id }, change).await?; ``` ManagedWorktrees removes a directory: the owner holds the exclusion while the caller's Git step removes the root, and deletes or keeps the record by that step's result. @@ -113,8 +114,8 @@ Every operation takes one request object and answers one reply object. Writes ar | `owner` | The Agent that owns a stored Session | `{id}` | `{agentId?}` | None | `closed`, `storage` | | `hasRecords` | Whether an id has any stored row | `{id}` | `{exists}` | None | `closed`, `storage` | | `sessionConfig` | A stored Session's decoded configuration | `{id}` | `{config?}` | None | `not_found`, `closed`, `storage` | -| `catalog` | One stored Session page | `{request, agent?, version, hosts, closed}` | the stored page | While the page is read | `invalid`, `cancelled`, `closed`, `storage` | -| `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not) | `{scope, query, page?}`; `scope` is `{key:{sessionId,branchId}, through, segments}` | `{result, next}` | While the page is read | `invalid`, `storage`, `cancelled`, `closed` | +| `catalog` | One stored Session page | `{request, agent?, version, hosts, closed}` | the stored page defined by the `sessions` service ([sessions service](../appserver/sessions-service.md)) | While the page is read | `invalid`, `cancelled`, `closed`, `storage` | +| `query` | One consistent history read of a Session's stored rows, for a caller outside the Session (loaded or not); `next` is the opaque cursor of the same read binding | `{scope, query, page?}`; `scope` is `{key:{sessionId,branchId}, through, segments:[{branchId, from, through, storedThrough, tail}]}`; `tail` is the producer's list of stored segment tails | `{result, next}` | While the page is read | `invalid`, `storage`, `cancelled`, `closed` | | `grants` | The Session's grant set | `{id}` | `{grants}` | None | `closed`, `storage` | | `addGrant` | Add one grant, never downgrading a write grant | `{id, path, kind, mode}` | `{}` | None | `not_found`, `invalid`, `closed`, `storage` | | `removeGrant` | Remove one grant; an absent grant counts as removed | `{id, path}` | `{}` | None | `closed`, `storage` | @@ -125,7 +126,7 @@ Every operation takes one request object and answers one reply object. Writes ar | `worktrees` | Recorded directories, with their last use when known | `{}` | `{directories}` | None | `closed`, `storage` | | `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `closed`, `storage` | | `sessionsUnder` | Stored Sessions whose workspace is a root or lies under it | `{root}` | `{sessionIds}` | None | `invalid`, `closed`, `storage` | -| `removeWorktree` | Remove one recorded directory under the Session exclusion, with the caller's own removal step | `{repository, root}` + `remove` | `{removed}` | The caller's step ends; the record stays | `invalid`, `not_found`, `in_use`, `rejected`, `closed`, `storage` | +| `removeWorktree` | Remove a directory under the Session exclusion, with the caller's own removal step; the directory record may be absent | `{repository, root}` + `remove` | `{removed}`; true when a record was deleted | The caller's step ends; the record, if any, stays | `invalid`, `not_found`, `in_use`, `rejected`, `closed`, `storage` | | `removeUnregisteredDirectory` | Remove a directory no record names, under the Session exclusion, with the caller's own removal step | `{root}` + `remove` | `{removed}` | The caller's step runs to its end; no record is involved | `invalid`, `not_found`, `in_use`, `rejected`, `closed`, `storage` | `worktree` in `create` and `associateWorktree` is `{repository, root, subtree}`: absolute UTF-8 paths, `subtree` inside `root`, and no `.` or `..` component. The caller passes paths it already resolved; the owner re-checks that each is absolute, UTF-8, has no relative component and, for an association, that the root still is a directory. @@ -158,13 +159,23 @@ Flows: - The owner registers a listener with the calling row before returning; the row's unload withdraws it. - `commits` and `closeCommits` on a closing generation answer `closed`; a pending read ends `closed`. +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `head`, `branches`, `trace`, `batchEnd`, `batchEndAt`, `latestSnapshot` | One read per call; no lock | Before the reply | Nothing to release | Pending reads end `closed`; a new call is refused `closed` | SessionStore | +| `readPage`, `readSegments` | Read the committed rows in request order | Before the reply; nothing changes | The read stops | Pending reads end `closed` | SessionStore | +| `saveSnapshot` | Write one snapshot row; the write is not cancelled once it starts | None; the caller may drop the reply | The write completes | Admitted writes end before close | SessionStore | +| `commits` | Register the listener with the calling row and answer the subscription id | The caller's unload withdraws it | The listener is withdrawn | A new call answers `closed`; registered listeners receive no further notifications | SessionStore | +| `closeCommits` | Withdraw the listener; idempotent | None | The listener is withdrawn | A new call answers `closed` | SessionStore | + +After the store releases a Session, a face call answers `not_found`; after the generation closes, it answers `closed`. A failed batch refuses later admissions with `storage` but does not fail the reads. + ### Errors | Kind | What the caller does next | | --- | --- | | `invalid` | Fix the request: an id that is not one path component, a relative or non-UTF-8 path or a `.`/`..` component, a subtree outside the root, an unknown language code, an invalid catalog cursor. A `removeUnregisteredDirectory` root that lies under a registered directory answers `invalid`; call `removeWorktree` for it | | `workspace_missing` | The creation's `cwd` no longer is a directory; the caller reports the failed creation and discards the worktree | -| `not_found` | No stored Session has the id, a fork source has no rows, or a removal has no matching record or directory; the caller decides whether that is a business error or an answer. A second removal answers `not_found` and does not call the removal step | +| `not_found` | No stored Session has the id, a fork source has no rows, or the directory a removal names is absent; the caller decides whether that is a business error or an answer. A removal whose record is absent but whose directory exists still runs the removal step and answers `{removed:false}`; only an absent directory answers `not_found` | | `in_use` | A Session association or a stored workspace still names the directory; delete that Session or refuse the removal | | `rejected` | The caller's change, text or removal step refused with its own `code` and `message`; nothing was written and the caller acts on that code. `create` with an id that already has rows answers reason `exists`; the caller reads the id instead of retrying | | `cancelled` | The caller stopped the read; nothing changed | @@ -178,12 +189,13 @@ When a change, text or removal callback refuses, the operation answers `rejected | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `create` | Validate the id, take the exclusion, validate the workspace, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller keeps the id it supplied and decides whether to publish or delete the Session | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | -| `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove visible and Timeline rows, call `sessionFiles.releaseSession` | Before the handover: every row stays. After: the owner task runs to its end; dropping the caller's future does not stop it | The owner task continues; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | -| `fork` | Take the exclusion, read the source body, call `text`, copy in bounded transactions, write the target body and target rows in the last batch transaction, commit | Before the handover; a refused text step copies nothing | The owner task continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | +| `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove the visible and Timeline rows and clear the leader link on member Sessions, then call `sessionFiles.releaseSession`, which deletes the file-ownership rows and schedules the bytes sweep | Dropping the caller before the handover: every row stays. After: the owner task runs to its end | The owner task continues; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | +| `fork` | Take the exclusion, read the source body, call `text`, copy in bounded transactions, write the target body and target rows in the last batch transaction, commit | Dropping the caller before the handover; a refused text step copies nothing | The owner task continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | | `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | +| `worktrees`, `worktreeUsages`, `sessionsUnder` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed`; a new call is refused `closed` | SessionStore | | `catalog`, `query` | One consistent read under the caller's token | The read stops; no partial page | Nothing to release | Pending reads end `cancelled`; a new call ends `closed` | SessionStore | | `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | -| `setTitle` | Admit the write behind earlier admitted writes, read the current title, call `change` under the serialization, write the returned title as revision + 1, commit, announce, answer the revision | Dropping the reply never cancels the admitted write; a change that refuses leaves the title unchanged | The change callback is revoked before it returns; the admitted write fails and the title stays | Close stops admission, waits for every admitted write | SessionStore; the change computes only | +| `setTitle` | Admit the write behind earlier admitted writes, read the current title, call `change` under the serialization, write the returned title as revision + 1, commit, announce, answer the revision | Dropping the reply never cancels the admitted write; a change that refuses leaves the title unchanged | Once the change is called the write commits even if the calling row unloads; a change not yet started is revoked and the write ends `closed` with the title unchanged | Close stops admission, waits for every admitted write | SessionStore; the change computes only | | `removeWorktree` | Validate the paths, take the exclusion, check associations and stored workspaces, call `remove`, delete the record on success, release | The removal step refuses with its own code (for example `cancelled`); the record stays | The callback ends; the record stays; the exclusion releases | New calls are refused `closed`; an in-flight removal ends, and the record stays unless the step succeeded | Directory by the caller; record by SessionStore | | `removeUnregisteredDirectory` | Validate the root, take the exclusion, check stored workspaces under it, run the removal step as the owner's task, release | The removal step refuses with its own code; nothing changes | The owner task continues to the end and the exclusion is not released to the caller | New calls are refused `closed`; the running removal finishes and keeps the lock until it ends | Directory by the caller; exclusion by SessionStore | @@ -192,7 +204,7 @@ When a change, text or removal callback refuses, the operation answers `rejected - `create` takes the caller's already-validated configuration; `fork` reads the source text itself and calls the caller's text step under the fork's exclusion, so the lifecycle owner's `initialTitle` decision cannot race the copy and the copied bytes stay the source's text. - `delete` does not close the Session, remove its Agent admission slot or remove the worktree: closing is Agents', and a managed worktree is removed by ManagedWorktrees under `removeWorktree`. - `setTitle` runs the caller's change under the owner's serialization: the change only computes the next title from the current title and revision, and returns its own refusal; the reply may be lost, so the caller re-reads rather than assumes failure. -- `removeWorktree` runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. The exclusion has no time bound: a recursive forced deletion of an unregistered directory may run to its end, and `removeUnregisteredDirectory` uses the same exclusion for a directory no record names. +- `removeWorktree` serves both a recorded directory and a directory a failed creation left without a record (ManagedWorktrees' `discard`); the record is deleted only when it exists, and the reply says whether one was deleted. It runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. The exclusion has no time bound: a recursive forced deletion of an unregistered directory may run to its end, and `removeUnregisteredDirectory` uses the same exclusion for a directory no record names. - `owner` answers the Agent id for a delete notice; the Agent directory's own records are not returned here. - `associateWorktree` dedupes the directory record by `(repository, root)`: a repeated association for the same Session and directory replaces the subtree and updates its last use, and a new directory inserts one record. A retry after a lost reply therefore leaves one record and the caller's latest subtree. - `setTitle`'s change runs inside the owner's serialization and must not call `store` operations that take the same lock; it computes the next title only. @@ -264,7 +276,7 @@ Material uncertainty: a process death during the caller's removal step leaves th 2. **SessionScope (#2025): `timelineStore` ownership aligned.** This owner owns the Timeline operations and the `timelineStore` face; SessionScope binds that face at the Session instance. The face does not carry `createSession`, `releaseSession`, `rollbackSession` or `append`; those belong to the store's own creation and commit paths. The process `store.query` and `store.sessionConfig` are the same engine's reads for callers outside a Session (loaded or not) and keep one implementation. A comment on #2025 records the alignment. -The delivery part maps the current codes to these kinds: `creationRecord`, `title` and `associateWorktree` move from `closed` to `not_found`; a worktree removal conflict moves from `invalid` to `in_use`; a missing `cwd` moves from `invalid` to `workspace_missing`; `delete` answers `hadRows` instead of `removed`. +The delivery part maps the current codes to these kinds: `creationRecord`, `title` and `associateWorktree` move from `closed` to `not_found`; `addGrant` on a missing Session moves from `storage` to `not_found`; `setLanguage` moves from `closed` to `not_found`; `setTitle` during close moves from `storage` to `closed`; a worktree removal conflict moves from `invalid` to `in_use`; a missing `cwd` moves from `invalid` to `workspace_missing`; `delete` answers `hadRows` instead of `removed`. Field and operation renames: `sessionId`→`id`, `leaderSessionId`→`leader`, `createOwnedSession`→`create`, `worktreeDirectories`→`worktrees`, `sessionsUnderWorkspace`→`sessionsUnder`, `setSessionLanguage`→`setLanguage`. ## Binding appendix @@ -477,7 +489,6 @@ impl SessionStore { &self, caller: &Ctx, request: CreateSession, - cancelled: CancelledFn, ) -> Result<(), StoreError> { // ... } @@ -486,7 +497,6 @@ impl SessionStore { &self, caller: &Ctx, request: DeleteSession, - cancelled: CancelledFn, ) -> Result<DeleteSessionReply, StoreError> { // ... } @@ -496,7 +506,6 @@ impl SessionStore { caller: &Ctx, request: ForkSession, text: TextFn, - cancelled: CancelledFn, ) -> Result<(), StoreError> { // ... } @@ -507,7 +516,6 @@ impl SessionStore { caller: &Ctx, request: Directory, remove: RemoveFn, - cancelled: CancelledFn, ) -> Result<Removed, StoreError> { // ... } diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index 7cef4071e3..ebc1af84b0 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -88,7 +88,7 @@ The sequence diagrams show the change callback: `setTitle(id, change)`; the owne Cancellation before setTitle handover stops work without writing. The handover is the setTitle call itself: from then on SessionStore settles its own atomic operation, and a lost reply does not authorize -repeating or undoing it ([S5b §6](../appserver/session-title-metadata.md#6-handover-cancellation-and-settlement)). No rollback or +repeating or undoing it ([SessionStore](SessionStore.md#operations)). No rollback or coordination mechanism. Generation takes no Session activity hold ([idle unload D10](../appserver/idle-unload.md#3-decisions)); idle unload follows the same cancellation and store-handover rules. diff --git a/docs/zh/design/appserver/session-files.md b/docs/zh/design/appserver/session-files.md index 3cb5ce3802..3557c862c3 100644 --- a/docs/zh/design/appserver/session-files.md +++ b/docs/zh/design/appserver/session-files.md @@ -281,7 +281,7 @@ CREATE INDEX session_file_owners_by_file ON session_file_owners(file_id) **S5c 不需要为 Session 文件再改格式。** 它的分叉步骤只插入 `session_file_owners` 行(§4),删除步骤只删除这些行(§5.3),清扫读取 `session_files`;这些步骤读写的内容 v15 都已具备。v16 只可能来自 S5c 对它自己的 Session 记录的改动,不会来自 Session 文件。 -**宿主输出是 v29 的第二张表。** [ADR 013](../../adr/013-command-output-ownership.md) 为命令输出、转存的 `read` 结果和 shell 日志新增 `session_output_owners(session_id, path)` 及其索引。它不是 Session 文件表:这些路径没有 `session_files` 行或 id,目录由最后一个拥有它的 Session 删除时移除。分叉像复制 `session_file_owners` 一样复制它的行,因此源 Session 删除后输出仍可读。 +**宿主输出是 v29 的第二张表。** [ADR 013](../../../adr/013-command-output-ownership.md) 为命令输出、转存的 `read` 结果和 shell 日志新增 `session_output_owners(session_id, path)` 及其索引。它不是 Session 文件表:这些路径没有 `session_files` 行或 id,目录由最后一个拥有它的 Session 删除时移除。分叉像复制 `session_file_owners` 一样复制它的行,因此源 Session 删除后输出仍可读。 ## 9. 接口 diff --git a/docs/zh/design/appserver/session-title-metadata.md b/docs/zh/design/appserver/session-title-metadata.md index b3378ad473..2f3fcac851 100644 --- a/docs/zh/design/appserver/session-title-metadata.md +++ b/docs/zh/design/appserver/session-title-metadata.md @@ -1,6 +1,6 @@ # SessionStore 标题元数据 -目标绑定为 `store.readMetadata` 和 `store.setTitle`。SessionTitle 与重命名调用方一起切换到 `store`,随后移除 `sessionMetadata`。下文的旧绑定名描述迁移前的实现。 +「写入与绑定两节由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代;数据、通知、列表、生命周期与格式仍有效。」 状态:已在路线图 S5b 实现([#60](https://github.com/arcships/dim/issues/60),[#96](https://github.com/arcships/dim/pull/96)),在 C6([#49](https://github.com/arcships/dim/issues/49),[#85](https://github.com/arcships/dim/pull/85))之后;实现与本设计一致。评审细化了写入何时被接纳、卸载如何了结它(§6、D14)。需求:[SessionTitle](../plugins/SessionTitle.md) §2、§4 与 [A.2](../plugins/SessionTitle.md#a2-依赖的形状由所有者定义)。总览:[附录 B.2](../overview.md#b2-app-server-进程插件) 的 SessionStore 与 Rpc 行。范围:[ADR 002](../../adr/002-plugin-scope.md) 进程作用域,在既有 SessionStore 插件内,外加三个 Rpc 列表字段。使用方:SessionTitle。 @@ -61,71 +61,16 @@ SessionStore 为每个 Session 保存一个标题和一个按 Session 计数的 ## 4. 操作 ### 4.1 语言中立形式(ADR 002 D5) - -`sessionMetadata`,进程作用域,只在控制节点,没有实例键,由 SessionStore 提供。 - -| 方法 | 模式 | 请求 | 回复值 | 错误 | -| --- | --- | --- | --- | --- | -| `read` | async | `{sessionId}` | `{revision, title: {text, source} \| null}` | `not_found`、`storage` | -| `setTitle` | async | `{sessionId, expectedRevision, title: {text, source: "auto" \| "manual"} \| null}` | `{revision}`:提交后的修订号 | `conflict`、`not_found`、`storage` | - -- 回复使用同一个信封:`{ok: true, value}` 或 `{ok: false, error: {code, message}}`,与 `settings` 相同。 -- 两个方法都不装载 Session。`read` 读取已提交的状态,不等待标题写入者(§5)。 -- `setTitle` 必须带 `title`;`null` 表示清除。缺少 `title` 的请求被拒绝,而不是当作清除,这样调用方的遗漏不会抹掉用户的标题。 -- 格式错误的调用(未知方法、不是恰好一个请求对象、未知字段、类型错误或缺字段)是桥接错误,与 `settings` 相同:这是调用方的编程错误,不是写入的结果。 - -| 代码 | 何时 | 之后的状态 | -| --- | --- | --- | -| `not_found` | 存储里没有该 Session 的记录:从未创建、已删除或已回滚。已关闭或未装载但已存储的 Session 能找到 | 不变 | -| `conflict` | `expectedRevision` 不是当前修订号 | 不变,没有通知。重新读取 | -| `storage` | 事务失败,或调用在 SessionStore 开始关闭之后到达(§6) | 不变,没有通知 | +「本节由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代。」 ### 4.2 Rust - -Rust 使用方注入 `sessionMetadata` 的原生绑定 `SessionMetadataService`,调用 `read` 和 `set_title`。 -此绑定就是原 dispatcher,同一实例提供在类型键和 `host_key("sessionMetadata")` 上,两条路径直接调用 -同一个 SessionStore owner;既有回复类型 `SessionMetadata` 不变。 - -`set_title` 是返回 owner 等待 future 的普通函数。调用时就接纳写入,无需先轮询 future;丢弃 future -只丢弃回复。绑定不在接纳前增加异步包装,也不增加取消点、读取或第二个标题写入者。 +「本节由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代。」 ## 5. setTitle 时序 - -```text - 调用方 SessionStore SQLite Session 频道 - ------ ----------------------------------------------- ----------------- --------------- - setTitle(S, r, T) ----> SessionStore 正在关闭? -> 立即 storage,不写入 - 接纳:启动写入任务 <== 交接(调用本身) - | (任务归 SessionStore 所有;从这里起 - | 放弃调用只会丢掉回复) - | 等待轮到它使用标题写入者(一次一个写入) - +-- BEGIN IMMEDIATE ---------------------------> 读 S 的修订号 - | 没有 Session:not_found,回滚 - | 修订号 != r:conflict,回滚 - | 写入 r+1 与 T - +-- COMMIT ------------------------------------> 已提交,或 storage - | 仅在已提交时: - | notify(S, {SessionStore, title, - | {title, titleSource, titleRevision: r+1}}) -------------------> Notice - | 结束它的轮次 - <---- {revision: r+1} ----+ -``` - -`notify` 在提交之后、下一个写入轮到之前运行,所以同一 Session 的通知按提交顺序到达它的频道。它从不在 SQLite 连接锁内运行:监听方代码不在数据库锁内运行([timeline.rs](../../../../crates/dim-app-server/src/storage/timeline.rs) 的规则)。 +「本节由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代。」 ## 6. 交接、取消与了结 - -本节确定 SessionTitle §0 留给 S5b 的边界。 - -| 时点 | 规则 | -| --- | --- | -| 调用之前 | 调用方自己的工作。在调用前取消,不写入任何东西 | -| 调用 | 交接点是 SessionStore 收到调用:`setTitle` 在返回之前接纳写入,并把它作为 SessionStore 自己的任务启动;SessionStore 一旦开始关闭,则失败为 `storage`,不写入。Rust 的 `set_title` 是普通函数,做完这些后返回回复的 future。这个 future 只等待该任务,所以放弃它只会断开回复,不会断开写入。命名服务在 `invoke` 里调用它,所以 JavaScript 的调用在宿主收到时即完成交接 | -| 调用之后 | 写入由 SessionStore 自己了结:提交并宣布,或者失败且不写入。放弃调用、卸载调用方的行或丢失回复,都不会取消或撤销它。`setTitle` 没有取消动作 | -| 回复丢失 | 调用方用 `read` 读取。不要盲目重复写入:按旧修订号重复会得到 `conflict`,按新修订号重复则是第二次变更([SessionTitle 附录 C](../plugins/SessionTitle.md#附录-c-错误与恢复)) | -| SessionStore 卸载 | 它的清理先停止接纳:此后的调用立即失败为 `storage`,不写入。然后它等待每个已接纳的写入(正在执行的和仍在等待轮次的)提交并宣布或失败。之后它才关闭 Session 文件和 Timeline 写入线程;SqliteStorage 在 SessionStore 之后卸载,再关闭连接。这些通知按 C6 投递:Session 不再装载时无人监听,通知被丢弃。重载后不重试 | - -不采用:在事务开始前都有效的取消动作。它只是转移了不确定性,放弃调用的一方仍然要读取才能知道结果;而且 JavaScript 调用方在 rutis 里无法取消宿主调用([sessions §2](sessions-service.md#2-spike-结论) 第 5 条)。 +「本节由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代。」 ## 7. 标题通知 @@ -176,17 +121,7 @@ Rpc 从不调用 `setTitle`,也不新增方法。各错误到达客户端的 | SessionStore 或 SqliteStorage 重载 | 按 §6 了结。`sessionMetadata` 的使用方随 SessionStore 重载([ADR 002](../../adr/002-plugin-scope.md) D3),SessionTitle §1 已接受。SessionStore 只随没有依赖的 SqliteStorage 重载 | ## 10. 时序与冲突 - -| 场景 | 结果 | -| --- | --- | -| 两次写入带相同的预期修订号 | 先提交的胜出;另一次失败为 `conflict`,不宣布 | -| 写入不同 Session | 由唯一的标题写入者逐个执行;各自在自己的事务里提交 | -| `setTitle` 与 `session.delete` | 由存储的写事务排序:先提交的会被删除移除;先删除则写入得到 `not_found` | -| `setTitle` 与 `session.fork` | 互不影响:分叉不复制标题 | -| `setTitle` 与 Timeline 追加 | 不同的行;各自在同一存储连接上使用自己的事务 | -| 同一连接上的通知与列表读取 | §8:`titleRevision` 较高者胜出 | -| 没有附加客户端时 `setTitle` | 已提交;通知被丢弃;下一次列表显示标题 | -| 再次写入相同文本 | 提交新修订号并宣布([SessionTitle 附录 B](../plugins/SessionTitle.md#附录-b-完整冲突表):重复重命名会重写) | +「本节由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代。」 ## 11. 存储格式 @@ -309,28 +244,5 @@ CREATE TABLE session_metadata (session_id TEXT NOT NULL PRIMARY KEY REFERENCES a | D14 | 在调用时接纳;卸载先停止接纳,再等待每个已接纳的写入 | 写入轮到时才接纳,卸载时让仍在等待的写入失败(最初的实现) | 那样已交接的写入没有确定的接纳点:它能否执行,取决于它的任务和清理谁先到达标题写入者;卸载期间到达的调用,在当前写入结束前既不被拒绝也不被接纳。调用时接纳让交接和拒绝都立即确定。标题写得很少,等待已接纳的写入很短。Session 文件的写入也这样接纳 | ## 附录 A. Rust 绑定 +「本节由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代。」 -在 `dim_app_server::storage` 中: - -```rust -#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum TitleSource { Auto, Manual } -#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct Title { pub text: String, pub source: TitleSource } -#[derive(Clone, PartialEq, Eq, Serialize)] -pub struct SessionMetadata { pub revision: u64, pub title: Option<Title> } -/// v3 Session 列表条目的标题字段,也是标题通知的 data。 -#[derive(Clone, Default, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct TitleFields { pub title: Option<String>, pub title_source: Option<TitleSource>, pub title_revision: u64 } -pub enum MetadataError { Conflict, NotFound, Storage(String) } - -impl SessionMetadataService { - pub async fn read(&self, session_id: &str) -> Result<SessionMetadata, MetadataError>; - /// 被调用时就接纳并启动写入;SessionStore 正在关闭时失败为 `Storage`: - /// 调用即交接。放弃返回的 future 只丢掉回复。 - pub fn set_title(&self, session_id: &str, expected_revision: u64, title: Option<Title>) - -> impl Future<Output = Result<u64, MetadataError>> + Send + 'static; -} -``` diff --git a/docs/zh/design/plugins/SessionTitle.md b/docs/zh/design/plugins/SessionTitle.md index 142313ed7b..0413f9bc2d 100644 --- a/docs/zh/design/plugins/SessionTitle.md +++ b/docs/zh/design/plugins/SessionTitle.md @@ -28,7 +28,7 @@ App Server 测试不依赖 SessionTitle,仅覆盖通用宿主行为。验证 | 边界 | 当前合同与 Ready 决策 | | --- | --- | -| 观察 | 从 `sessionIdentity` 读取 Session id,从 `sessionConfig` 读取创建配置,从 `sessionLifecycle` 读取 closing([插件契约](../plugin-contract.md#9-向机制所有者提出的需求) R2),然后读取自身 Session 的 `session/{sessionId}` 通道记录。C4 广播 #180 已交付;#63/#168 已关闭。 | +| 观察 | 从 SessionScope 的 `identity` 读取 Session id,从 `config` 读取创建配置,从 `closing` 读取关闭状态([插件契约](../plugin-contract.md#9-向机制所有者提出的需求) R2),然后读取自身 Session 的 `session/{sessionId}` 通道记录。C4 广播 #180 已交付;#63/#168 已关闭。 | | 历史 | 使用已实现的进程 sessions.history,不读取私有 TimelineTree,也不使用分支(C5)绑定。 | | 配置 | 沿用具名 Settings 和原行来源声明,仅用户作用域(A.3/A12)。每次决定读取 settings.read({source:"session-title",scope:"user"}),直接使用已校验并补默认值的文档。 | | 元数据/通知 | 「本行由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代。」v3 列表字段为 `title`/`titleSource`/`titleRevision`;每次提交后 SessionStore 调用 `session_broadcast::notify`,Rpc 把记录以 `session.notice {sessionId, source, kind, data}` 转发给已附加的 v3 客户端(C6 #49/#85,[Session 广播通知](../appserver/session-notices.md))。 | @@ -50,8 +50,7 @@ atLeast 与 through,直接使用原生 HistoryPage/AgentEvent。S2 稳定目 `sessionMethods`,并在 `apply` 中把 `session.rename` 注册到它;它不提供服务。 插件仅依赖 Settings 与 `store` 的既有公开 Rust 绑定;历史回复在本插件的命名服务边界解析一次。插件行为与跨插件标题流程位于插件 crate 的 tests,使用公开客户端与宿主 API;App Server 测试不依赖该 crate,也不隐式安装标题插件。`apply` 读取 Session 标识和创建配置, 登记观察/清理,不启动异步初始化任务;创建配置不可变。同一部分注入必需依赖:进程服务 -`sessions`、`settings`、`store` 和 `auxiliaryModel`,以及 Session 服务 `sessionIdentity`、 -`sessionConfig`、`sessionLifecycle` 和 `sessionMethods`。可选的 `sessionTitleGenerator` +`sessions`、`settings`、`store` 和 `auxiliaryModel`,以及 SessionScope 的 `identity`、`config`、`activated`、`closing` 和 `sessionMethods`。可选的 `sessionTitleGenerator` 遵循[必需/可选绑定契约](../rutis-usage.md#3-按名字的服务),在使用时按名字读取,不注入,也不影响 Ready。 产品装配独立于外语插件行安装原生插件。 必需服务的提供者缺失时,依照既有依赖规则仅影响 SessionTitle 的可用性,不影响 Session 的执行能力。 @@ -96,7 +95,7 @@ flowchart LR | 部件 | 作用域 | 依赖 | 提供 | | --- | --- | --- | --- | | `session-title` | 进程 | Settings 和部件注册表 | 注册 Settings 来源及 Session 部分 | -| `SessionTitle` | Session | Session 服务 `sessionIdentity`、`sessionConfig`、`sessionLifecycle` 和 `sessionMethods`;进程 sessions 历史、Settings、标题元数据 `store`(S5b)和必需的 `auxiliaryModel`(提供者缺失使整行 Pending);按需读取可选的 `sessionTitleGenerator` | 把 session.rename 注册到 sessionMethods | +| `SessionTitle` | Session | SessionScope 的 `identity`、`config`、`activated`、`closing` 和 `sessionMethods`;进程 sessions 历史、Settings、标题元数据 `store`(S5b)和必需的 `auxiliaryModel`(提供者缺失使整行 Pending);按需读取可选的 `sessionTitleGenerator` | 把 session.rename 注册到 sessionMethods | 依赖位于 Session 或外层进程。C4/S2/Settings 已提供观察、前缀读取和配置;S5b 提供标题元数据,C6 提供通知;该配置的模型选择所有者提供具名辅助模型操作。插件的行在其 apply 中登记来源。真实提供者重载会取消该行工作(ADR 002 D3),S2 索引重载不会。业务数据更新不重载插件(D4)。 @@ -336,7 +335,7 @@ Settings 来源 `session-title`,一个文档:`enabled: bool` 默认 `true` | 步骤 | 路径 | | --- | --- | -| 监听 | 该部分在每个 Session 的副本于 `apply` 中监听自身 Session 的 `session/{sessionId}`,筛选 main input/applied,登记自持任务后返回;`sessionLifecycle.closing()` 或副本清理结束自持工作 | +| 监听 | 该部分在每个 Session 的副本于 `activated()` 后监听自身 Session 的 `session/{sessionId}`,筛选 main input/applied,登记自持任务后返回;`sessionLifecycle.closing()` 或副本清理结束自持工作 | | 资格 | C4 创建快照:`interactive !== false && collaborationRole === "leader"`(用于生成);原生省略值表示 true。创建时请求的初始标题(`initialTitle`,§3.4)对交互与非交互 Session 都写入:它不需要模型,文本属于调用方 | | 触发 | 收到位于 `N` 的 `input/applied` 时:若不具资格、已禁用、有在途生成或失败次数 ≥ 3(A5)则跳过;否则启动一个归属插件生命周期的生成任务 | | 检查 | `store.title({id})`:change 从当前标题与 revision 决定;`rejected` 时丢弃 | @@ -441,8 +440,8 @@ A1–A12 是首版实现采用的策略。 ```rust // SessionMetadataService (S5b; named service `store`) async fn read(&self, session_id: &str) -> Result<SessionMetadata, MetadataError>; -fn set_title(&self, session_id: &str, expected_revision: u64, title: Option<Title>) - -> impl Future<Output = Result<u64, MetadataError>>; // Conflict | NotFound | Storage; the call is the handover +fn set_title(&self, id: &str, change: ChangeFn) + -> impl Future<Output = Result<u64, StoreError>>; // Rejected | NotFound | Closed | Storage; the call is the handover pub struct SessionMetadata { pub revision: u64, pub title: Option<Title> } pub struct Title { pub text: String, pub source: TitleSource } // Auto | Manual // AuxiliaryModel(该配置的模型选择所有者) From 8edbe8ae01bbc22e08ba812b3680d7b635b939dd Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 17:52:05 +0800 Subject: [PATCH 17/19] docs(storage): map the FileStorage and instance-identity rules SessionFiles maps FileStorage's unsynced and missing_parent on put, import and write, and remove's cancellation to cancelled. The Timeline face states that a sessionId differing from the instance identity is invalid. Service faces names the three owners of the timelineStore row. Refs #2018 Refs #2015 --- docs/design/plugins/SessionFiles.md | 16 +++++++++++----- docs/design/plugins/SessionStore.md | 2 +- docs/design/service-faces.md | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md index e1bf333517..cd8bbdcd6f 100644 --- a/docs/design/plugins/SessionFiles.md +++ b/docs/design/plugins/SessionFiles.md @@ -67,13 +67,13 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, content}`, `content` is base64 | `{fileId, path, bytes}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | -| `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, path, bytes}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | -| `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, content}`, `content` is base64 | `{fileId, path, bytes}` | Before the replacement; the old bytes stay | `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, content}`, `content` is base64 | `{fileId, path, bytes}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `unsynced`, `missing_parent`, `cancelled`, `closed`, `storage` | +| `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, path, bytes}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `unsynced`, `missing_parent`, `cancelled`, `closed`, `storage` | +| `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, content}`, `content` is base64 | `{fileId, path, bytes}` | Before the replacement; the old bytes stay | `too_large`, `not_found`, `node_unavailable`, `unsynced`, `missing_parent`, `cancelled`, `closed`, `storage` | | `read` | One page of a Session file, at most 64 KiB | `{sessionId, fileId, offset}` | `{data, eof}`, `data` is base64 and `eof` is true exactly when it is empty | While the page is read; nothing changes | `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `register` | Record a caller-owned output path for the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `closed`, `storage` | | `owns` | Whether a path or file id belongs to the Session | `{sessionId, path}` | `{owned}` | While the path is resolved | `node_unavailable`, `cancelled`, `closed`, `storage` | -| `remove` | Remove one Session file and its ownership row; an absent or foreign file answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal during close | `node_unavailable`, `closed`, `storage` | +| `remove` | Remove one Session file and its ownership row; an absent or foreign file answers success | `{sessionId, fileId}` | `{}` | None; the owner completes the removal during close | `node_unavailable`, `cancelled`, `closed`, `storage` | | `releaseSession` | Delete every ownership row of a deleted Session and schedule the sweep; a repeated call succeeds | `{sessionId}` | `{}` | None; the owner completes the release | `closed`, `storage` | | `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `closed`, `storage` | @@ -87,6 +87,8 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `too_large` | Treat the file as not storable; store a smaller representation or refuse the attachment | | `not_found` | The Session has no such file, the file belongs to another Session, or the Session no longer exists; the caller refuses the request | | `node_unavailable` | The Session's resource node cannot be reached; retry later or report the node as unavailable | +| `unsynced` | The bytes are in place but durability is unconfirmed; do not treat the write as failed or as committed. Read the file to confirm, then retry the same write; the replacement is idempotent | +| `missing_parent` | The target path's parent is missing; this is the caller's path error. Create the directory or fix the path, then retry | | `cancelled` | The reservation and any copy are left to the sweep; no ownership row was committed, and the caller stops | | `closed` | This generation is unloading; call the replacement generation | | `storage` | The store or the file system failed; the caller reports the failure and keeps its own copy | @@ -99,7 +101,7 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `import` | Open the source, check size, copy through FileStorage into a temporary file, commit ownership | The temporary file is removed; no owned row | The copy completes or is abandoned; the sweep removes what no row owns | As `put` | Source and temporary file by FileStorage; rows by SessionFiles | | `write` | Resolve the file id, write the new bytes through FileStorage under the same path, keep the row | Before the replacement: the old bytes stay | The write completes or is abandoned | As `put` | File and path by FileStorage; row by SessionFiles | | `read` | Resolve the file id, read one page at the offset; an offset at or past the end is an empty page | The page stops; nothing changes | The read stops | Pending reads end `closed` | FileStorage | -| `remove` | Resolve the file id; an absent or foreign id answers success; remove the directory entry through FileStorage, delete the row | None | The call ends | A new call is refused `closed`; an admitted removal finishes | File and row by SessionFiles | +| `remove` | Resolve the file id; an absent or foreign id answers success; remove the directory entry through FileStorage, delete the row | Before the unlink: nothing removed, `cancelled`; a tree can be partly removed and a retry is safe | The call ends | A new call is refused `closed`; an admitted removal finishes | File and row by SessionFiles | | `releaseSession` | Delete every ownership row of the Session, schedule the sweep; the bytes are deleted outside the transaction | None | The release continues under the owner's task | A new call is refused `closed`; an admitted release finishes | Rows by SessionFiles; bytes by the sweep | | `register` | Check the Session, record the path the caller resolved | None | The row stays; a later Session delete removes it | A new call is refused `closed`; rows stay for the next generation | SessionFiles | | `owns` | Resolve the path against the owner's directory, check the output row, else the file id row | The resolution stops | Nothing to release | Pending calls end `closed` | SessionFiles | @@ -192,6 +194,10 @@ pub enum SessionFileError { NotFound { message: String }, #[error("{message}")] NodeUnavailable { message: String }, + #[error("{message}")] + Unsynced { message: String }, + #[error("{message}")] + MissingParent { message: String }, #[error("the call was cancelled")] Cancelled, #[error("the file service is unloading")] diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 099859befd..60eaf3b06e 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -133,7 +133,7 @@ Every operation takes one request object and answers one reply object. Writes ar #### Timeline face -`timelineStore` is the same owner's Session-scoped Timeline face; SessionScope installs the binding at the Session instance (#2093). This contract owns the spellings. The face carries the line reads and the completion subscriptions; `createSession`, `releaseSession`, `rollbackSession` and `append` are the store's own creation and commit steps, and `sessionConfig`/`query` are the process `store` reads. +`timelineStore` is the same owner's Session-scoped Timeline face; SessionScope installs the binding at the Session instance (#2093). This contract owns the spellings. The instance identity is the Session: every request's `sessionId` must equal it, and a mismatch answers `invalid`; that rule is part of every row's `invalid` below. The face carries the line reads and the completion subscriptions; `createSession`, `releaseSession`, `rollbackSession` and `append` are the store's own creation and commit steps, and `sessionConfig`/`query` are the process `store` reads. | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 5c7a7f7a60..b8a70ead7f 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` | 本节由 [SqliteStorage 契约](plugins/SqliteStorage.md) 取代。 | 本节由 [SqliteStorage 契约](plugins/SqliteStorage.md) 取代。 | -| `timelineStore` | 本节由 [SessionStore 契约](plugins/SessionStore.md) 取代。 | 本节由 [SessionStore 契约](plugins/SessionStore.md) 取代。 | +| `timelineStore` | Session 面由 [#2093](https://github.com/arcships/dim/pull/2093) 定义;进程 `store` 由 [#2091](https://github.com/arcships/dim/pull/2091) 定义;Timeline 操作由 [#2092](https://github.com/arcships/dim/pull/2092) 定义。 | 同上。 | | `promptSourcesBranch` | 分支 prompt 装配 | 按 #1292 确认公共操作与装配内部职责。 | 这些行按当前对象形状分组。前四行的数据契约由 [resource and store data faces](resource-faces.md) 定义(#1295/#1297/#1298)。其余行按 #1292 逐批确定操作面。 From d2eb578ffc7db17893694155bed8481e55a5e1ea Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 19:13:28 +0800 Subject: [PATCH 18/19] docs(storage): answer the round-eight reviews SessionFiles settles new-file creation itself: put and import create their parents, resolve unsynced by committing the ownership row or deleting the bytes, and keep only the attachment-facing codes; only a replacement leaves unsynced to the caller. removeWorktree treats a missing root as success and unregisters the record under the same exclusion. The example drops the extra argument, ManagedWorktrees maps every store refusal, and the internal Timeline step is releaseTimeline. The sibling heads and the trailing blank line are fixed. Refs #2018 Refs #2015 --- docs/design/plugins/ManagedWorktrees.md | 14 +++++++++++++- docs/design/plugins/SessionFiles.md | 19 ++++++++++--------- docs/design/plugins/SessionStore.md | 12 ++++++------ docs/design/plugins/SessionTitle.md | 2 +- .../appserver/session-title-metadata.md | 1 - 5 files changed, 30 insertions(+), 18 deletions(-) diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md index 645736da22..63a4fb9920 100644 --- a/docs/design/plugins/ManagedWorktrees.md +++ b/docs/design/plugins/ManagedWorktrees.md @@ -68,7 +68,7 @@ for candidate in confirmed(&preview) { | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `create` | Allocate a task id and make a Git worktree and branch for a Session creation | `{source, base?, branch?}` | `{taskId, repository, root, subtree, branch, base}` | Between Git calls and before the branch is created; a cancelled creation removes its empty task directory | `worktree_unavailable`, `worktree_invalid`, `worktree_branch_exists`, `worktree_git_failed`, `worktree_interrupted` | -| `discard` | Settle a created worktree that the Session creation did not adopt; the store's record may not exist yet | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `worktree_in_use`, `worktree_git_failed`, `worktree_interrupted`, `worktree_store_failed` | +| `discard` | Settle a created worktree that the Session creation did not adopt; the store's record may not exist yet | `{taskId}` | `{}` | Not cancellable: the cleanup runs to its end | `unknown_preparation`, `worktree_invalid`, `worktree_in_use`, `worktree_git_failed`, `worktree_interrupted`, `worktree_store_failed` | | `list` | Managed worktrees with Git state and Session use | `{}` | `{worktrees}` | While the views are built | `worktree_unavailable`, `worktree_interrupted`, `worktree_store_failed` | | `pruneSelection` | Candidates a prune would delete and the kept ones with reasons | `{olderThanMs?, keep?, force}` | `{candidates, kept}` | While the selection is built | `worktree_invalid`, `worktree_unavailable`, `worktree_interrupted`, `worktree_store_failed` | | `remove` | Remove one managed worktree, or an unregistered directory, with its record; an unregistered removal keeps the branch, and `worktree.list` reports it | `{taskId, force}` | `{removed}` | Before the Git removal; after it starts the removal completes or reports `worktree_git_failed` | `worktree_invalid`, `worktree_not_found`, `worktree_in_use`, `worktree_git_failed`, `worktree_interrupted`, `worktree_store_failed` | @@ -77,6 +77,18 @@ for candidate in confirmed(&preview) { `remove` composes the store's removal under its exclusion: `removeWorktree` for a recorded directory and `removeUnregisteredDirectory` for a directory no record names. The store checks the associations and the stored workspaces and calls this owner's Git and filesystem removal as a callback; the record is deleted when the callback succeeds and kept when it refuses or fails. No claim id or lock crosses. `force` overrides only the content check; the Git removal receives `--force` only then. +The store's refusals map to this owner's codes, and each has the caller's next step: + +| Store answer | Owner code | Caller next step | +| --- | --- | --- | +| `invalid` | `worktree_invalid` | Fix the task id or root; if the root is under a registered directory, call `removeWorktree` | +| `not_found` (unregistered removal only) | `worktree_not_found` | The directory is already gone; nothing to retry | +| `in_use` | `worktree_in_use` | Delete the Session or stored workspace that uses the directory, then retry | +| `rejected` with reason `git` | `worktree_git_failed` | Report Git's message; the directory and record stay | +| `rejected` with reason `cancelled` | `worktree_interrupted` | Retry the removal on the same generation | +| `rejected` with reason `invalid` | `worktree_invalid` | Fix the directory state; the record stays | +| `closed` or `storage` | `worktree_store_failed` | Report the failure; the record stays and the call is retryable on the replacement generation | + ### Errors The wire codes are the published `worktree_*` codes (`crates/dim-app-server/src/worktrees.rs:85-108`); `unknown_preparation` is the only internal code. diff --git a/docs/design/plugins/SessionFiles.md b/docs/design/plugins/SessionFiles.md index cd8bbdcd6f..01b083a2c1 100644 --- a/docs/design/plugins/SessionFiles.md +++ b/docs/design/plugins/SessionFiles.md @@ -67,9 +67,9 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, content}`, `content` is base64 | `{fileId, path, bytes}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `unsynced`, `missing_parent`, `cancelled`, `closed`, `storage` | -| `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, path, bytes}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `unsynced`, `missing_parent`, `cancelled`, `closed`, `storage` | -| `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, content}`, `content` is base64 | `{fileId, path, bytes}` | Before the replacement; the old bytes stay | `too_large`, `not_found`, `node_unavailable`, `unsynced`, `missing_parent`, `cancelled`, `closed`, `storage` | +| `put` | Store bytes under a new file id and commit ownership | `{sessionId, name, content}`, `content` is base64 | `{fileId, path, bytes}` | While the bytes land; a cancelled put leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `import` | Copy a regular host file into the Session namespace and commit ownership | `{sessionId, name, source}` | `{fileId, path, bytes}` | Before the replacement; a cancelled import leaves no owned row | `invalid`, `too_large`, `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | +| `write` | Replace one Session file's bytes under the same id and path | `{sessionId, fileId, content}`, `content` is base64 | `{fileId, path, bytes}` | Before the replacement; the old bytes stay | `too_large`, `not_found`, `node_unavailable`, `unsynced`, `cancelled`, `closed`, `storage` | | `read` | One page of a Session file, at most 64 KiB | `{sessionId, fileId, offset}` | `{data, eof}`, `data` is base64 and `eof` is true exactly when it is empty | While the page is read; nothing changes | `not_found`, `node_unavailable`, `cancelled`, `closed`, `storage` | | `register` | Record a caller-owned output path for the Session | `{sessionId, path}` | `{}` | None | `invalid`, `not_found`, `closed`, `storage` | | `owns` | Whether a path or file id belongs to the Session | `{sessionId, path}` | `{owned}` | While the path is resolved | `node_unavailable`, `cancelled`, `closed`, `storage` | @@ -77,7 +77,9 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `releaseSession` | Delete every ownership row of a deleted Session and schedule the sweep; a repeated call succeeds | `{sessionId}` | `{}` | None; the owner completes the release | `closed`, `storage` | | `ownedPaths` | Every path the Session owns | `{sessionId}` | `{paths}` | None | `closed`, `storage` | -`path` is absolute on the Session's resource node; `bytes` is the stored length. `offset` at the file size answers an empty `data` with `eof`; an offset above the size is clamped to the size before the page read, because FileStorage refuses an offset above it with `invalid`. The rule is stated once in both documents: at `size` an empty page with `eof`, above `size` `invalid` at FileStorage; this owner clamps so its own callers keep the empty page their client contract states. A `fileId` outside the Session, or a name that is not one component, is `not_found` for reads and writes and `invalid` for a name `put` or `import` receives. +`path` is absolute on the Session's resource node; `bytes` is the stored length. `offset` at the file size answers an empty `data` with `eof`; an offset above the size is clamped to the size before the page read, because FileStorage refuses an offset above it with `invalid`. + +A new file is settled by this owner. `put` and `import` create their parent directories with the recursive `create_directory`; the caller never receives `missing_parent`, and the path it passes is used as given. If a new file's bytes land but durability is unconfirmed (`unsynced` from FileStorage), the owner synchronizes or retries the write; on success it commits the ownership row and returns the file id, and if it cannot settle the file it deletes the bytes and publishes no ownership row. The caller sees only the attachment face's existing codes: `attachment_invalid`, `attachment_too_large`, `node_unavailable` or `storage_failed` (`crates/dim-agent-attachments/src/lib.rs:65-73`). The rule is stated once in both documents: at `size` an empty page with `eof`, above `size` `invalid` at FileStorage; this owner clamps so its own callers keep the empty page their client contract states. A `fileId` outside the Session, or a name that is not one component, is `not_found` for reads and writes and `invalid` for a name `put` or `import` receives. ### Errors @@ -87,8 +89,7 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | `too_large` | Treat the file as not storable; store a smaller representation or refuse the attachment | | `not_found` | The Session has no such file, the file belongs to another Session, or the Session no longer exists; the caller refuses the request | | `node_unavailable` | The Session's resource node cannot be reached; retry later or report the node as unavailable | -| `unsynced` | The bytes are in place but durability is unconfirmed; do not treat the write as failed or as committed. Read the file to confirm, then retry the same write; the replacement is idempotent | -| `missing_parent` | The target path's parent is missing; this is the caller's path error. Create the directory or fix the path, then retry | +| `unsynced` | A replacement (`write`) whose bytes are in place but whose durability is unconfirmed; do not treat it as failed or as committed. Read the file to confirm, then retry the same write; a new file (`put`, `import`) never returns this: the owner settles it as described below | | `cancelled` | The reservation and any copy are left to the sweep; no ownership row was committed, and the caller stops | | `closed` | This generation is unloading; call the replacement generation | | `storage` | The store or the file system failed; the caller reports the failure and keeps its own copy | @@ -97,8 +98,8 @@ let stored = files.import(Import { session_id, name, source }, cancelled).await? | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | -| `put` | Reserve the file under the generation, write the bytes through FileStorage, commit the ownership row while the generation and the Session still exist | The reservation and the written bytes are abandoned; the sweep removes them; no owned row | The write completes under the owner's task, or the reservation expires with the generation; the sweep removes unowned bytes | Admission stops; admitted writes finish; a new generation sweeps the old one's pending rows | FileSystem by FileStorage; rows and sweep by SessionFiles | -| `import` | Open the source, check size, copy through FileStorage into a temporary file, commit ownership | The temporary file is removed; no owned row | The copy completes or is abandoned; the sweep removes what no row owns | As `put` | Source and temporary file by FileStorage; rows by SessionFiles | +| `put` | Create the parent, reserve the file under the generation, write the bytes through FileStorage; an `unsynced` new file is synchronized or retried, then either the ownership row commits and the id is returned, or the bytes are deleted with no ownership row | The reservation and the written bytes are abandoned; the sweep removes them; no owned row | The write completes under the owner's task, or the reservation expires with the generation; the sweep removes unowned bytes | Admission stops; admitted writes finish; a new generation sweeps the old one's pending rows | FileSystem by FileStorage; rows and sweep by SessionFiles | +| `import` | Open the source, check the size, create the parent, copy through FileStorage; an `unsynced` new file is settled by the owner as `put` describes, then the ownership row commits or the bytes are deleted | The temporary file is removed; no owned row | The copy completes or is abandoned; the sweep removes what no row owns | As `put` | Source and temporary file by FileStorage; rows by SessionFiles | | `write` | Resolve the file id, write the new bytes through FileStorage under the same path, keep the row | Before the replacement: the old bytes stay | The write completes or is abandoned | As `put` | File and path by FileStorage; row by SessionFiles | | `read` | Resolve the file id, read one page at the offset; an offset at or past the end is an empty page | The page stops; nothing changes | The read stops | Pending reads end `closed` | FileStorage | | `remove` | Resolve the file id; an absent or foreign id answers success; remove the directory entry through FileStorage, delete the row | Before the unlink: nothing removed, `cancelled`; a tree can be partly removed and a retry is safe | The call ends | A new call is refused `closed`; an admitted removal finishes | File and row by SessionFiles | @@ -169,7 +170,7 @@ Flow tests on the owner: ## Requirements raised to mechanism owners -1. **FileStorage (#2016): the operations this owner calls.** `root_path`, `read` with `{offset, length}` and `{data, eof, size}`, `write` with its `source` and `privateReadOnly`, `import` with `max_bytes` and `privateReadOnly`, `create_directory`, `list` and `remove` exist in [FileStorage's contract](https://github.com/arcships/dim/pull/2080) at head `2a312945c`. The owner reads the store directory's root with `root_path`; the host registers the native store directory as a root, and a comment on #2016 records the dependency. +1. **FileStorage (#2016): the operations this owner calls.** `root_path`, `read` with `{offset, length}` and `{data, eof, size}`, `write` with its `source` and `privateReadOnly`, `import` with `max_bytes` and `privateReadOnly`, `create_directory`, `list` and `remove` exist in [FileStorage's contract](https://github.com/arcships/dim/pull/2080) in PR #2080. The owner reads the store directory's root with `root_path`; the host registers the native store directory as a root, and a comment on #2016 records the dependency. 2. **Service type placement (#2015): a process owner in the app server.** The owner type is in `dim-app-server`, where the engine and the rows are; callers in plugin crates cannot depend on the app server. The request and reply types are plain data in `dim-agent-capabilities::host`, and callers outside the crate call the operations by the `sessionFiles` name. If the maintainers decide every process face must be annotated on a type plugin crates can name, the type moves to a shared crate; a comment on #2015 states the requirement. ## Binding appendix diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index 60eaf3b06e..aaef64d732 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -92,7 +92,7 @@ let remove: RemoveFn = Arc::new(move |root: String| { let cancelled = cancelled.clone(); Box::pin(async move { git_remove(&root, force, &cancelled).await }) }); -store.removeWorktree(Directory { repository, root }, remove, cancelled.clone()).await?; +store.removeWorktree(Directory { repository, root }, remove).await?; ``` ## Own contract @@ -126,14 +126,14 @@ Every operation takes one request object and answers one reply object. Writes ar | `worktrees` | Recorded directories, with their last use when known | `{}` | `{directories}` | None | `closed`, `storage` | | `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `closed`, `storage` | | `sessionsUnder` | Stored Sessions whose workspace is a root or lies under it | `{root}` | `{sessionIds}` | None | `invalid`, `closed`, `storage` | -| `removeWorktree` | Remove a directory under the Session exclusion, with the caller's own removal step; the directory record may be absent | `{repository, root}` + `remove` | `{removed}`; true when a record was deleted | The caller's step ends; the record, if any, stays | `invalid`, `not_found`, `in_use`, `rejected`, `closed`, `storage` | +| `removeWorktree` | Remove a directory under the Session exclusion, with the caller's own removal step; the record may be absent and an already-missing root is success | `{repository, root}` + `remove` | `{removed}`; true when a record was deleted | The caller's step ends; the record, if any, stays | `invalid`, `in_use`, `rejected`, `closed`, `storage` | | `removeUnregisteredDirectory` | Remove a directory no record names, under the Session exclusion, with the caller's own removal step | `{root}` + `remove` | `{removed}` | The caller's step runs to its end; no record is involved | `invalid`, `not_found`, `in_use`, `rejected`, `closed`, `storage` | `worktree` in `create` and `associateWorktree` is `{repository, root, subtree}`: absolute UTF-8 paths, `subtree` inside `root`, and no `.` or `..` component. The caller passes paths it already resolved; the owner re-checks that each is absolute, UTF-8, has no relative component and, for an association, that the root still is a directory. #### Timeline face -`timelineStore` is the same owner's Session-scoped Timeline face; SessionScope installs the binding at the Session instance (#2093). This contract owns the spellings. The instance identity is the Session: every request's `sessionId` must equal it, and a mismatch answers `invalid`; that rule is part of every row's `invalid` below. The face carries the line reads and the completion subscriptions; `createSession`, `releaseSession`, `rollbackSession` and `append` are the store's own creation and commit steps, and `sessionConfig`/`query` are the process `store` reads. +`timelineStore` is the same owner's Session-scoped Timeline face; SessionScope installs the binding at the Session instance (#2093). This contract owns the spellings. The instance identity is the Session: every request's `sessionId` must equal it, and a mismatch answers `invalid`; that rule is part of every row's `invalid` below. The face carries the line reads and the completion subscriptions; `createSession`, `releaseTimeline`, `rollbackSession` and `append` are the store's own creation and commit steps, and `sessionConfig`/`query` are the process `store` reads. | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | @@ -175,7 +175,7 @@ After the store releases a Session, a face call answers `not_found`; after the g | --- | --- | | `invalid` | Fix the request: an id that is not one path component, a relative or non-UTF-8 path or a `.`/`..` component, a subtree outside the root, an unknown language code, an invalid catalog cursor. A `removeUnregisteredDirectory` root that lies under a registered directory answers `invalid`; call `removeWorktree` for it | | `workspace_missing` | The creation's `cwd` no longer is a directory; the caller reports the failed creation and discards the worktree | -| `not_found` | No stored Session has the id, a fork source has no rows, or the directory a removal names is absent; the caller decides whether that is a business error or an answer. A removal whose record is absent but whose directory exists still runs the removal step and answers `{removed:false}`; only an absent directory answers `not_found` | +| `not_found` | No stored Session has the id or a fork source has no rows; the caller decides whether that is a business error or an answer. A worktree removal whose root is already gone is success: the step confirms the missing root and the record is deleted under the same exclusion, so a retry is safe (`crates/dim-app-server/src/storage/timeline.rs:1853-1890`) | | `in_use` | A Session association or a stored workspace still names the directory; delete that Session or refuse the removal | | `rejected` | The caller's change, text or removal step refused with its own `code` and `message`; nothing was written and the caller acts on that code. `create` with an id that already has rows answers reason `exists`; the caller reads the id instead of retrying | | `cancelled` | The caller stopped the read; nothing changed | @@ -189,7 +189,7 @@ When a change, text or removal callback refuses, the operation answers `rejected | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `create` | Validate the id, take the exclusion, validate the workspace, write the rows, the owner row, the main branch, the catalog row and the association, commit | Before the transaction: nothing written. During: the transaction completes or fails; the reply may be lost | The transaction still completes; the caller keeps the id it supplied and decides whether to publish or delete the Session | New calls are refused `closed`; admitted work ends before the writer closes | Rows by SessionStore; the workspace by the caller | -| `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove the visible and Timeline rows and clear the leader link on member Sessions, then call `sessionFiles.releaseSession`, which deletes the file-ownership rows and schedules the bytes sweep | Dropping the caller before the handover: every row stays. After: the owner task runs to its end | The owner task continues; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | +| `delete` | Take the exclusion, read whether rows exist, remove output, touch worktree use, remove the visible and Timeline rows and clear the leader link on member Sessions, then call `sessionFiles.releaseSession`, which deletes the file-ownership rows and schedules the bytes sweep; the store's own Timeline step is `releaseTimeline` | Dropping the caller before the handover: every row stays. After: the owner task runs to its end | The owner task continues; the reply may be lost | The admitted delete ends before close | Output and rows by SessionStore; files by SessionFiles | | `fork` | Take the exclusion, read the source body, call `text`, copy in bounded transactions, write the target body and target rows in the last batch transaction, commit | Dropping the caller before the handover; a refused text step copies nothing | The owner task continues; the reply may be lost | The admitted fork ends before close | Rows by SessionStore | | `title`, `creationRecord`, `owner`, `hasRecords`, `sessionConfig`, `grants` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed` | SessionStore | | `worktrees`, `worktreeUsages`, `sessionsUnder` | One read; no lock | Before the read | Nothing to release | Pending reads end `closed`; a new call is refused `closed` | SessionStore | @@ -273,7 +273,7 @@ Material uncertainty: a process death during the caller's removal step leaves th 1. **SessionTitle (#2033): the title write is a change callback.** `store.setTitle(id, change)` receives the current title, its source and revision, and returns the next title or its own refusal; the owner serializes the write and announces the commit. The revision-checked `{expectedRevision, title}` shape in SessionTitle.md and session-title-metadata.md is superseded; the manual-title rule moves into the change. A comment on #2033 states the requirement. -2. **SessionScope (#2025): `timelineStore` ownership aligned.** This owner owns the Timeline operations and the `timelineStore` face; SessionScope binds that face at the Session instance. The face does not carry `createSession`, `releaseSession`, `rollbackSession` or `append`; those belong to the store's own creation and commit paths. The process `store.query` and `store.sessionConfig` are the same engine's reads for callers outside a Session (loaded or not) and keep one implementation. A comment on #2025 records the alignment. +2. **SessionScope (#2025): `timelineStore` ownership aligned.** This owner owns the Timeline operations and the `timelineStore` face; SessionScope binds that face at the Session instance. The face does not carry `createSession`, `releaseTimeline`, `rollbackSession` or `append`; those belong to the store's own creation and commit paths. The process `store.query` and `store.sessionConfig` are the same engine's reads for callers outside a Session (loaded or not) and keep one implementation. A comment on #2025 records the alignment. The delivery part maps the current codes to these kinds: `creationRecord`, `title` and `associateWorktree` move from `closed` to `not_found`; `addGrant` on a missing Session moves from `storage` to `not_found`; `setLanguage` moves from `closed` to `not_found`; `setTitle` during close moves from `storage` to `closed`; a worktree removal conflict moves from `invalid` to `in_use`; a missing `cwd` moves from `invalid` to `workspace_missing`; `delete` answers `hadRows` instead of `removed`. Field and operation renames: `sessionId`→`id`, `leaderSessionId`→`leader`, `createOwnedSession`→`create`, `worktreeDirectories`→`worktrees`, `sessionsUnderWorkspace`→`sessionsUnder`, `setSessionLanguage`→`setLanguage`. diff --git a/docs/design/plugins/SessionTitle.md b/docs/design/plugins/SessionTitle.md index ebc1af84b0..844ab89787 100644 --- a/docs/design/plugins/SessionTitle.md +++ b/docs/design/plugins/SessionTitle.md @@ -36,7 +36,7 @@ only outcome and duration. | Boundary | Current contract and Ready decision | | --- | --- | -| Observation | Read the Session id, the creation configuration and closing from SessionScope's `identity`, `config` and `closing` ([#2093](https://github.com/arcships/dim/pull/2093), target, pending; [plugin contract](../plugin-contract.md#9-requirements-raised-to-mechanism-owners) R2), then the records on its Session's `session/{sessionId}` channel. C4 broadcast #180 is delivered; #63/#168 are closed. | +| Observation | Read the Session id, the creation configuration and closing from SessionScope's `identity`, `config` and `closing` ([#2093](https://github.com/arcships/dim/pull/2093), target, pending; [plugin contract](../plugin-contract.md#9-requirements-raised-to-mechanism-owners) R2); the copy starts observing on `activated`, when the Session is published, then reads the records on its Session's `session/{sessionId}` channel. C4 broadcast #180 is delivered; #63/#168 are closed. | | Timeline reads | Use the Session’s branch query facade on `main`, with a fixed published cutoff. Read only the adopted input identity, its user content or Goal objective, and the adopted model fields (§0.1). | | Configuration | Existing named Settings and row source declaration, user scope only (A.3/A12). Read settings.read({source:"session-title",scope:"user"}) at each decision and use its validated/defaulted document directly. | | Metadata/notice | This row is superseded by [the SessionStore contract](SessionStore.md#operations); the v3 list fields are `title`/`titleSource`/`titleRevision`, and Rpc forwards the notice as `session.notice {sessionId, source, kind, data}` (C6 #49/#85, [Session broadcast notices](../appserver/session-notices.md)). | diff --git a/docs/zh/design/appserver/session-title-metadata.md b/docs/zh/design/appserver/session-title-metadata.md index 2f3fcac851..d4aee3c780 100644 --- a/docs/zh/design/appserver/session-title-metadata.md +++ b/docs/zh/design/appserver/session-title-metadata.md @@ -245,4 +245,3 @@ CREATE TABLE session_metadata (session_id TEXT NOT NULL PRIMARY KEY REFERENCES a ## 附录 A. Rust 绑定 「本节由 [SessionStore 契约](../../../design/plugins/SessionStore.md#operations) 取代。」 - From c6d1dae4fd49273eb518af669151a35cc438ba1d Mon Sep 17 00:00:00 2001 From: scotares <ericted8810@gmail.com> Date: Tue, 24 Nov 2026 19:33:15 +0800 Subject: [PATCH 19/19] docs(storage): carry main's removal registration into the contracts The store's removal checks and registers the resolved root, releases the exclusion, runs the callback in its own task and re-takes the exclusion to delete the record and clear the registration; create, fork, associate and a second removal refuse a path at, under or above a registered root. Creations register symmetrically, the record-only cleanup keeps its operation, and the worktree owner states the non-Unix unregistered removal rule. Refs #2018 Refs #2015 --- docs/design/plugins/ManagedWorktrees.md | 2 ++ docs/design/plugins/SessionStore.md | 9 +++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/design/plugins/ManagedWorktrees.md b/docs/design/plugins/ManagedWorktrees.md index 63a4fb9920..9c744137db 100644 --- a/docs/design/plugins/ManagedWorktrees.md +++ b/docs/design/plugins/ManagedWorktrees.md @@ -122,6 +122,8 @@ A process death between `create` and `store.create` leaves an unregistered direc - A branch is kept when `remove` deletes a worktree: committed content must not disappear with the directory, and `worktree.list` reports it. - `discard` is not cancellable: a cancelled Session creation still has to settle what the owner made. A store refusal (`closed` or `storage`) leaves the directory and branch in place; the caller reports it. The preparation is dropped with the generation, so the directory is unregistered and `remove` by task id is the retry path on the replacement generation. - Unregistered directories are never pruned: the owner has no record to age, so only an explicit `remove` by task id deletes them. +- A creation registers its selected root in the store's creating set before it makes the directory; a removal that meets the registration is refused, and a failed creation hands the registration to the removing set so its own cleanup is not blocked. The set is in memory; a process death leaves the directory removable by task id. +- An unregistered directory's non-force removal on a non-Unix platform is refused `worktree_in_use` with the advice to pass `--force`, because the platform primitive cannot delete only empty directories while staying inside the managed root. - The preparation table exists because a created worktree has no record until the Session adopts it: the task id is the only handle a caller keeps after its own state is lost or reloaded, so `discard` settles by id instead of by a value the caller may no longer hold. - A branch outlives a creation that was never adopted: a process death between `create` and `store.create` leaves the branch. `remove` on an unregistered directory never deletes a branch; `worktree.list` reports it, and the operator deletes it with Git. The preparation table is gone by then, so the owner cannot tell a default `dim/<taskId>` branch from one the operator named; never deleting is the only decidable rule. - Git is the owner's process resource: the owner starts each call, bounds it (10s read, 30s write) and reaps it on cancellation. diff --git a/docs/design/plugins/SessionStore.md b/docs/design/plugins/SessionStore.md index aaef64d732..e8b2214eb3 100644 --- a/docs/design/plugins/SessionStore.md +++ b/docs/design/plugins/SessionStore.md @@ -127,6 +127,7 @@ Every operation takes one request object and answers one reply object. Writes ar | `worktreeUsages` | The Session associations of one recorded directory | `{repository, root}` | `{usages}` | None | `invalid`, `closed`, `storage` | | `sessionsUnder` | Stored Sessions whose workspace is a root or lies under it | `{root}` | `{sessionIds}` | None | `invalid`, `closed`, `storage` | | `removeWorktree` | Remove a directory under the Session exclusion, with the caller's own removal step; the record may be absent and an already-missing root is success | `{repository, root}` + `remove` | `{removed}`; true when a record was deleted | The caller's step ends; the record, if any, stays | `invalid`, `in_use`, `rejected`, `closed`, `storage` | +| `removeWorktreeDirectory` | Delete one directory record only, with the association and stored-workspace checks | `{repository, root}` | `{removed}` | None | `invalid`, `in_use`, `closed`, `storage` | | `removeUnregisteredDirectory` | Remove a directory no record names, under the Session exclusion, with the caller's own removal step | `{root}` + `remove` | `{removed}` | The caller's step runs to its end; no record is involved | `invalid`, `not_found`, `in_use`, `rejected`, `closed`, `storage` | `worktree` in `create` and `associateWorktree` is `{repository, root, subtree}`: absolute UTF-8 paths, `subtree` inside `root`, and no `.` or `..` component. The caller passes paths it already resolved; the owner re-checks that each is absolute, UTF-8, has no relative component and, for an association, that the root still is a directory. @@ -197,14 +198,18 @@ When a change, text or removal callback refuses, the operation answers `rejected | `addGrant`, `removeGrant`, `setLanguage`, `associateWorktree` | One write transaction | None after it starts | The write completes; the reply may be lost | Admitted writes end before close | SessionStore | | `setTitle` | Admit the write behind earlier admitted writes, read the current title, call `change` under the serialization, write the returned title as revision + 1, commit, announce, answer the revision | Dropping the reply never cancels the admitted write; a change that refuses leaves the title unchanged | Once the change is called the write commits even if the calling row unloads; a change not yet started is revoked and the write ends `closed` with the title unchanged | Close stops admission, waits for every admitted write | SessionStore; the change computes only | | `removeWorktree` | Validate the paths, take the exclusion, check associations and stored workspaces, call `remove`, delete the record on success, release | The removal step refuses with its own code (for example `cancelled`); the record stays | The callback ends; the record stays; the exclusion releases | New calls are refused `closed`; an in-flight removal ends, and the record stays unless the step succeeded | Directory by the caller; record by SessionStore | -| `removeUnregisteredDirectory` | Validate the root, take the exclusion, check stored workspaces under it, run the removal step as the owner's task, release | The removal step refuses with its own code; nothing changes | The owner task continues to the end and the exclusion is not released to the caller | New calls are refused `closed`; the running removal finishes and keeps the lock until it ends | Directory by the caller; exclusion by SessionStore | +| `removeUnregisteredDirectory` | Validate the root, take the exclusion, check stored workspaces, register the root as being removed, release; the owner task runs the removal step, then re-takes the exclusion to clear the registration | The removal step refuses with its own code; the registration is cleared | The owner task continues to the end | New calls are refused `closed`; the running removal finishes and clears its registration | Directory by the caller; registration by SessionStore | ## Exceptions with reasons - `create` takes the caller's already-validated configuration; `fork` reads the source text itself and calls the caller's text step under the fork's exclusion, so the lifecycle owner's `initialTitle` decision cannot race the copy and the copied bytes stay the source's text. - `delete` does not close the Session, remove its Agent admission slot or remove the worktree: closing is Agents', and a managed worktree is removed by ManagedWorktrees under `removeWorktree`. - `setTitle` runs the caller's change under the owner's serialization: the change only computes the next title from the current title and revision, and returns its own refusal; the reply may be lost, so the caller re-reads rather than assumes failure. -- `removeWorktree` serves both a recorded directory and a directory a failed creation left without a record (ManagedWorktrees' `discard`); the record is deleted only when it exists, and the reply says whether one was deleted. It runs ManagedWorktrees' removal step under the Session exclusion: the directory is that owner's resource, and the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. The caller must not call SessionStore operations from the step; a failed or cancelled step keeps the record, and a row unload or owner close keeps it too. The exclusion has no time bound: a recursive forced deletion of an unregistered directory may run to its end, and `removeUnregisteredDirectory` uses the same exclusion for a directory no record names. +- `removeWorktree` serves both a recorded directory and a directory a failed creation left without a record (ManagedWorktrees' `discard`); the record is deleted only when it exists, and the reply says whether one was deleted. It runs ManagedWorktrees' removal step under the Session exclusion: the checks and the record deletion cannot interleave with a Session creation that would point into the removed root. A failed or cancelled step keeps the record and clears the registration. + +Removal and creation use a registration, not a held lock: `removeWorktree` and `removeUnregisteredDirectory` check under the exclusion, register the resolved root in the in-memory removing set, release the exclusion and run the callback in the owner's task, then re-take the exclusion to delete the record and clear the registration. While a root is registered, `create`, `fork`, `associateWorktree` and a second removal refuse any path equal to, under or above it with `invalid`; the worktree client maps that to `worktree_in_use`. A creation registers its selected root in the symmetric creating set under the same exclusion; a removal that meets it is refused `in_use`. The registration lives in memory only, so a process death leaves a half-removed directory that `remove` by task id retries. The callback has no time bound: a recursive forced deletion runs in the owner's task, and dropping the caller neither stops it nor releases the registration. + +`removeWorktreeDirectory` is the record-only cleanup: it takes `{repository, root}`, applies the same association and stored-workspace checks, refuses a path being removed, deletes the directory record and answers `{removed}`; it removes no directory. - `owner` answers the Agent id for a delete notice; the Agent directory's own records are not returned here. - `associateWorktree` dedupes the directory record by `(repository, root)`: a repeated association for the same Session and directory replaces the subtree and updates its last use, and a new directory inserts one record. A retry after a lost reply therefore leaves one record and the caller's latest subtree. - `setTitle`'s change runs inside the owner's serialization and must not call `store` operations that take the same lock; it computes the next title only.