diff --git a/crates/dim-app-server/README.md b/crates/dim-app-server/README.md index 063e2ab994..86278f143e 100644 --- a/crates/dim-app-server/README.md +++ b/crates/dim-app-server/README.md @@ -521,105 +521,7 @@ The Dim account (`dimcode-api-oauth`) is such a plugin, in [`crates/dim-oauth`]( ### Trusted plugin storage -The native provider is installed once whenever the host supplies an authorized -product root. Public process, Session and branch rows use the same provider; a -Session-only configuration needs no process row. Without -that root, no provider or working-directory fallback is supplied. See the -[public binding](../../docs/design/process-typescript.md#52-public-pluginfiles-binding). -The embedding host must provision each consumer's parent directories before -enabling it: `withLock` returns `io` for a missing parent and does not create it. -A host without a product home names its plugin root in `ServerConfig.plugin_files`. The `dimcode` development profile (`--model-config`) uses its `--home` directory, so the root and its `scheduler/` directory are provisioned there. - -A plugin with a row-bound scope declares `inject: ['pluginFiles']` and opens a fresh scope during each `apply`. Register `scope.close()` with `ctx.effect` immediately after opening, then register business cleanup. The host chooses the authorized product root; the plugin supplies relative file paths only. This is a trusted-plugin API, not a sandbox for untrusted Node code. - -A scope offers `withLock(name, callback, cancelled?)`, `list(prefix)`, `remove(name)`, `directory(name)`, `openRead(name)` and `writeStream(name, next)`; a lease offers `read()`, `replace(text)`, `backup(suffix)`, `readBytes()` and `replaceBytes(bytes)`. Every name is a path relative to the authorized root, resolved through FileStorage: `..`, an absolute path and this module's reserved names fail `invalid_path`. - -`list(prefix)` returns one level of the directory `prefix`, sorted by name, each entry its name relative to the authorized root and its kind (`file`, `directory`, or `other` for a link or special file, never followed). A returned name is the stored components joined by `/`, so it can be passed straight to another operation; on Unix a backslash is part of a name, and on Windows it is a separator. It does not recurse and does not enter a directory entry, and the root itself is not listed, so a prefix names a directory. An entry whose name is not valid UTF-8 is omitted: these operations address names as strings, so it could not be read either, but removing the directory removes it. `remove(name)` removes a file, or a directory and everything beneath it. A file a lease holds, and a directory with a lease held beneath it, fail `locked`; an absent entry counts as removed, so a retry is safe. Removal is not atomic: an error can leave part of a tree removed. - -Every file is either a text envelope or raw bytes. `read()` and `replace(text)` use the envelope below. `readBytes()` returns the file's bytes whole, so a text file returns its stored envelope; `replaceBytes(bytes)` writes raw bytes with no envelope. A text read of a raw file fails `invalid_data` and leaves it untouched. Both byte operations are whole-buffer and capped at [`MAX_WHOLE_FILE_BYTES`](src/plugin_files.rs) (8 MiB), which bounds one allocation; a file over the cap fails `invalid_data` before it is read, and a replacement over it fails `invalid_data` without writing. A text `replace` is admitted when its serialized record fits the runtime's 16 MiB frame; a larger one fails that call with a `BindingError` coded `bad-value` naming the limit, and leaves the file unchanged. rutis 0.23 chunks a larger call frame up to the deployment's `max_transfer`, so the runtime no longer refuses a call at the 16 MiB boundary; limits that a Dim face does not enforce are not guaranteed. For larger files use a pinned reader or a streamed replacement as described below. - -`PluginFiles::open(ctx)` ties a Rust scope to its row. EventHub uses `PluginFiles::scope(Some(ctx.clone()))` so admitted publishes can finish their writes across a row restart. The caller releases its last `Arc` after those operations settle. Stopping the file provider cancels and drains its active operations. The scope’s `with_lock(name, change)` runs `change` on the inner text under the file's lock. `change` receives `None` for a missing file and returns the replacement text (`None` keeps the file as it is) together with its own result. The host writes and checks the same `{version: 1, text}` envelope. An envelope that is not version 1 fails with `InvalidData` before `change` runs, and its bytes stay unchanged. - -The file scope also provides these operations. - -| Method | Value | -| --- | --- | -| `read_bytes(name)` | the whole file, envelope included, or `None` when absent; over the cap is `InvalidData` | -| `open_read(name)` | `OpenRead { read_id, size }` for `FsHost::read_at` and `close_read`, or `None` when absent | -| `write_stream(name, source)` | replaces the file from a reader under its lock; no envelope and no size bound | -| `list(prefix)` | one level under `prefix`, each a `PluginFileEntry { name, kind }` | -| `remove(name)` | a file or a directory tree; `Locked` while a lease holds it or a file beneath it | -| `directory(name)` | makes the directory and its missing parents (mode 0700) and returns the absolute path | - -`write_stream` writes through FileStorage's own temporary file and atomic rename, so a failure or cancellation leaves the old content and no temporary file. `directory` is for handing a work directory to a helper process: a link or other non-directory at any existing component fails `InvalidPath`, so the returned path never names a followed link. The path names what the call created; a component replaced by a link afterwards is outside its control. A plugin calls `scope.directory(name)` for the node-local path. `scope.openRead(name)` returns null for a missing file or the pinned reader ID and size for `fsHost.readAt` and `fsHost.closeRead`. The opening row owns the reader until explicit close or unload. `scope.writeStream(name, next)` pulls one byte chunk per callback until the source returns null. A source failure discards the partial replacement. - -Import `PluginFiles`, `FileScope`, `FileLease`, `FileEntry` and `FileResult` with -`import type { PluginFiles } from 'dimcode/plugin'`. The -[SDK declarations](../../npm/plugin.d.ts) define the method types; the -[plugin author's guide](../../docs/typescript-plugin-authoring.md) shows their use. -`quiesce()` synchronously returns null; `close()` waits for admitted work and -resolves to null. Awaiting either remains valid. - -`withLock` holds the native FileStorage lease through the complete callback, including asynchronous work. Reads validate the storage record below and return its UTF-8 text; a missing file returns null. Replacement is atomic and flushed, with Unix mode 0600 and native Windows DACL handling. `backup` creates a flushed, exclusive sibling copy with an alphanumeric/hyphen suffix. A failed partial backup is retained; an existing backup is never overwritten. Storage errors expose only fixed codes, never file contents or exception text. An error after replacement does not imply rollback or authorize replaying remote side effects. - -Use a fresh suffix for each backup attempt, such as `before-reset-`. An `exists` result does not prove the earlier backup completed. After a failed backup, stop the destructive operation, address the storage failure, and create a successful backup with a new suffix before proceeding. Retained partial backups require explicit operator inspection and cleanup; the lease has no deletion API. Host worker failures return `internal`, distinct from invalid arguments or paths. Callback exceptions retain Rutis rejection semantics and still revoke the lease. - -Quiesce rejects new transactions and cancels acquisition, but permits an acquired transaction to persist before close joins it. The optional Promise cancels acquisition when it settles; Node must settle it on ordinary completion too so a pending exported Promise cannot hold runtime drain open. Rutis 0.10 does not encode Node AbortSignal arguments; do not pass one. Escaped file callbacks are revoked before releasing the lease. Abandoning the caller does not abandon issued I/O. Runtime loss revokes the lease after admitted native I/O settles; it cannot guarantee persistence of an external side effect whose result died with the runtime. - -Bytes a plugin stores pass through this trusted local bridge. They must never be forwarded to terminal RPC, model requests, history, diagnostics or logs. Startup follows current loader row identities: Rutis may replace an offline JS row when it discovers its declared injections, so a disposed provisional fiber is not itself a startup failure. A row that remains disposed consumes the remaining startup deadline before reporting its terminal state; an explicit failed state still fails immediately. - -#### Storage record format - -PluginFiles owns a UTF-8 JSON storage envelope, independent of the plugin's -payload schema: - -```json -{"version":1,"text":"opaque plugin-owned UTF-8 text"} -``` - -Both fields are required; `version` is the integer `1`, `text` is a string, -and additional fields are invalid. The host does not parse or validate `text`. -`replace(text)` atomically writes this envelope through the existing FileStorage -lease, preserving the existing permissions, durability and cancellation rules. -`read()` decodes and validates the envelope at this external storage boundary -and returns only `text`; a missing file still returns `null`. Only `read` and -`replace` use the envelope; `readBytes` and `replaceBytes` carry the file's -bytes as they are. - -An unversioned file, malformed record, unknown version or invalid UTF-8 returns -the existing fixed `invalid_data` error, without file contents or parser details. -Read failure never rewrites or deletes the original. There is no automatic -migration, fallback to empty state or interpretation of an unknown format. -No distributed Rust App Server build used the unversioned PluginFiles format. -Files from before v1 are development data: the owning plugin and data owner must -explicitly decide whether to recreate that state or preserve it for manual -recovery. The host never resets, converts or deletes these files on read. This -baseline is separate from native SQLite storage and changes no database format. - -`backup(suffix)` remains a byte-for-byte copy of the stored file, including its -envelope or any rejected legacy bytes. A backup must not decode, re-encode or -upgrade its source. An explicit `replace` writes version 1; the caller still owns -the decision to replace existing data and to make a successful backup first. -`readBytes` and `replaceBytes` do not use this envelope: a binary file is raw -bytes, and a text file's bytes are its envelope. - -##### Rule check - -§1 and ADR 002 D1–D3 keep storage in the existing process plugin and -FileStorage dependency, without a wiring layer or new lock. §4 rules 1–6 and 9 -are unchanged: there are no Timeline events, handovers, before callbacks or -context changes. §4 rule 7 keeps storage validation at its owner. ADR 002 D4 -leaves plugin business settings and payload schemas with their owners; D5 keeps -the existing language-neutral service and error data unchanged. - -##### Requirements raised to mechanism owners - -None (§4 rule 8). Existing atomic -replacement, listing, removal and directory primitives cover the operations. -Acceptance uses disposable plugin roots to verify round-trip text and binary -files, stored version, reopen, version rejection with byte preservation, the -whole-buffer bound, listings, removal under a held lease, work directories and -unchanged transaction/backup/lifecycle behavior. +This section is superseded by the [PluginFiles contract](../../docs/design/plugins/PluginFiles.md). ## Managed provider contract diff --git a/crates/dim-oauth/docs/runtime-contract.md b/crates/dim-oauth/docs/runtime-contract.md index 7505663e68..e312847075 100644 --- a/crates/dim-oauth/docs/runtime-contract.md +++ b/crates/dim-oauth/docs/runtime-contract.md @@ -27,13 +27,13 @@ terminal and returns `cancelled`. DimOAuth never writes Session metadata or choo ## Account record -`/auth.json` is the only persisted source of Dim credentials (`nextApiOauth`) and account state (`dimAccountState`, schema 1: `credentialEpoch`, `generation`, `credentialRevision`, `state`, and when authenticated `identity` and `tokenDigest`). It is plain JSON shared with the native subscription providers; other root fields belong to their owners and are preserved. Writes go through the product root's FileStorage lease, which also serializes concurrent processes, with Unix mode 0600. A lookup that finds a usable record reads the file atomically without that lease, so a fresh grant creates no `auth.json.lock` marker and no fsync; the lease is taken when a refresh, normalization or any other write is needed. The provider publishes whether the file stores a signed-in account as a watch, and moves it after every write. The startup initialization and the host's `observe_account` share one read-only observation. An observation whose validated state already equals the published one answers from the atomic read and publishes nothing; a missing `auth.json` is a home that never signed in, and the observation neither creates nor normalizes it. The first observation, or one whose state differs, takes the lease, rereads the file and publishes that validated read, whose `tokenDigest` must match its grant, before releasing the lease; a record this build cannot validate publishes nothing. The observation ends with its caller's wait: dropping the wait ends the lease wait, so a timed-out Session read leaves no retry behind. An `account.status` read whose result differs from the published state — including the first read after an uninitialized start — takes the lease and reads the file again, publishing that observation before releasing it, so a read that started earlier never overwrites a newer write or logout; an unchanged result answers from the atomic read without the lease. `tokenDigest` is the SHA-256 of the grant's RFC 8785 canonical JSON. +`/auth.json` is the only persisted source of Dim credentials (`nextApiOauth`) and account state (`dimAccountState`, schema 1: `credentialEpoch`, `generation`, `credentialRevision`, `state`, and when authenticated `identity` and `tokenDigest`). It is plain JSON shared with the native subscription providers; other root fields belong to their owners and are preserved. Writes go through FileStorage's `auth.json.lock` marker (the `claim`/`update` protocol), which also serializes concurrent processes, with Unix mode 0600. A lookup that finds a usable record reads the file atomically without the marker, so a fresh grant creates no `auth.json.lock` marker and no fsync; the marker is claimed when a refresh, normalization or any other write is needed, and released only after the row's admitted claim-carrying update settles. The provider publishes whether the file stores a signed-in account as a watch, and moves it after every write. The startup initialization and the host's `observe_account` share one read-only observation. An observation whose validated state already equals the published one answers from the atomic read and publishes nothing; a missing `auth.json` is a home that never signed in, and the observation neither creates nor normalizes it. The first observation, or one whose state differs, takes the marker, rereads the file and publishes that validated read, whose `tokenDigest` must match its grant, before releasing the marker; a record this build cannot validate publishes nothing. The observation ends with its caller's wait: dropping the wait ends the marker wait, so a timed-out Session read leaves no retry behind. An `account.status` read whose result differs from the published state — including the first read after an uninitialized start — takes the marker and reads the file again, publishing that observation before releasing it, so a read that started earlier never overwrites a newer write or logout; an unchanged result answers from the atomic read without the marker. `tokenDigest` is the SHA-256 of the grant's RFC 8785 canonical JSON. The TypeScript plugin (0.2.0) wrote this file as a PluginFiles record `{"version":1,"text":...}`. Reading accepts that record, keeping fields other owners wrote beside it; the next write stores plain JSON. Its digests verify unchanged, so a signed-in account survives the upgrade with the same epoch and generation. JSON or root errors and an unknown schema remain errors and are never shown as signed out. Only an explicit login or logout resets a corrupt schema-1 record: the complete original bytes are first written exclusively to `auth.json.dim-reset-backup`, then only the Dim fields are replaced by a new signed-out state. An existing backup blocks another reset and is never overwritten or removed. Explicit recovery (`account.recover`) accepts a legacy grant or a digest mismatch, confirms the identity online and starts a new epoch at generation 1. -Login captures the record's revision before starting and compares it when committing. Logout advances the signed-out generation, including when already signed out, and revokes the refresh token on a best-effort basis. Credentials are refreshed within a 30-second freshness window, under the account lock, and a rotated grant is persisted before the lock is released; 408, 429, 5xx and network failures keep the stored grant, and an explicit rejection signs out only the grant that holds the lock. Requests resolve their credential under this window, which is the correctness boundary: a fresh grant answers from the atomic read, and only a grant inside the window waits for the lock and refreshes. While the process runs, a background task also renews the grant as it enters the window, so an idle process does not let its refresh token lapse. It renews and persists a rotated grant and signs out a rejected one, but it never normalizes the record it reads; write-on-normalize stays with the explicit account operations. It retries a transient failure after 60 seconds, and stops after a sign-out or an unusable record until this process signs in again. Quiesce ends it. +Login captures the record's revision before starting and compares it when committing. Logout advances the signed-out generation, including when already signed out, and revokes the refresh token on a best-effort basis. Credentials are refreshed within a 30-second freshness window, under the account marker claim, and a rotated grant is persisted before the claim is released; 408, 429, 5xx and network failures keep the stored grant, and an explicit rejection signs out only the grant that holds the claim. Requests resolve their credential under this window, which is the correctness boundary: a fresh grant answers from the atomic read, and only a grant inside the window waits for the lock and refreshes. While the process runs, a background task also renews the grant as it enters the window, so an idle process does not let its refresh token lapse. It renews and persists a rotated grant and signs out a rejected one, but it never normalizes the record it reads; write-on-normalize stays with the explicit account operations. It retries a transient failure after 60 seconds, and stops after a sign-out or an unusable record until this process signs in again. Quiesce ends it. The public host contract (`ManagedProvider`, its DTOs, leases, quiesce and error mapping) is in the [App Server README](../../dim-app-server/README.md#managed-provider-contract). diff --git a/docs/architecture/rust-agent/plugins/FileStorage.md b/docs/architecture/rust-agent/plugins/FileStorage.md index a9b0942039..f96afd4b7b 100644 --- a/docs/architecture/rust-agent/plugins/FileStorage.md +++ b/docs/architecture/rust-agent/plugins/FileStorage.md @@ -2,14 +2,576 @@ Owner: [file_storage.rs](../../../../crates/dim-agent-capabilities/src/file_storage.rs) and [windows.rs](../../../../crates/dim-agent-capabilities/src/file_storage/windows.rs). -Provides authorized-root-relative file operations and leases with secure path -traversal and serialized mutation, plus directory creation, listing and removal. -## Dependencies +Target contract for [#2016](https://github.com/arcships/dim/issues/2016) and the current implementation. + +Scope: process. Issue: #2016. + +FileStorage owns byte storage under explicitly authorized roots. This document is the owner's target contract; the current implementation is described in [Current implementation](#current-implementation) below. PluginFiles is a separate owner with its own contract and is not covered here; its calls appear in the delivery tables in the [delivery comment on #2016](https://github.com/arcships/dim/issues/2016#issuecomment-7090617699). + +## Use and scope: responsibility split + +FileStorage owns: + +- **Roots.** The process's authorized directories and their open handles. The host registers the roots it assembles with and the workspace of each Session it creates. `add_root` lets a trusted process part make a runtime directory addressable (Settings' project authorization, the UI extension directories, the migration source); `root_path` answers a root's directory for a caller that was given its id. Both are values, and neither grants authority: the trusted-plugin boundary and Permission decide what may be read or written. +- **Generations.** One service instance admits calls, owns the descriptors it opened and releases them on close. +- **Exclusion.** Each file's lock key beside the file; `auth.json`'s lock is the account marker instead. A replacement, removal or update holds the key; another process holds the same key for the same file under every case and Unicode spelling the filesystem equates. FileStorage waits for the key until the caller cancels or the owner closes. +- **The account marker.** `auth.json` uses the published marker `auth.json.lock` beside it: an exclusive file carrying the holder's process id, creation time and nonce. `claim` returns an id for it, `release` removes it, and a marker older than 30 seconds without a live process at its creation is reclaimed. Creation and reclamation of the marker are serialized by the private `auth.json` key in the reserved directory; the key is held only while creating or reclaiming and is released before waiting, and it never crosses the face. Every operation that writes, removes or imports over `auth.json` takes the same marker for its call; any holder, including the row that holds a claim, waits. A claim holder writes only through `update(claim_id)`; for any other operation it releases the claim first. +- **Atomic replacement.** A temporary file in the owner's namespace, flushed and renamed over the target, with the durability answer. +- **Reads and facts.** A whole document up to 8 MiB, one 64 KiB page at an offset, and a file's kind and size; reads are stateless, so no read id crosses. +- **Path validation.** Absolute paths inside a root, one validated component per open, no link followed, the owner's own resource names excluded. + +Callers keep: + +- Document formats and versions: settings documents, `auth.json`, the plugin envelope, JSONL records. +- Which root and file a business uses, and the file names. +- What a business conflict means and when to retry it. +- Permission and approval: FileStorage never decides whether a call may run. +- Workspace, system and worktree facts: FileAccess owns them; FileStorage answers only whether an absolute path is inside a root. +- Files a plugin creates and manages itself under a root, such as SQLite's database, the model-log recorder's JSONL and the UI extension cache. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Read one document: settings, accounts, plugin records, a project's hooks file | Yes: `read` without an offset reads the whole document and answers none when absent | Business composes | +| Read a large file in pages | No: the owner bounds one reply to a page, reports the end and the file's size, so the caller never holds an id or a page size of its own | `read` with `offset` and `length` | +| Learn a file's kind and size before reading or writing it (a permission fact, a publish) | No: existence, kind and length are one owner read, and a read cannot answer them without a file | `stat` | +| Replace a document's bytes atomically | Yes: `write` whose source yields the whole content once | Business composes | +| Write content that arrives in pieces, including a stream an adapter produces | No: holding it whole is unbounded; the temporary file and the key must stay inside the owner | `write` with a source | +| Read, decide and write back while other processes may replace the file | No: between a read and a write another writer replaces the file, so only the owner can hold the file across the caller's decision | `update` with a change | +| Keep the replaced bytes before a destructive rewrite | Yes: read the current bytes, `write` a sibling copy, then `update` whose change refuses when the bytes moved | Business composes; DimOAuth compares inside the change and retries | +| Hold the account marker across a credential refresh | No: the marker is the published cross-process exclusion, and only the owner can create, reclaim and verify it | `claim`, `release`, and `update` with `claim_id` | +| Refresh a credential | Yes: read the record, judge freshness, call the provider and write back inside the claim | Business | +| Bring a host file the caller named into a root | No: the source is outside the roots and must be bounded and land atomically | `import` | +| Keep a document's file owner-only from creation (settings, accounts) | No: the mode is a file attribute the owner applies at creation and replacement | `permissions` on `write`, `import` and `update` | +| Write a Session file that `write` and `edit` may not modify | No: the read-only attribute is a file attribute the owner applies | `permissions` | +| Bound a host file import by the business limit (a Session attachment) | No: the caller's limit must stop the copy before it lands | `import` with `max_bytes` | +| Make a work directory tree and learn its absolute path | No: per-component link and alias validation is the owner's knowledge | `create_directory` | +| List one level and remove by a listed native name | No: the name's encoding and the single-component rule are the owner's knowledge | `list`, `remove` | +| Make a runtime-discovered directory addressable | No: the root set is the owner's state, and a root is a value other parts address | `add_root` | +| Hand a root's directory to another module: a process working directory, a path quoted in history, a log directory | No: the root set is the owner's state | `root_path` | +| Learn whether an optional file exists (a project hooks file, a Settings source) | Yes: `read` answers none; `stat` answers `missing`; `list` answers the parent's entries | Business composes | +| Decode or encode a document, choose its name and its root | Yes: formats and business paths stay with callers | Business | +| Append records to a log it owns (the model-log recorder) | Yes: the recorder owns the file; `root_path` gives it the directory | Business; the file is the recorder's, as SQLite's database is | +| Write a UI extension cache and then publish it | Yes: the cache belongs to UiExtensions; FileStorage reads it only on request | Business | +| Decide whether a read or write is allowed | Yes: Permission and Approval decide | Business | + +An operation or parameter exists only where its row says No. + +## Caller example + +Reading one document, one page, and a file's facts: + +```rust +// Whole document: none when absent, too_large above 8 MiB. +let Some(document) = storage.read(path.clone(), None, None, cancelled.clone()).await? else { + return Ok(None); +}; +let document = document.data; +// One 64 KiB page: size is the file length, eof says the page reached the end, +// and an offset past size is invalid rather than an empty page. +let page = storage.read(path.clone(), Some(offset), Some(PAGE), cancelled.clone()).await?; +// Existence, kind and size without reading the bytes. +let facts = storage.stat(path, cancelled).await?; +``` + +Settings' compare-and-set: the change runs under the owner's file key, sees the current content and returns the next content or a business refusal. + +```rust +storage.update( + ctx, + path, + Arc::new(move |current: Option| { + Box::pin(async move { + let current = decode(current.as_ref().map(|bytes| bytes.0.as_slice()))?; // business format + let next = check_and_update(current, document)?; // business rules, including the document's own revision + Ok(Some(Bytes(encode(next)?))) + }) + }), + None, + Some(Permissions::Private), + cancelled, +) +.await?; +``` + +SessionStore's write of bytes, and of a host path: + +```rust +// `once` is a source that yields the bytes once and then none. +let size = storage.write(path, once(bytes), Some(Permissions::PrivateReadOnly), cancelled.clone()).await?; +// A host file the caller named, without reading it first. +let size = storage.import(path, source, Some(MAX_FILE_BYTES), Some(Permissions::PrivateReadOnly), cancelled).await?; +``` + +DimOAuth's reset: copy the current file, then rewrite it under the owner's key. The change refuses when the bytes are no longer the ones that were copied, and the caller retries the whole step. + +```rust +let current = storage.read(auth_path.clone(), None, None, cancelled.clone()).await? + .ok_or(OAuthError::UnsupportedSchema)? + .data; +// The backup is a business copy; the rewrite starts only after the copy is durable. +storage.write(backup_path, once(current.clone()), Some(Permissions::PrivateReadOnly), cancelled.clone()).await?; +storage.update( + ctx, + auth_path, + Arc::new(move |stored: Option| { + Box::pin(async move { + if stored.as_ref() != Some(¤t) { + return Err(Rejected::new("conflict", "the account file changed after it was copied")); + } + let mut document = parse(stored.as_ref().map(|bytes| bytes.0.as_slice()))?; // business format + document.remove(TOKENS); + document.insert(STATE.into(), signed_out()); + Ok(Some(Bytes(encode(document)?))) + }) + }), + None, + Some(Permissions::Private), + cancelled, +) +.await?; +``` + +UiResources' publish and pages, with no id to release: + +```rust +// The size is checked at publish; a page request beyond it is the caller's invalid_params. +let facts = storage.stat(path.clone(), cancelled.clone()).await?; +let size = facts.size.unwrap_or(0); +let page = storage.read(path, Some(offset), Some(PAGE), cancelled).await?; +``` + +A module that needs a root's directory, such as the model-log recorder: + +```rust +let home = storage.root_path(home_root)?; +let directory = format!("{home}/model-log"); // the recorder owns this file +``` + +## Callers that hold work across an external wait + +The public face has no lease. Managed OAuth composes its exclusion from `claim`, `release` and `update`; Migration and PluginFiles compose theirs from `update`, and the owner keeps the guarantee that one `update` is exclusive across processes. + +**Managed OAuth, with a rotating refresh token.** `auth.json.lock` is the one exclusive lock for `auth.json`; there is no separate file key exposed to callers. `claim` and a directory removal that meets the marker take the private `auth.json` key while they create or reclaim it, release it before waiting, and re-acquire it after the wait; `release` removes the marker by matching its owner record without the key. Two reclaimers therefore cannot both create a marker, and a waiter never blocks the holder's release. The caller claims it with `claim(path)`, which creates the marker with its process id, creation time and nonce and returns a claim id. The caller reads the record and judges freshness. The winner performs the HTTP refresh while it holds the marker, then writes the rotated record with one `update(path, change, claim_id)`: the owner checks that the marker still carries this claim's nonce (a reclaimed claim answers `rejected` with reason `claim-lost`) and runs the change under that same hold without taking the lock again; the change compares the record's `credentialRevision` with the one it read, refusing with `conflict` when another write advanced it. The caller then releases the claim. If the refresh fails, the caller releases the claim, re-reads the record and adopts it when `credentialRevision` advanced; otherwise it reports the failure. A waiter's `claim` waits for the marker; when it is released, the waiter re-reads the record, adopts it when `credentialRevision` advanced, and otherwise claims and refreshes itself. A `write` or `update` without a claim takes the same lock for its call, so another writer waits while the claim is held; a claim holder writes only through `update(claim_id)` and releases the claim first for any other operation. + +Managed OAuth owns the refresh it issued. Before unload it finishes admitted work, and a cancellation waits for the disk write before returning; an admitted claim-carrying `update` settles before the claim is released, while an unadmitted call ends `cancelled`. On row unload or owner close, FileStorage waits for this row's admitted claim-carrying `update` to settle (the write or an explicit failure) before releasing the claim, so a provider rotation cannot outlive the local claim. The flow tests assert `refreshes == 1` with two callers and a rotating token, a write between claim and commit, a failed refresh with a waiting loser, an external marker-following writer blocked during the refresh, and a row unload between the refresh and its write that settles before the claim is released. + +If the refresh succeeds but its write-back does not, the ending is one of: `io`, `closed`, `conflict` or `claim-lost` means the record was not written; Managed OAuth returns the error, leaves the record as it was and releases the claim. `unsynced` means the content is written but durability is unconfirmed; the caller treats it as success. If the provider already rotated and the record still holds the older refresh token, the next refresh is rejected by the provider and the record becomes `rejected`; the user signs in again ([managed_oauth.rs:1073-1077](../../../../crates/dim-app-server/src/managed_oauth.rs)). Row unload ends the row's admitted refresh, HTTP and its last update, before the release; FileStorage's row-unload release is the fallback after that work settles ([managed_oauth.rs:245-273](../../../../crates/dim-app-server/src/managed_oauth.rs)). + +**Migration snapshot run.** Migration defines its run claim in its own document; the FileStorage operation it uses is `update`. The claim is a file whose change writes the content only when the file is absent and otherwise refuses with a `rejected` error whose reason is `held`; a later run checks the recorded process with the account marker's rule (the process id is alive and its start time is not later than the claim's creation) and replaces a stale claim inside the same `update`. No key is held while a run copies files. + +**PluginFiles.** PluginFiles' transaction is defined by the [PluginFiles contract](../../../design/plugins/PluginFiles.md); its callers change in the same delivery as this face. + +## Own contract + +### Dependencies + +None. FileStorage injects no service and reads no other owner's state. The host registers roots through the provider when it assembles the process and when it creates a Session; trusted process parts add runtime roots with `add_root` and read a root's directory with `root_path`. The provider is chosen by deployment ([resource faces §1](../../../design/resource-faces.md#1-scope)): whether a call reaches a local or a mounted instance is not a property of this name. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `add_root` | Make an existing absolute directory addressable | `{path}` | `root`; an existing root answers its id | Before the directory handle is opened | `invalid`, `io`, `closed`, `cancelled` | +| `root_path` | A root's absolute directory for another module | `{root}` | `path` | None; the owner completes the read | `invalid`, `closed` | +| `stat` | A path's kind and size | `{path}` | `Stat`; `missing` is a kind, not an error | Before the reply | `invalid`, `io`, `closed`, `cancelled` | +| `read` | Read a whole document, or one page of a file | `{path, offset?, length?}` | `ReadReply {data, eof, size}` or none | Before the reply; nothing changes | `invalid`, `too_large`, `io`, `closed`, `cancelled` | +| `claim` | Hold the account marker for `auth.json` | `{path}` | `claim_id`; the marker carries this caller's nonce | While the marker is held | `invalid`, `io`, `closed`, `cancelled` | +| `release` | Remove the account marker this caller holds | `{claim_id}` | unit | None; the owner completes the removal | `invalid`, `io`, `closed` | +| `write` | Replace a file's bytes atomically from a source the owner pulls to its end | `{path, permissions?}` and the `source` callback | `size` | Before the replacement; the temporary file is removed | `invalid`, `missing_parent`, `rejected`, `io`, `unsynced`, `closed`, `cancelled` | +| `import` | Copy a regular host file into a root atomically | `{path, source, max_bytes?, permissions?}` | `size` | Before the replacement; the temporary file is removed | `invalid`, `too_large`, `missing_parent`, `io`, `unsynced`, `closed`, `cancelled` | +| `update` | Change a file's content while the owner holds the file across the caller's decision | `{path, claim_id?, permissions?}` and the `change` callback | `UpdateReply {applied}` | Before the replacement; the temporary file is removed | `invalid`, `missing_parent`, `too_large`, `rejected`, `io`, `unsynced`, `closed`, `cancelled` | +| `create_directory` | Make the path an existing directory tree | `{path}` | `path` | Between levels; created ancestors stay, a retry is safe | `invalid`, `io`, `unsynced`, `closed`, `cancelled` | +| `list` | One level of a directory; the owner's own resources, including equivalent spellings, never appear | `{path}` | `entries` or none when the directory is absent | Before the reply | `invalid`, `io`, `closed`, `cancelled` | +| `remove` | Make a file or a directory tree absent; an absent entry counts as removed | `{path}` or `{parent, name}` | unit | Before the entry is unlinked; a tree can be partly removed, a retry is safe | `invalid`, `io`, `unsynced`, `closed`, `cancelled` | + +`read` without `offset` and `length` reads the whole document up to 8 MiB and answers `too_large` above it; with both, it reads one page of at most 64 KiB (`length` above the page is clamped), `size` is the file's length and `eof` is true when the page reaches the end; one of the two alone is `invalid`. An offset equal to `size` reads an empty page with `eof`; an offset above `size` is `invalid`, and a `length` of 0 is `invalid` (the client paging contract depends on the distinction). An absent file answers none, and so does a missing parent directory. A whole-document read reports `eof: true`. `Bytes` crosses as base64 text, so 8 MiB of bytes fits the 16 MiB bridge frame with the JSON envelope. + +`write`'s `source` and `update`'s `change` are direct method parameters, not request fields. `source` is called repeatedly until it returns none: each call yields the next chunk of at most 8 MiB of raw bytes, or a `Rejected` error that ends the write and leaves the target unchanged; a larger chunk is `invalid`. `change` is called once while the file's key is held, with the current content (at most 8 MiB) or none when the file is absent, and returns the next content (`Some`), no write (`None`) or a `Rejected` error. `None` leaves an existing file unchanged and does not create an absent file, and still runs under the file's key. A returned content above 8 MiB is `too_large`; `applied` is false when the content equals the current one, so a repeated write is idempotent. `change` must only compute: waiting on another owner, on network I/O or on FileStorage itself inside `change` holds the file for that whole wait. §7 allows a callback by reference, and the change is never called inside the Timeline's commit lock. + +`claim`'s `path` is the account file; the owner derives `auth.json.lock` beside it and answers `invalid` for a path without a published marker. A claim is bound to the caller's row for ownership and cleanup: the row's unload releases it and `release` accepts only the claim that row holds. A second `claim` from the same row waits like any caller and can cancel; only one refresh per row runs at a time. `update` with `claim_id` checks the marker's nonce before the change runs; a reclaimed claim is `rejected` with reason `claim-lost`. A write or update of `auth.json` without a claim takes the marker for the call; a claim holder passes `claim_id` only to `update` and releases the claim before any other operation. -No injected services (`Deps = ()`). +`permissions` is absent for "keep the existing mode; a new file gets `private`": `private` is owner-only (0600), `privateReadOnly` is owner-only and read-only (0400), the attribute Session files use. `max_bytes` is absent for the owner's 8 MiB default; a caller with a different business cap passes it. A listed name is passed back to `remove` unchanged. FileStorage waits for a file's key until the caller cancels or the owner closes; there is no fixed bound, so a call that must not wait ends with its cancellation. -## Events and lifetime +### Errors + +| Kind | Retry | What the caller does next | +| --- | --- | --- | +| `invalid` | After fixing the input | A relative path, a destination outside every root, a root's own path, the owner's reserved names (the lock directory, its temporary directory and the account marker, including filesystem-equivalent spellings), a name that is not one component, a directory where a file is required, a file where a directory is required, a link where a directory or a file is required, one of `offset` and `length` without the other, an offset above the file's size, a source chunk above 8 MiB, a claim path without a published marker, an unknown or other-row claim id; for `import`, a source that is relative, missing, not a regular file or a link | +| `missing_parent` | After creating the parent | Call `create_directory` or fix the path; the owner changed nothing | +| `too_large` | For `read`, yes in pages; for `import`, after fixing the source | `read`: use `offset` and `length`, or treat it as not a document; no partial bytes were returned. `import`: the source exceeds `max_bytes` or grew during the copy; nothing was published. `update`: the current or returned content is above the document limit; treat it as not a document | +| `rejected` | Depends on `reason` | The caller's own `change` or `source` refused with its `reason` and `message`, or the claim was reclaimed (`claim-lost`); act on `reason`, for example re-read and retry the business step on `conflict` or re-claim after `claim-lost`. A revoked callback is `cancelled`, not `rejected` | +| `io` | Yes, after fixing the environment | The filesystem refused the operation or the import source shrank while copying: a permission, a device, a network or an unsupported-filesystem error. The message and optional path say which; a `read` or `stat` shows whether the earlier call changed anything | +| `unsynced` | Not as an unchanged write | Durability is unconfirmed: after `write`, `import` or `update` the new bytes are in place; after `create_directory` the directory is; after `remove` the entry is absent. A read or stat shows the state, and a repeated call confirms | +| `cancelled` | Yes, the same call | `read`, `write` and `update` changed nothing before the replacement; `create_directory` and `remove` follow their cancellation columns: created ancestors stay, a tree can be partly removed | +| `closed` | Yes, against the replacement generation | This generation is unloading; the operation did not run or its result is unknown past the replacement, and a `read` or `stat` answers which | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `add_root` | Open the directory handle, append the root; an existing root answers its id | Before the handle is opened or appended; nothing is appended | The call ends `cancelled` | New calls are refused; the append-only root table stays for the next generation, so a root id stays valid | Directory handle and root table by FileStorage | +| `root_path` | Read the root's directory from the root table | None; the call completes | The call completes | A later call is `closed`; a root id stays valid across the reload | Value by FileStorage | +| `claim` | Take the private `auth.json` key, then create `auth.json.lock` exclusively with this process's id, creation time and nonce; a stale marker is unlinked and recreated under the same key and read back to verify its nonce. A live marker, a marker this row already holds, or a lost recreate race releases the key, waits for the marker to clear or change, then re-acquires the key and re-reads; the winner never waits while holding the key | Before the marker is created; a waiter's wait ends `cancelled`; no key is held while waiting | The row's admitted claim-carrying updates settle first, then the claim is released and the marker removed | Pending claims end `closed`; a claim the owner still holds is removed | Marker by FileStorage; the claim id's lifetime by the calling row | +| `release` | Remove the marker whose owner record matches the claim, without taking the private key; a name that no longer carries this claim's marker answers `invalid` | None; the owner completes the removal | The row's claim is released | A later call is `closed`; the marker is removed | Marker by FileStorage | +| `stat` | Open the parent and the entry without following links, read the kind and size, release | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | Descriptor by FileStorage | +| `read` | Open the parent and the file without following links, read the whole document or the page, report `size` and `eof`, release | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | Descriptor by FileStorage | +| `write` | Parent handle, the file's key (`auth.json` takes the marker), temporary file, pull the source to its end, flush, rename, sync parent, release key | The pull stops, the temporary file is removed, the target is unchanged, `cancelled` | The source callback is revoked; the pull fails; the temporary file is removed, `cancelled` | New calls are refused; in-flight calls finish or end `closed`; the generation releases every key and temporary file | Temporary file and key by FileStorage; the source's future by the calling row | +| `import` | Open the source without following links, require a regular file at its initial length, copy into a temporary file, verify the source kept that length (growth is `too_large`, shrink is `io`, neither publishes), rename, sync parent; `auth.json` takes the marker; a claim holder releases the claim first | The temporary file is removed, the target is unchanged, the source closes | The call ends `cancelled` | Pending calls end `closed` | Source descriptor and temporary file by FileStorage | +| `update` | With `claim_id`, check the marker's nonce and run under that hold without taking the lock again; without it, take the file's key (`auth.json` takes the marker) for the call. Read the current content within the document limit, call `change`; `None` writes nothing and releases the key, `Some` writes the temporary file, flush, rename, sync parent, release | Before the rename: temporary file removed, target unchanged, key released, `cancelled`. After the rename: success or `unsynced`, the write is not undone | An admitted claim-carrying update settles (its change stays callable) before the row's claim is released; without a claim the callback is revoked and the call ends `cancelled`; the same release applies | New calls are refused; in-flight calls finish or end `closed`; the generation releases every key and temporary file | Key and temporary file by FileStorage; the change's future by the calling row | +| `create_directory` | Each missing level below the held parent, mode 0700, sync the parent | Between levels; created ancestors stay | The call ends `cancelled` | Pending calls end `closed` | Created directories by FileStorage | +| `list` | Open the directory, read one level, sort by name | Before the reply | The call ends `cancelled` | Pending calls end `closed` | Directory handle by FileStorage | +| `remove` | Parent handle, the entry's key; `auth.json` takes the marker (a claim holder releases the claim first), and a directory holding `auth.json.lock` is handled under the private `auth.json` key, released before waiting: a live marker waits, a stale one is reclaimed by `claim`'s rule, and the marker is never removed as a business entry; remove depth first without following links, sync the parent | Before the unlink: nothing removed; a tree can be partly removed, a retry is safe | The call ends `cancelled` | Pending waits end `closed`; the generation releases keys | Entry removal by FileStorage | + +## Exceptions with reasons + +- `import` reads a host path outside the roots: the caller names a file the user or model chose (an attachment); the owner checks that the source is a regular file, does not follow a link and enforces the byte limit, while the root constrains only the destination. +- The account marker `auth.json.lock` is the published exclusion for `auth.json`: every writer of the file, in this process or another, holds the same marker. The marker is a file carrying the holder's process id, creation time and nonce; a marker older than 30 seconds without a live process at its creation is reclaimed, and a marker this process failed to release is reclaimed at once by its next claim. It coordinates the two Rust writers of `auth.json` — the DimOAuth store and managed OAuth; the TypeScript plugin no longer writes the file ([runtime contract](../../../../crates/dim-oauth/docs/runtime-contract.md) line 32), so this is not a cross-language protocol. +- `Rejected` carries only `reason` and `message`: a callback error must cross languages, so it comes back as data; `From` recovers the wire error's own code into `reason`, and the caller keeps its business error type inside its own callback. +- A file another plugin owns under a root — SQLite's database, the model-log recorder's JSONL, the UI extension cache — is not FileStorage's data; FileStorage does not track ownership and cannot refuse a `remove` of it. The convention that a plugin removes only its own files is the caller's, and a root is not an ownership boundary. +- `claim`, `release` and a claim-carrying `update` take `caller: &Ctx`, the dispatch's calling row, because the claim is bound to that row; it is not caller-supplied data and no caller sends it. +- `add_root` and `root_path` are trusted-host values, not authority: FileStorage is not a sandbox, a root only says which directories are addressable, and Permission and Approval decide what an agent action may read or write. The host registers the roots it assembles with and each Session's workspace; a process part registers a runtime directory it owns. + +## Client-visible changes + +None at the client protocol. This contract changes the plugin-facing `fsHost` surface and three pluginFiles `FileScope` behaviours: `read(name, offset, length)` replaces the pinned reader, `remove` waits for a key instead of answering `locked`, and `withLock` is one `update` instead of a lease held across the callback. Client protocol error codes, notification names, `session.ui.resources.read` (its request, `total` and `bytes`), Session file offset paging, the import reply's `path`, model-visible text, and disconnect and progress behavior are unchanged. UiResources pages by path through `read`'s offset and length; its contract (#2095) records the size at publish and requires a publisher to keep a published path unchanged. A rewrite under a published reference is a UiResources contract violation. The pinned reader is deleted and UiResources moves to path paging in the same delivery; until #2095's replace-between-pages acceptance lands, UiResources' existing version guarantee stays as it is, and the acceptance is an upper alignment item. + +## Supersedes + +- `docs/design/resource-faces.md`: the `fsHost` row of §1, the storage family of §4.1, §4.6, the error table of §4.7, and the `fileStorage` row and FileStorage caller rows of §6. +- `docs/design/contracts/resource-owner-operations.md`: the `fileStorage` row, the FileScope read row and the "OS path, pinned reader and input reader" paragraph. +- `docs/design/service-faces.md`: the `fileStorage` row of §3.4 and the `fileStorage` sentence in the paragraph after the table. +- `docs/design/appserver/session-files.md`: the FileStorage bullet of §3 and §7. +- `docs/design/p6-p7-bindings.md`: the Workflow definitions row of §3, the root registration paragraph and the definition-file paragraph of §3.4. +- `docs/design/plugins/Modality.md`: the FileStorage clause of the dependency table. +- `docs/design/process-typescript.md`: the FileScope read paragraph and §5.2. +- `docs/typescript-plugin-authoring.md`: the `scope.openRead` paragraph. +- `crates/dim-app-server/README.md`: the `openRead` entries of the trusted-plugin storage section. +- `crates/dim-oauth/docs/runtime-contract.md`: the lease sentences of the account record paragraph. +- `docs/design/appserver/session-deletion-and-fork.md`: the FileStorage lease and `replace` references. +- `docs/architecture/rust-agent/plugins/Hooks.md`, `HostPlatform.md`, and `docs/design/appserver/mcp-oauth.md`: the `readBytes` and lease sentences. +- `docs/design/appserver/session-files.md` §16 item 8 and §17 D1: the `create_directory` acceptance and key detail. +- `docs/design/client-ui-extensions.md`: the reading-resource, read-handle and R5 sentences. + +## Verification + +Flow tests on the owner: + +- `read` answers none for an absent file, `too_large` above 8 MiB for a whole read, `size` and `eof` for a page, an empty page at `offset == size`, and `invalid` at `offset > size`. +- A bridge flow test near 8 MiB: the whole-read reply crosses the 16 MiB frame, and a source chunk above 8 MiB answers `invalid`. +- `read` stays stateless: no id is issued, and a page read after a replace sees the replaced content. +- `stat` answers `file`, `directory`, `other` and `missing`, with the size for files and none for the others. +- `write` pulls a multi-chunk source, commits atomically, removes the temporary file when the source fails or is revoked, and leaves the target when cancelled. +- `update` calls the change under the key; a change that returns `Rejected` leaves the file unchanged; an identical result reports `applied: false`; a cancel before the rename removes the temporary file; a failed parent sync reports `unsynced`. +- `import` over `max_bytes` copies nothing; a missing, non-regular or linked source is `invalid`; a destination outside every root is `invalid`. +- `remove` of a tree with a file another writer holds waits, and cancelling ends the wait with `cancelled`; a retry after a partial removal finishes; a link is not followed. +- `add_root` answers the same id for the same path; a root id registered before a provider reload answers its directory after the reload. +- An `update` with a `None` replacement on an absent file creates nothing, and a concurrent creator takes the key after it. +- The managed OAuth flow tests: two concurrent callers and a rotating refresh token perform one refresh (`refreshes == 1`) and both read `rotated-1`; a write between claim and commit answers `conflict` or `claim-lost`; a failed refresh with a waiting loser lets the waiter claim and refresh; a writer that follows the marker waits while another caller holds the claim. + +Material uncertainty: a change that waits on another owner or on I/O holds the file's key for that wait. The contract forbids it; review checks each caller's change. + +## Rule check + +The rules are [design rules §7](../principles.md#7-所有者与操作) and §1–§6 of `docs/architecture/rust-agent/principles.md`. + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | FileStorage is one process part. It writes no Timeline event and folds no state, so it is not a Capability. It injects no service; the process assembly provides it. | +| §2 scopes | Process. Callers are process or Session parts and use the service as a process dependency. No branch or Session state is held. | +| §3 orthogonality | No other owner's state is read or changed. A caller that needs a new file operation gets a general operation here or composes one. | +| §4 rule 1 | No command event: FileStorage writes no Timeline fact. | +| §4 rule 2 | No handoff: the bytes and the key stay with FileStorage. | +| §4 rule 3 | No before callback: the `update` change runs under the file's own key, never inside the Timeline's commit lock. | +| §4 rule 4 | Core and assembly carry no business meaning; no document format, permission or approval appears in this contract. | +| §4 rule 5 | No batches. | +| §4 rule 6 | File content reaches the model only through tool results; the tools own that path, and FileStorage only returns bytes to the owner that asked. | +| §4 rule 7 | Callers use these operations; no caller reads a descriptor, a key or a generation. | +| §4 rule 8 | No infrastructure change and no requirement to a mechanism owner. | +| §4 rule 9 | No Timeline fact. | +| §7.1 resource and lifecycle | FileStorage owns the roots, keys, descriptors and generations; the host registers roots, the owner settles keys and temporary files on close and reload. | +| §7.1 operation granularity | One operation is one state transition or one consistent read; read ids, keys and temporary files never cross a call. | +| §7.1 owner granularity | One process owner for byte storage under roots; no second owner beside it. | +| §7.2 operations | Every cross-plugin call lands on an operation here; the sibling contracts' operations exist. | +| §7.2 handoff | Only values (paths, sizes, root ids, claim ids), read-only views (bytes, entries) and callbacks (source, change) cross; no object or handle. | +| §7.2 no proxying | FileStorage returns no other owner's resource or data. | +| §7.2 one face | One operation set on the owner type; no forwarding facade, command or host object. | +| §7.2 data face | No Rust-only method; caller-supplied arguments, replies and errors are data except the callbacks §7 allows, and `caller: &Ctx` is the dispatch's row identity (see Exceptions), not caller-supplied data. | +| §7.2 business boundary | No caller business concept on the face; each operation and parameter answers why it cannot be composed, in the table above. | +| §7.2 one change | The implementation task deletes the old surface, adds these operations and migrates every caller in one change. | +| ADR 002 D1 | Process scope: roots, descriptors, keys and generations outlive Sessions and are shared across them. | +| ADR 002 D2 | No wiring plugin: the service is on the owner type; no adapter or facade exists beside it. | +| ADR 002 D3 | Dependencies point from extensions to the core; FileStorage depends on nothing and is a process service they may depend on. | +| ADR 002 D4 | Roots are structural: the host registers them, and a trusted business part may register a directory it owns; a root is addressability, and Permission decides what an agent action may do there. | +| ADR 002 D5 | The contract is language-neutral: operations, data and callbacks; the Rust binding is the appendix below. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +The service is marked on the owner type; the wire name stays `fsHost`. The `FsHost` wrapper type no longer exists. `CancelledFn` is the binding's cancellation argument, not a request field. Error codes are the snake_case `code` values of the error table. + +```rust +use crate::host::CancelledFn; +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; +use rutis::Ctx; +use std::sync::Arc; + +/// Raw bytes of a whole read, an update, or one source chunk. Base64 on the wire, +/// so 8 MiB of bytes fits the 16 MiB bridge frame with the JSON envelope. +pub const DOCUMENT_LIMIT: u64 = 8 * 1024 * 1024; +pub const PAGE_LIMIT: u32 = 64 * 1024; +pub const CHUNK_LIMIT: u32 = 8 * 1024 * 1024; +pub const IMPORT_LIMIT: u64 = 8 * 1024 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub struct Bytes(#[serde(with = "base64_bytes")] pub Vec); // a small local serde module; crosses as base64 text + +#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Permissions { + #[default] + Preserve, + Private, + PrivateReadOnly, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReadReply { + pub data: Bytes, + pub eof: bool, + pub size: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum StatKind { + File, + Directory, + Other, + Missing, +} + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Stat { + pub kind: StatKind, + #[serde(skip_serializing_if = "Option::is_none")] + pub size: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ClaimReply { + pub claim_id: String, +} + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UpdateReply { + pub applied: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Entry { + pub name: Name, + pub kind: EntryKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum EntryKind { + File, + Directory, + Other, +} + +/// A listed name is passed back unchanged: a string, or the native bytes. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum Name { + Text(String), + Unix { #[serde(rename = "Unix")] unix: Vec }, + Windows { #[serde(rename = "Windows")] windows: Vec }, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum RemoveTarget { + Path { path: String }, + Entry { parent: String, name: Name }, +} + +/// The caller's own refusal or failure from a source or a change, carried unchanged. +#[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[error("{reason}: {message}")] +pub struct Rejected { + pub reason: String, + pub message: String, +} + +impl Rejected { + pub fn new(reason: &str, message: &str) -> Self { + Self { reason: reason.to_owned(), message: message.to_owned() } + } +} + +/// A failed callback arrives as the wire's error; its own code becomes `reason`. +impl From for Rejected { + fn from(error: rutis::host::CallError) -> Self { + let (message, raw) = error.into_raw(); + let reason = raw + .and_then(|raw| raw.downcast::().ok()) + .and_then(|error| error.code().map(str::to_owned)) + .unwrap_or_else(|| "failed".to_owned()); + Self { reason, message } + } +} + +/// The next chunk of a write, or none at the end. +pub type SourceFn = + Arc BoxFuture<'static, Result, Rejected>> + Send + Sync>; + +/// The current content (none when absent); the next content, no write, or a refusal. +pub type ChangeFn = + Arc) -> BoxFuture<'static, Result, Rejected>> + Send + Sync>; + +#[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum FileError { + #[error("{message}")] + Invalid { + message: String, + #[serde(skip_serializing_if = "Option::is_none")] + path: Option, + }, + #[error("{message}")] + MissingParent { message: String, path: String }, + #[error("{message}")] + TooLarge { message: String, path: String, size: u64 }, + #[error("{reason}: {message}")] + Rejected { reason: String, message: String }, + #[error("{message}")] + Io { + message: String, + #[serde(skip_serializing_if = "Option::is_none")] + path: Option, + }, + #[error("{message}")] + Unsynced { message: String, path: String }, + #[error("{message}")] + Cancelled { message: String }, + #[error("{message}")] + Closed { message: String }, +} + +impl PublicService for FileStorage {} + +#[rutis::service(name = "fsHost")] +impl FileStorage { + pub async fn add_root(&self, path: String, cancelled: CancelledFn) -> Result { + // ... + } + + pub fn root_path(&self, root: String) -> Result { + // ... + } + + pub async fn stat(&self, path: String, cancelled: CancelledFn) -> Result { + // ... + } + + pub async fn read( + &self, + path: String, + offset: Option, + length: Option, + cancelled: CancelledFn, + ) -> Result, FileError> { + // ... + } + + pub async fn claim( + &self, + caller: &Ctx, + path: String, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn release(&self, caller: &Ctx, claim_id: String) -> Result<(), FileError> { + // ... + } + + pub async fn write( + &self, + path: String, + source: SourceFn, + permissions: Option, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn import( + &self, + path: String, + source: String, + max_bytes: Option, + permissions: Option, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn update( + &self, + caller: &Ctx, + path: String, + change: ChangeFn, + claim_id: Option, + permissions: Option, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn create_directory( + &self, + path: String, + cancelled: CancelledFn, + ) -> Result { + // ... + } + + pub async fn list( + &self, + path: String, + cancelled: CancelledFn, + ) -> Result>, FileError> { + // ... + } + + pub async fn remove(&self, target: RemoveTarget, cancelled: CancelledFn) -> Result<(), FileError> { + // ... + } +} +``` + +`CancelledFn` is the crate's existing cancellation argument ([`host::CancelledFn`](../../../../crates/dim-agent-capabilities/src/host.rs)). `Bytes` crosses as base64 text; `Name` as a string or the native `{Unix: …}`/`{Windows: …}` object; root ids and sizes as strings and numbers. `claim`, `release` and a claim-carrying `update` take `caller: &Ctx` because the claim is bound to the calling row; the dispatch fills it, and it is not a request field. Requests carry callbacks by reference only where the operation needs the caller's own step — the write source and the update change — plus the cancellation argument; every other argument and reply is data. + +## Current implementation + +The code at this head still exposes the lease surface that the contract above replaces. Where the two differ, the contract is authoritative and the delivery part on [#2016](https://github.com/arcships/dim/issues/2016) is the migration. The sections below record the behaviour that is not part of the contract: traversal, the account marker's wire format, creation, listing, removal and their tests. + +### Events and lifetime No Timeline events. Each `apply` opens fresh root-directory handles; blocking operations and leases are tracked by that generation. Close stops admission, @@ -26,61 +588,11 @@ opens leave `OBJECT_ATTRIBUTES.Attributes` at 0 so the actual directory's case-sensitivity setting governs lookup; forcing `OBJ_CASE_INSENSITIVE` or folding names would break case-sensitive directories and their aliases. -## Bounded reads - -`read_limited(path, limit, cancel)` preserves the same authorized-handle traversal and cancellation as `read`. It checks the opened file's length before allocating contents, then checks each chunk before extending the buffer to cover concurrent growth. Exceeding the byte limit returns `Io(InvalidData)` without partial bytes or a write. The lease's own `read_limited(limit, cancel)` applies the same rule under the held lock; `read` is its unbounded case. The business caller chooses its byte limit. - -## Filesystem data face - -`fsHost.createDirectory`, `list` and `remove` resolve absolute paths in the owner's -authorized roots. They use the directory creation, listing and removal contracts above. -Pass a listed name unchanged to `remove({parent, name})`. A Unicode name is a string. Other names carry the original Unix bytes (`{Unix: number[]}`) or Windows UTF-16 code units (`{Windows: number[]}`). The owner accepts a single component below the listed directory. - -`fsHost.stat({path})` returns the entry kind and the size of a regular file, without following links. An absent entry has kind `missing`. - -`fsHost.readBytes({path, limit, leaseId?})` returns base64 bytes and the length. A file over the limit fails with `too_large`. Hooks reads the authorized project settings path through this operation. `lock({path})` returns a lease ID for reads of that same file. `replace({path, bytes, permissions?, leaseId?})` accepts base64 bytes and atomically replaces the target under the supplied lease or a new lock. `backup({leaseId, suffix, permissions?})` creates an exclusive sibling copy under the same lease. Explicit `unlock({leaseId})` or caller unload releases the lease. - -### Pinned reads +### The lease surface the contract replaces -The process `fsHost` name provides the pinned-reader operations from -[resource faces §4.1](../../../design/resource-faces.md#41-methods), using this -same FileStorage generation and reader registry. `openRead` resolves the supplied -absolute path through the existing authorized-root traversal and pins that exact -file. Replacing the path afterwards does not change the reader's bytes. +The code's `FileLease`, `read_limited`, `open_read`/`readAt`/`closeRead`, `resolve`, `register_root`, `root_path`, `replace`, `backup`, `import` with the old `PathBuf` source and required `limit`, `create_directories` and the `FsHost` wrapper are the surface the contract's `read`, `write`, `update`, `claim`, `release`, `add_root`, `root_path`, `import` and `create_directory` replace. Their tests below stay until the migration lands. -The wire `openRead` operation requires a calling row to own retention; `readAt` -and `closeRead` require only the reader id. These are trusted-plugin operations: -an id identifies a reader, not caller authorization, and a plugin that receives -another row's id can read or close it. Readers opened through native -`FileStorage::open_read` have no caller retention to release through this face; attempting to close such an id returns `invalid` -without unregistering it. - -`readAt` keeps the existing maximum of 64 KiB and independent offsets. Zero limit -or an offset at/past the pinned length returns empty bytes. The wire encodes bytes -as base64; the native binding reads the same reader id directly. Unknown, closed -or prior-generation ids are `invalid`; unavailable storage is `node_unavailable`, -a missing file is `not_found`, cancellation is `cancelled`, and other existing -I/O failures are `io`. No extra read or normalization follows the owner's result. - -The calling row retains an opened reader until `closeRead` or that row's unload; -registration finishes before `openRead` returns. Close removes the id before -releasing retention, while reads already accepted finish under the owner's -existing operation tracking. Dropping close before it is polled does nothing; -once close removes the id, the existing context cleanup continues even if its -wait is dropped. FileStorage close drains those operations and -releases the same pinned handles, including readers retained by a caller. There -is one reader registry and no separate connection table or read queue. - -In the Rust binding, `FsHost::open_read` takes the calling part's `&Ctx` and -cancellation token along with the path. The context supplies the same cleanup -registration that the wire binding obtains from its calling row; it is not a -request field. Both return only `OpenRead {read_id, size}`. The public `FsHost` -binding has these three operations, no owner dereference or native file handle; -its methods directly return the existing owner's operation futures. Native -FileStorage readers outside this face retain their original weak-registry/RAII -lifetime while sharing the same generation's shutdown. - -## Leases and lock keys +### Lock keys A lease locks a key file with the target's name in the reserved `.dim-file-storage-locks` directory beside the target, so the filesystem's own @@ -126,9 +638,8 @@ A reused PID, a permission-denied process probe or a missing PID or creation time does not establish ownership. The exception is a marker this process failed to release: it keeps the owner record, whose nonce only that marker carries, and reclaims the marker at once, so removal and locking need -not wait for the process to exit. The marker is the external TypeScript wire -format: PID, milliseconds since the Unix epoch (`Date.now()` in TypeScript), -nonce and a trailing newline, with no other fields. Writers must use +not wait for the process to exit. The marker is the published marker format: PID, milliseconds since the Unix +epoch, nonce and a trailing newline, with no other fields. Writers must use milliseconds, not seconds. The start-time comparison on macOS, Linux, Android and Windows assumes wall-clock @@ -140,7 +651,9 @@ On Windows, releasing a `PhysicalLock` unlocks its byte range explicitly before release completes, because `CloseHandle` may defer the implicit unlock; a later generation would otherwise see a stale `Locked` lock. -## Directory creation +### Directory creation + +The contract's `create_directory` makes the whole path an existing tree; the code below creates one level per call and `create_directories` composes the levels. `create_directory` makes a path below an authorized root an existing business directory, one level at a time: its parent must exist and is reached as every @@ -183,7 +696,9 @@ fails `InvalidPath` and is left untouched, and so does an alias of a reserved resource; the returned path therefore names the result without a followed link. This is the primitive for handing a work directory to a helper process. -## Listing and removal +### Listing and removal + +The contract's `remove` waits for a held key; the code below answers `Locked`. `list` returns the entries of a directory below an authorized root, sorted by name, each a `File`, `Directory` or `Other` (a link, reparse point or special @@ -311,7 +826,7 @@ removal of its directory therefore resolves its key again or returns another removal of the same tree treats what the other deleted as removed, and starts again from its target if a directory it returns to was deleted. -## Tests +### Tests [file_storage_flow.rs](../../../../crates/dim-agent-capabilities/tests/file_storage_flow.rs): `late_roots_preserve_indices_and_generation_boundaries_on_reload`, @@ -343,27 +858,3 @@ public API cannot produce reliably. | 提供 | `P:FileStorage`、`P:FsHost`、`P:dyn HostDispatch#fsHost` | | 被注入于 | `HostPlatform` | - -## Native streaming reads - -`resolve(absolute)` identifies an existing authorized root without adding one; -paths use the root's canonical spelling. `open_read(path, cancel)` traverses held -directory handles and pins a regular file. Its `FileReader` reports the length -at open and reads at explicit offsets, at most 64 KiB per call. Concurrent reads -serialize access to the pinned descriptor; replacing a pathname does not change -an existing reader. The producer keeps published files unchanged in place. - -Readers belong to the storage generation. Closing refuses new work, drains -accepted reads and closes retained descriptors. Caller cancellation is checked -before and after each bounded read. This native interface does not export binary -callbacks through the language bridge. UiResources uses it for the protected -resource routes in the [client UI contract](../../../design/client-ui-extensions.md). - -## Path import - -`import(path, source, limit, permissions, cancel)` copies an authorized absolute -source file into the authorized destination using `replace_from`. It opens and -pins the source, requires a regular file within the caller's limit, and rejects -length changes during copying. On Unix the open is nonblocking and rejects a -terminal symlink. The destination follows the existing lease, atomic replacement, -permissions and cancellation contract. The operation returns the copied byte count. diff --git a/docs/architecture/rust-agent/plugins/Hooks.md b/docs/architecture/rust-agent/plugins/Hooks.md index e147caa8c6..015efc23db 100644 --- a/docs/architecture/rust-agent/plugins/Hooks.md +++ b/docs/architecture/rust-agent/plugins/Hooks.md @@ -45,7 +45,7 @@ The runtime reads sources when a hook point is evaluated, never at Session start: a change to the user's `hooks.json` or to a project document applies to the next hook point, and the catalog is recomputed rather than cached. Reading is a `S:HookSourcesHost` call, which the App Server binds to Settings and -`fsHost.readBytes`; a Session whose host binds no sources (the scripted model +FileStorage's `read`; a Session whose host binds no sources (the scripted model assembly) sees an empty catalog. `DIMCODE_HOME` comes from the same port, so a Session started by a product daemon passes the daemon's product home into every hook command and a Session without one sets nothing. diff --git a/docs/architecture/rust-agent/plugins/HostPlatform.md b/docs/architecture/rust-agent/plugins/HostPlatform.md index e2dadab46a..b4d86a8977 100644 --- a/docs/architecture/rust-agent/plugins/HostPlatform.md +++ b/docs/architecture/rust-agent/plugins/HostPlatform.md @@ -67,7 +67,7 @@ the directory (ADR 013 D4). An absent directory counts as removed. detected shell choices, returning the byte revision, optional explicit executable and any parse error. `update_exec_shell_settings(expected_revision, executable_path, cancel)` validates the selection with the same resolver used by execution, then -replaces the preference atomically under a FileStorage lease if its byte revision +replaces the preference atomically with FileStorage's `update` if its byte revision still matches. An absent executable selects automatic detection; a malformed preference can be repaired using its current revision. Missing files have revision `absent`. App Server exposes these operations as trusted local management methods diff --git a/docs/architecture/rust-agent/plugins/README.md b/docs/architecture/rust-agent/plugins/README.md index 1fd80891c6..3f275a7da9 100644 --- a/docs/architecture/rust-agent/plugins/README.md +++ b/docs/architecture/rust-agent/plugins/README.md @@ -45,7 +45,7 @@ dependency is not necessarily a plugin with the same name. | [Loop](Loop.md) | — | [LoopMethods](LoopMethods.md) | Loop | | [ModelProvider](ModelProvider.md) | — | — | ModelProvider | | [HostPlatform](HostPlatform.md) | HostPlatform | — | — | -| [FileStorage](FileStorage.md) | FileStorage | — | — | +| [FileStorage](FileStorage.md) (owner contract) | FileStorage | — | — | | [Hooks](Hooks.md) | — | HooksSession, HookSources (App Server) | HooksBranch | App Server optional plugins are outside this local-execution profile. [Web](../../../design/plugins/Web.md) provides `web_search` and `web_fetch` through a Session part its `web` process row registers; it adds no service to the assembly recorded here. diff --git a/docs/design/appserver/mcp-oauth.md b/docs/design/appserver/mcp-oauth.md index 42e226f36b..8910a8d933 100644 --- a/docs/design/appserver/mcp-oauth.md +++ b/docs/design/appserver/mcp-oauth.md @@ -36,7 +36,7 @@ flow, and the gaps rmcp leaves, three of them MUSTs of the specification (Append | [rmcp pin](../../../crates/dim-app-server/Cargo.toml), feature `auth` (`src/transport/auth.rs`) | The `auth` module covers metadata discovery, DCR and CIMD client selection, PKCE and `state`, code exchange with `resource` and `iss`, and refresh with rotation. The `CredentialStore` and `StateStore` traits are pluggable. It shares the reqwest 0.13 already used by the transport | The protocol engine; gaps in Appendix A | | Claude Code (`/mcp`, `claude mcp login`, [docs](https://code.claude.com/docs/en/mcp)) | The `oauth` object in `.mcp.json`: `clientId`, `callbackPort`, `authServerMetadataUrl`, `scopes`. Redirect `http://localhost:PORT/callback`; a switch to `127.0.0.1` broke servers that match the registered URI exactly and was reverted. Paste the callback URL when the redirect fails. The client secret is kept out of config. Refresh, then retry once, on `401` | The `oauth` field names and types, the redirect form, the paste fallback, the secret outside config | | MCP TypeScript and Python SDKs (`OAuthClientProvider`, `TokenStorage`) | Storage and redirect handling are injected by the host. Credentials carry an issuer stamp and are discarded on mismatch. `invalid_client` clears the registration and `invalid_grant` clears the tokens | Owner-supplied storage, issuer binding, clearing rules | -| Dim account login (`account.login.browser.begin/complete`, `managed_oauth.rs`, `dim-cli/src/login.rs`) | The daemon returns `{attemptId, authorizationUrl, expiresAt}`. The client sends back the pasted callback URL, read with hidden input. Tokens live in `auth.json` under the home root, through a FileStorage lease with atomic 0600 replace | The attempt shape, paste input, the storage pattern | +| Dim account login (`account.login.browser.begin/complete`, `managed_oauth.rs`, `dim-cli/src/login.rs`) | The daemon returns `{attemptId, authorizationUrl, expiresAt}`. The client sends back the pasted callback URL, read with hidden input. Tokens live in `auth.json` under the home root, through FileStorage's `claim`/`update` with atomic 0600 replace | The attempt shape, paste input, the storage pattern | ## 3. Structure diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index adad6399f9..497b6be2fc 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -122,7 +122,7 @@ are Rust methods over the native store, not services: only Agents calls them. `SessionHold`, a Scheduler run through the `sessions` service takes a lease) or appends after the close, which the branch refuses. 2. **Close.** If S is loaded, Agents closes it as `session.close` does: a business close, not an unload. Its - capabilities settle their accepted work, write their terminal facts and release processes, FileStorage leases and + capabilities settle their accepted work, write their terminal facts and release processes, FileStorage's keys and claims, and member requests. A close that reports cleanup errors is logged and the delete continues: the facts it could not write are removed with the rest. From the close on, S's slot is closed: S does not load again in this process, whether or not its rows go (step 6). @@ -675,7 +675,7 @@ None to rutis. To the event format: the event kind `session/forked` (§13, rule | To | Requirement | Status | | --- | --- | --- | -| FileStorage | `remove` syncs the parent of the removed entry before it reports success, also when the entry was already absent, and returns `Unsynced` when that sync fails. Windows has no directory sync and relies on NTFS metadata journaling, as for `replace`. Needed so a delete's removal is durable before its commit (§4) | Implemented in S5c ([FileStorage](../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal)) | +| FileStorage | This row is superseded by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal). | Implemented in S5c | | Loop, InputQueue, BackgroundExec | A read-only rest-point check at a fixed cut: no open turn, no Queue or Steer input waiting to drive a turn, every background task ended with its wake posted (§6.2). A capability whose reload rule comes to start work from other facts adds them to the check, so a fork keeps starting nothing | Agents queries these capabilities' public facts through the Timeline face (§16 D1). Their owners extend the check in [agents/fork.rs](../../../crates/dim-app-server/src/agents/fork.rs) when a reload rule comes to start work from other facts. BackgroundExec owns the shared wake predicate, including generation boundaries | | Collaboration | When a branch rebuilds, a delivered request without a result is settled as failed without stopping its member unless the member's relation names this Session as its leader. In general, reload settlement acts only on resources its own Session holds. The rebuild stopped any loaded Session named in the fact ([collaboration.rs](../../../crates/dim-app-server/src/collaboration.rs) `rebuild`), so a fork of a leader would have stopped the source's member | Implemented ([#127](https://github.com/arcships/dim/issues/127)). Before #127 that reload stopped such a member if it was loaded. Now the member keeps whatever its own reload rules start, the leader has already settled the request as failed, and the member's `agent` messages to a fork of the leader are refused (`TeamMemberNotFound`) because no relation names the fork ([#97 review](https://github.com/arcships/dim/pull/97)). A restart keeps the Team: relations are rebuilt from the stored leaders ([Collaboration §6](../plugins/Collaboration.md#6-delegation-ownership-and-lifetime)). Acceptance 7 | | Goal (P5, [#69](https://github.com/arcships/dim/issues/69)) | A copied goal must not drive a turn in F or be F's goal. The fork writes `session/forked` after the copied facts in its transaction (§6.5); Goal folds `main` from after that fact and clears a copied live goal once ([Goal](../plugins/Goal.md) A11) | Implemented with Goal's acceptance ([#209](https://github.com/arcships/dim/pull/209)) | diff --git a/docs/design/appserver/session-files.md b/docs/design/appserver/session-files.md index 38532937c9..b3345da58b 100644 --- a/docs/design/appserver/session-files.md +++ b/docs/design/appserver/session-files.md @@ -20,7 +20,7 @@ history quotes it and history never changes. rows instead of copying bytes. Deleting a Session removes its rows. - **Removal.** A background sweep removes files whose last owner row is gone, and anything in the directory that no row records. -- **FileStorage.** S5a adds one operation, `create_directory`. Sharing needs no link operation. +- **FileStorage.** This section is superseded by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md). Sharing needs no link operation. - **Format.** The native store moves to version 15, with two new tables. A v13 store is upgraded in place at startup. - **Interface.** Attachments reaches the store through the process service `sessionFiles`. @@ -46,7 +46,7 @@ No Timeline event, no new plugin, no change to the runtime, rutis or the Session +------------------------------------------------|-------------------------+ v Resource node (P1/P2: the control node) FileStorage: create_directory, - replace, list, remove + write, import, list, remove Session scope Attachments (Deps: SessionIdentity, sessionFiles) -- put(own sessionId, name, text) ``` @@ -183,7 +183,7 @@ Rejected alternatives: | | (file_id, node, writer = G) ->| | | | create_directory() ------------------------------------->| parent synced | | create_directory(/) -------------------------------->| parent synced - | | replace(//, content, read-only) -------------->| file and parent synced + | | write(//, content, read-only) ---------------->| file and parent synced | | cancelled? -> abandon | | | | txn 2: S exists, row still G? | | | | insert owner (S, id); | | @@ -192,7 +192,7 @@ Rejected alternatives: ``` The reply is sent only after the file and its directory entries are synced and txn 2 has -committed (`synchronous=FULL`). Windows has no directory sync. As for `replace`, durability +committed (`synchronous=FULL`). Windows has no directory sync. As for `write`, durability there rests on the file sync and NTFS metadata journaling. **Abandon.** Txn 1 is followed by a failure, a cancellation (checked right before txn 2), or @@ -247,7 +247,7 @@ also removes the Session's command output on the node first 2 remove: for each row on node N with writer IS NULL and no owner: FileStorage(N).remove(/) absent counts as removed ok -> txn: delete the row if it is still unowned - Locked, I/O error -> keep the row, record a diagnostic; the next sweep retries + cancelled, unsynced, io -> keep the row, record a diagnostic; the next sweep retries node unavailable -> stop; the next sweep retries 3 list: FileStorage(N).list(), then read the rows for those names every entry with no row -> FileStorage(N).remove(/) @@ -275,11 +275,11 @@ safe because FileStorage removal can be retried. ## 6. Deletion, crash recovery and serialization -**Order against Session close and leases.** S5c closes the Session first, then commits its -delete transaction, then SessionStore sweeps. No FileStorage lease outlives a put: `replace` -holds its lease only while it writes. The sweep never removes a pending file of the live -generation. A deletion therefore never meets `Locked` or `DirectoryNotEmpty` because of a put. -If it meets them because of something outside SessionStore, the row stays and the next sweep +**Order against Session close and keys.** S5c closes the Session first, then commits its +delete transaction, then SessionStore sweeps. No FileStorage key outlives a put: `write` +holds its key only while it writes. The sweep never removes a pending file of the live +generation. A deletion therefore never waits on a key or meets a non-empty directory because of a +put. If it does because of something outside SessionStore, the row stays and the next sweep retries. **Serializing put against delete and fork.** All three decide at a write transaction of the one @@ -309,30 +309,7 @@ creates the fork. SQLite orders those transactions, so no in-memory lock is need ## 7. FileStorage additions -**`create_directory` is the only addition.** Sharing is by rows (§4), so FileStorage needs no -link or reference-count operation. Removal, listing and durable writes already exist: S6's -`remove` and `list`, and `replace` with its permissions parameter. The S6 review agreed to add -`create_directory` in S5a. - -`create_directory(path, cancel) -> ()`: makes `path`, below an authorized root, an existing -business directory. - -| Rule | Content | -| --- | --- | -| Parent | Every component but the last is opened as `open_directory` opens it: an existing directory reached without following links, never the reserved directory. A missing parent fails `Io` `NotFound`; there is no recursive creation, and callers create each level in order | -| Reserved names | `path` already rejects the reserved prefix `.dim-file-storage-` and `auth.json.lock` by name (`InvalidPath`) | -| Aliases | Aliases are checked the way `lock` checks them, before anything is created. The parent's reserved directory is ensured first, so any spelling the filesystem equates with it already exists. Then the key for `auth.json.lock` is ensured in that reserved directory and the key for the last component is opened if it exists; if they are the same file, the name is an alias of the account marker and the call fails `InvalidPath` | -| Create | An absent last component is created relative to the held parent handle: Unix `mkdirat` with mode `0700`; Windows `NtCreateFile` with `FILE_CREATE` and `FILE_DIRECTORY_FILE`, inheriting the parent's DACL | -| Present | An existing directory is opened as `open_directory` opens it, so an alias of the reserved directory fails `InvalidPath`. An existing business directory counts as created, just as S6's `remove` counts an absent entry as removed. Any other existing entry (file, link, reparse point, special file) fails `Io` and is left untouched; links are never followed | -| Durability | In both the created and the present case the parent is synced before the call returns, so a retry after `Unsynced` confirms durability. A sync failure returns `Unsynced` (the directory exists and is visible, durability unconfirmed); its message is generalized from "file replaced" to cover directories. Windows has no directory sync, as for `replace` | -| Roots | A root itself cannot be named: `path` requires a relative name | -| Cancellation | Checked up to the creation, which is the commit boundary. Once created, the sync result is reported | -| Errors | `InvalidPath`, `Io` (`NotFound` parent, an existing non-directory entry, other I/O), `Unsynced`, `Closed`, `Cancelled`, `Worker` | - -The alias check never creates a key for the new directory's name, so a put leaves no key behind -in `.session-files/.dim-file-storage-locks`, which is never removed (Design changes, D1). The -operation lives inside FileStorage's own module, beside `list` and `remove`, and holds the same -generation admission. FileStorage's plugin page documents it. +This section is superseded by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md). ## 8. Storage format @@ -477,14 +454,14 @@ Limits, and who owns them: | Limit | Owner | Reason | | --- | --- | --- | -| One file at most 16 MiB | SessionStore | A put is one message, and `replace` holds the content in memory; the bound caps one call's memory | -| `name`: `[A-Za-z0-9._-]{1,64}`, no leading dot, not `auth.json` or `auth.json.lock` in any letter case, and accepted by the node's FileStorage as one path component (Windows device names) | SessionStore | The name becomes a path component under SessionStore's directory. `auth.json` would switch `replace` to FileStorage's account-marker protocol | +| One file at most 16 MiB | SessionStore | A put is one message, and FileStorage streams its bytes; the bound caps one call's memory | +| `name`: `[A-Za-z0-9._-]{1,64}`, no leading dot, not `auth.json` or `auth.json.lock` in any letter case, and accepted by the node's FileStorage as one path component (Windows device names) | SessionStore | The name becomes a path component under SessionStore's directory. `auth.json` would switch `write` to FileStorage's account-marker protocol | | Content rules (non-empty text, 10 MiB, default `paste.txt`) | Each consumer (Attachments A.2) | Business rules of the feature | | No per-Session count or total quota | None | Disk use ends with Session deletion and cleanup (S5c); a quota would need a business owner, and none exists | **Immutability.** A path names the same bytes for the file's whole life, which ends only when the sweep removes an unowned file. The file is written once, read-only: Unix mode `0400`, -Windows read-only attribute, through `replace`'s permissions parameter. WorkspaceTools' `write` +Windows read-only attribute, through `write`'s permissions parameter. WorkspaceTools' `write` and `edit` therefore fail with `permission_denied`: their commit step opens the target for writing, and on Windows also checks the read-only attribute, before replacing it. This is a guard, not isolation. A daemon running as root on Unix is not stopped by the mode, a shell @@ -639,7 +616,7 @@ Rejected alternatives: | FileStorage reloads during a put | `node_unavailable` or `storage`; abandoned and swept | SessionStore | | SessionStore reloads during a put | Cancelled before txn 2 (abandoned), or already committed; Attachments reloads with it | SessionStore unload | | Process restart | Leftovers are swept on the first put or after the next delete | Sweep | -| Something outside SessionStore writes into the Session-files directory | A top-level entry is removed by step 3 of the sweep; an entry inside a file's directory goes with that directory when the file is unowned. `Locked` leaves it for the next sweep | FileStorage, sweep | +| Something outside SessionStore writes into the Session-files directory | A top-level entry is removed by step 3 of the sweep; an entry inside a file's directory goes with that directory when the file is unowned. A `cancelled`, `unsynced` or `io` removal leaves it for the next sweep | FileStorage, sweep | | `read` after the last owner is deleted | File not found; no surviving Session quotes the path | — | ## 13. Changes to other documents @@ -705,8 +682,8 @@ None to the runtime or rutis. Supplements and requirements to other owners: schema with every business row unchanged, then reopens as v15. The upgrading open reports the upgrade, which the §8 log line comes from; the reopen does not. The branch-only v14 and unknown schemas are refused and preserved. -8. FileStorage flow: `create_directory` creates `0700` and syncs the parent; an existing - directory succeeds; a missing parent fails `NotFound`. Reserved names, a case alias of the +8. FileStorage flow: `create_directory` creates the tree with `0700` and syncs the parent; an existing + directory succeeds; a link at any level fails `invalid`. Reserved names, a case alias of the reserved directory, and a case alias of `auth.json.lock` (on a case-insensitive filesystem) fail `InvalidPath` and create nothing. An existing file or link is refused and untouched. Cancellation before creation creates nothing. @@ -737,7 +714,7 @@ only S5a. | # | Change | Why | | --- | --- | --- | -| D1 | `create_directory` ensures the key for `auth.json.lock` and only opens the key for the new name, instead of opening both keys with creation (§7) | Opening a key with creation leaves a key file named after the directory, and FileStorage unlinks keys only when it removes their parent. `.session-files` is never removed, so every put would have left one key there for good. An existing alias of the marker still resolves to the marker's key, so the check gives the same answer | +| D1 | The account marker's key handling is defined by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md); `create_directory` creates no key for the new name (§7) | A key file named after a directory that is never removed would stay for good. The contract's marker and private key keep the same alias check without leaving a key for the directory name | | D2 | Before P3, a put reads no resource node. The Session's existence is decided by txn 1, after the FileStorage lookup, so an unknown Session gets `node_unavailable` while FileStorage is not active (§5.1) | `SessionConfig.resourceNode` does not exist yet, so a read before txn 1 would only repeat txn 1's check. P3 adds the node read before the lookup | | D3 | Every put schedules a sweep until one sweep of the generation has completed on its node, instead of only the first put (§5.4) | A first sweep stopped by an unavailable node would otherwise wait for an abandon or a release to retry; a completed sweep ends the extra requests | @@ -781,8 +758,8 @@ FileStorage: ```rust impl FileStorage { - pub async fn create_directory(self: &Arc, path: &FilePath, cancel: &CancellationToken) - -> Result<()>; + pub async fn create_directory(&self, path: String, cancelled: CancelledFn) + -> Result; } ``` diff --git a/docs/design/client-ui-extensions.md b/docs/design/client-ui-extensions.md index 69de4c7b52..0a26004e53 100644 --- a/docs/design/client-ui-extensions.md +++ b/docs/design/client-ui-extensions.md @@ -194,7 +194,7 @@ UiResources 提供通用的**已完成文件发布**:受信任的后端 Sessio - 发布只接受 App Server 所在文件系统可读的有限长度普通文件,不接受目录、设备、socket 或网络 URL。远端浏览器不需要访问该文件系统;不共享文件系统的后端执行节点不是首期文件发布来源。 - 发布参数 `path` 是 App Server 文件系统上的 canonical 绝对路径,且须位于 FileStorage 的既有授权根内。相对路径以 `invalid_params` 拒绝;绝对路径没有匹配的授权根、越界或指向链接时以 `resource_unavailable` 拒绝。UiResources 在可信后端发布边界解析到根相对路径,不因 UI 请求扩大授权。所需的原生文件读取能力见 R5。 - 发布调用是后端命名服务,不是浏览器 Session RPC。浏览器没有“路径换 URL”、任意文件读取、上传或 URL 代理方法。业务 owner 在自己的外部输入边界决定哪些文件可以发布,不能直接把客户端传来的路径当成发布许可。 -- 生产者必须在文件完成后发布,并保证发布期间字节不变。UiResources 打开文件,记录长度和 MIME,持有读取资源;它不复制业务缓存、不接管下载或转码。替换内容要发布新引用,不能修改已发布文件。 +- 生产者必须在文件完成后发布,并保证发布期间字节不变。UiResources 按路径分页读取文件,记录长度和 MIME,不持有读取资源;它不复制业务缓存、不接管下载或转码。替换内容要发布新引用,不能修改已发布文件。 - 引用绑定 Session、发布者的本次注册与资源 ID。它不是 bearer 凭据,也不是持久业务 ID。一个资源可被同一 Session 的多个面板读取;每个客户端仍需通过服务入口和 Session 访问授权。 - 注册属于发布者的生命周期;显式撤下、发布者卸载和 Session closing 都停止准入,取消在途读取并等待文件句柄释放。撤下完成后,生产者才可删除缓存文件。Session 未发布前不接受读取。 - UI 关闭只取消自己的读取,不撤下别的面板仍可能使用的资源。资源过期后由业务方法显式取得新引用,不自动下载或重放具有副作用的操作。 @@ -209,7 +209,7 @@ UiResources 提供通用的**已完成文件发布**:受信任的后端 Sessio Rust 和 TypeScript Session part 均可使用此服务。路径由已持有文件位置的业务 owner 提供,例如后端插件使用 Node 文件 I/O 在已授权工作目录生成文件,或由现有业务服务返回绝对路径。`pluginFiles` 只提供相对文本文件接口,不提供绝对路径,因此它的相对路径不能直接传给发布服务,也不能通过猜测产品 home 拼接。 -[sessionFiles](appserver/session-files.md) 负责持久化不可变文件及 Session 所有权记录、fork 和删除;UiResources 只持有已有文件的临时展示引用与读取句柄,不写入该存储、不复制文件、不增加持久化所有权行。关闭展示引用不等于删除 Session 文件,故不把传输生命周期加入 sessionFiles。 +[sessionFiles](appserver/session-files.md) 负责持久化不可变文件及 Session 所有权记录、fork 和删除;UiResources 只持有已有文件的临时展示引用,读取按路径分页进行,不写入该存储、不复制文件、不增加持久化所有权行。关闭展示引用不等于删除 Session 文件,故不把传输生命周期加入 sessionFiles。 此服务不复用文本型 [pluginFiles](process-typescript.md#52-public-pluginfiles-binding) 的编码或事务格式。图片生成、网络抓取、媒体解密、转码与缓存策略属于发布资源的业务插件。 @@ -284,10 +284,10 @@ Rust 和 TypeScript Session part 均可使用此服务。路径由已持有文 ### R5. FileStorage:受授权根约束的原生只读流 -- **阻塞与规则:** §3.2 和 §6 需要有界复制与按字节区间读取;[FileStorage](../architecture/rust-agent/plugins/FileStorage.md) 的整块读取/限长读取不提供随传输背压拉取的文件句柄。 +- **阻塞与规则:** §3.2 和 §6 需要有界复制与按字节区间读取;[FileStorage](../architecture/rust-agent/plugins/FileStorage.md) 的按路径偏移读满足分页(`read` 的 offset/length),不提供文件句柄或背压流;撤下与在途页竞争时只返回整页或 `resource_gone`。 - **考虑的机制:** 整块读取使内存随媒体大小增长;在 UI owner 中重写根约束和安全打开逻辑会复制文件边界;文本事务不能表达二进制流。 -- **所需通用能力:** FileStorage 接受已有授权根内的路径,返回只读文件长度和可定位读取资源;保留原有防越界打开、取消、generation 准入与收尾保证,不由读取请求扩大根授权。每个消费者有独立读取位置;读取资源随使用者释放,存储关闭等待其结束。这是 Rust 原生 I/O 能力,不把文件句柄或逐块字节回调导出给 TypeScript。 -- **时序影响:** 取得读取资源时固定文件对象;取消或 owner 关闭停止读取并释放。无 Timeline、格式或写事务变更。 +- **所需通用能力:** FileStorage 的 `stat` 返回只读文件长度,`read(path, offset, length)` 由调用方自己携带偏移分页读取;保留原有防越界打开、取消、generation 准入与收尾保证,不由读取请求扩大根授权。没有读取资源或文件句柄跨出所有者。 +- **时序影响:** UiResources 保证已发布路径在撤下前不被改写,因此同一引用的分页来自同一版本;取消或 owner 关闭停止读取。无 Timeline、格式或写事务变更。 - **Owner / issue:** FileStorage,[#1136](https://github.com/arcships/dim/issues/1136);实现与根约束、关闭流程验证在 FileStorage 内完成。 ## 9. 实施顺序与波及面 diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index ce4052095c..a8b1263371 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -8,23 +8,22 @@ directly. The rutis binding dispatches its data arguments and returns its result | Dependency | Caller and contract | | --- | --- | | `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. | +| `fileStorage`, `mentionIndex` | This row is superseded by the [FileStorage contract](../../architecture/rust-agent/plugins/FileStorage.md). File tools and workspace completion keep the tool family under [#1297](https://github.com/arcships/dim/issues/1297). | | `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). | -| `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. | +| `pluginFiles` | This row is superseded by the [PluginFiles contract](../plugins/PluginFiles.md). | | `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. | +| 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, the file-tools face's resolution and FileStorage's reads. | ## Additional public bindings | Target and signature | Existing operation and consumer | | --- | --- | | FileScope.directory(name) → FileResult of node-absolute path | The file scope validates the scoped name, creates parents and returns the directory. Modality passes the node-local input filenames and work directory directly to its native adapter. OCR uses its current work/tmp/cache paths and grants. Existing exports use the recorded result filename. | -| FileScope.openRead(name) → FileResult of {readId,size} or null | The file scope opens a pinned file by relative name and returns None if missing. Bind that reader to the existing fsHost reader identity for the caller on the same node. Use fsHost.readAt/closeRead and the existing caller-unload cleanup. A scoped name never requires a caller-side root lookup. | -| FileScope.writeStream(name, next) → FileResult of null | The file scope consumes a reader to EOF under the destination lease. A rutis callback supplies bytes or EOF for the native reader parameter. Preserve atomic replacement and cleanup on failure or caller shutdown. The existing bounded whole-file replaceBytes remains available for small files. | +| FileScope.read(name, offset, length) → FileResult of {data, eof, size} or null | The file scope reads one page through FileStorage's offset read; no reader id crosses. A scoped name never requires a caller-side root lookup. | +| FileScope.writeStream(name, next) → FileResult of null | The file scope consumes a reader to EOF and replaces the file through FileStorage's `write` with a source. A rutis callback supplies bytes or EOF for the native reader parameter. Preserve atomic replacement and cleanup on failure or caller shutdown. The bounded whole-file `replaceBytes` remains available for small files. | | settings.declaredBy({instanceId}) → SourceDeclaration[] | SettingsService.declared_by already selects live declarations by registering instance. PluginManager passes the loader's current instance ID. settings.sources lists declarations across owners and omits that identity. | -The OS path, pinned reader and input reader above use a path value, an existing reader ID -and a callback respectively. Existing local media submission/import, legacy node paths, +The OS path and input reader above use a path value and a callback respectively; FileStorage's read is defined by its [contract](../../architecture/rust-agent/plugins/FileStorage.md). Existing local media submission/import, legacy node paths, result settlement and result paging keep the [Modality contract](../plugins/Modality.md). ## Persistent Agents → sqliteStorage @@ -77,7 +76,7 @@ An admitted round is drained on shutdown. Losing the reply does not authorize re 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. +First import emits no notice. File and project profiles use FileStorage's `read` and `update`; their notification paths stay. ### Provider → sqliteStorage @@ -139,7 +138,7 @@ serves declared sources and excludes the native `mcp-secrets` document. | HooksSettings and HookSources | hooks, hooks-projects and hooks-plugins. The runtime consumes sources(cwd,cancelled) → HookSourcesSnapshot. Source resolution, revisions and enablement belong to Hooks. | | Mcp and McpPublication | mcp, mcp-projects, mcp-plugins and mcp-secrets. Publication reads effective server configuration and constructs live connections. Keep partial decoding of individual server entries and credential use at the MCP owner. | | SkillsCatalog, Scheduler, Modality | Each registers and reads/updates its own native source. Keep the existing SkillDocument, ScheduleDocument and ModalitySettings behavior, including duplicate-job checks and validated model defaults. Their public management methods run at the feature owner. | -| Settings → sqliteStorage in the native user profile | Read the existing row; on first use import validated content and provenance atomically; replace at expected revision and publish after commit. File-backed and project settings keep their existing file path and lease behavior. | +| Settings → sqliteStorage in the native user profile | Read the existing row; on first use import validated content and provenance atomically; replace at expected revision and publish after commit. File-backed and project settings keep their existing file path and use FileStorage's `read` and `update`. | | Sources using a declared schema → Settings | `settings.register/read/update`. | | Native non-secret sources with custom decoding → Settings | `settings.registerDocument({source,userFile,projectFile?},codec) → {read,update}`. The source-bound operations are `read(scope) → {revision,document}` and `update(scope,expectedRevision,document) → {revision,document}`. Registration ends on owner unload. | diff --git a/docs/design/p6-p7-bindings.md b/docs/design/p6-p7-bindings.md index d7d3f1ef11..4535b8a991 100644 --- a/docs/design/p6-p7-bindings.md +++ b/docs/design/p6-p7-bindings.md @@ -20,7 +20,7 @@ owner's design; the storage binding does not implement either business package. | Consumer | Required behavior | Existing mechanism | Missing repository work | | --- | --- | --- | --- | | Scheduler launching under a preset | Cap the saved preset against the live host bound at launch | S2's `sessions.launch` admission takes `policy?`, caps it and replies with the effective policy ([S2 D4/D6](appserver/sessions-service.md#3-decisions)) | None: Scheduler stores the preset and reads no permission state ([Scheduler §3.3](plugins/Scheduler.md#33-permission-of-a-run)) | -| Workflow definitions | Read user, project and installed-package definitions; save project definitions within file authority | Settings owner reads/CAS and project authorization; `FileStorage` read/list/replace/create-directory | A native, row-scoped file binding restricted to definition directories | +| Workflow definitions | Read user, project and installed-package definitions; save project definitions within file authority | Settings owner reads/CAS and project authorization; FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | A native, row-scoped file binding restricted to definition directories | | Workflow report recovery | Retry a report whose reply was lost without writing it twice | S2 input with the branch accepting each `submissionId` once | Retain admitted native input work through settlement; verify resubmission across row and runtime replacement in actual Node flows | Creation configuration is not live Permission state. Published history is not a @@ -133,7 +133,7 @@ The four methods are asynchronous: | `read` | `{root, path}` | Bytes, received as `Uint8Array` by TypeScript | | `list` | `{root}` | Definition-directory entries `[{name, kind}]`, where `kind` is `file`, `directory` or `other` | | `replace` | `{root: {project: canonicalCwd}, path, bytes}` | `void`, after existing atomic replacement and durability check | -| `createDirectory` | `{root: {project: canonicalCwd}}` | `void`, after ensuring `.dimcode`, then `.dimcode/workflows`, through existing non-recursive creates | +| `createDirectory` | `{root: {project: canonicalCwd}}` | `void`, after ensuring `.dimcode`, then `.dimcode/workflows`, through `createDirectory` for each level | The plain Rust methods take serde request types. `read` returns `std::result::Result`; @@ -152,9 +152,7 @@ also an authorized FileStorage root. Directory creation ensures only the two fixed project ancestors, without creating siblings or replacing non-directories. These are new binding authorization checks, not existing FileStorage guarantees. -FileStorage has `register_root` and `root_path`, not a path-to-index lookup. Use -the project indices Settings already owns and package indices from trusted -assembly; expose neither root lookup nor registration. Reserved resources, +This paragraph is superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). Reserved resources, symlinks, generation validity and mutation locking remain FileStorage's checks. Root registration stays with the trusted host. Selectors and internal indices are not persisted definition identities. @@ -170,7 +168,7 @@ raw numeric root, is refused by generated decoding before the method runs. A name that cannot be represented as UTF-8 is `invalid_data`, never a lossy alias. `unsynced` means a mutation may already be visible: do not retry it as an unchanged write. `replace` keeps native permission behavior, with no chmod API. -`read` and `replace` reject definition files above 8 MiB as `invalid_data`. Reads use FileStorage's bounded read: check the opened handle's length before allocating contents and enforce the cap on each chunk to cover concurrent growth. An over-limit read returns no partial bytes; an over-limit replacement leaves the existing file untouched. This ceiling leaves room for base64 bytes and the JSON envelope within the existing 16 MiB bridge frame. Workflow checks serialized project-save bytes before issuing a binary call. Workflow's own decoded-definition admission (1 MiB compact JSON) and run-store payload (8 MiB) bounds apply after this port returns bytes; committed run snapshots keep their existing decoder. This port adds no chunking or shared transport change. +`read` and `replace` reject definition files above 8 MiB as `invalid_data`. Reads take the length from FileStorage's `stat` before allocating and enforce the cap on each `read` page to cover concurrent growth. An over-limit read returns no partial bytes; an over-limit replacement leaves the existing file untouched. This ceiling leaves room for base64 bytes and the JSON envelope within the existing 16 MiB bridge frame. Workflow checks serialized project-save bytes before issuing a binary call. Workflow's own decoded-definition admission (1 MiB compact JSON) and run-store payload (8 MiB) bounds apply after this port returns bytes; committed run snapshots keep their existing decoder. This port adds no chunking or shared transport change. No deletion, arbitrary root registration, lock API or S10 envelope is exported. diff --git a/docs/design/plugins/Modality.md b/docs/design/plugins/Modality.md index 9d5d97d89c..ff288dc8fe 100644 --- a/docs/design/plugins/Modality.md +++ b/docs/design/plugins/Modality.md @@ -40,7 +40,7 @@ All dependencies are process services at the same scope ([ADR 002 D3](../../adr/ | Part | Scope | Depends on | Provides | | --- | --- | --- | --- | -| `Modality` | Process (control node) | Provider model selection (`ModelSelectionHost`) and non-conversational connection resolution; `pluginFiles` (UTF-8 and binary), `fsHost.readAt/closeRead` for opened readers; Settings business source `modality`; the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, A.2); HostPlatform of the control node (OCR); diagnostics | `modalityTasks` and `modalityTargets` process services; registers `modality` (`modality.*`) with `managementMethods` | +| `Modality` | Process (control node) | Provider model selection (`ModelSelectionHost`) and non-conversational connection resolution; `pluginFiles` (UTF-8 and binary); FileStorage's reads per its [contract](../../architecture/rust-agent/plugins/FileStorage.md); Settings business source `modality`; the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, A.2); HostPlatform of the control node (OCR); diagnostics | `modalityTasks` and `modalityTargets` process services; registers `modality` (`modality.*`) with `managementMethods` | | Adapter plugins | Process | their own provider dependencies | `modalityAdapter` provider copies at their provider ids; the built-in supplies only the family fallback (A.2) | **Contracts depended on:** the [methods](../contracts/session-boundary.md) contract (namespaces registered with `managementMethods`, per-call progress sink, connection-bound notifications); the per-provider adapter copy read per call, with the family copy behind it ([#40](https://github.com/arcships/dim/issues/40) decided it, §1 and A.2); Provider's model selection (`ResolveModelSelection::resolve`, which rejects an unselectable explicit model; [AuxiliaryModel](../appserver/auxiliary-model.md)), its selectable-model read for the option list (§9.2), and, for every adapter operation and realtime session, its non-conversational connection resolution ([overview Appendix B.2](../overview.md#b2-app-server-process-plugins), §9.3); `pluginFiles` (extended) with binary atomic replace and a format version ([App Server README](../../../crates/dim-app-server/README.md#trusted-plugin-storage)); HostPlatform spawn with isolation ([HostPlatform](../../architecture/rust-agent/plugins/HostPlatform.md), isolation supplement in [overview Appendix B.1](../overview.md#b1-session-and-branch-capabilities)). diff --git a/docs/design/plugins/PluginFiles.md b/docs/design/plugins/PluginFiles.md new file mode 100644 index 0000000000..3140ab2876 --- /dev/null +++ b/docs/design/plugins/PluginFiles.md @@ -0,0 +1,345 @@ +# PluginFiles + +Scope: process service with row-bound scopes. Issue: #2016. + +PluginFiles owns trusted-plugin file storage under one authorized product root: the version-1 text envelope, the per-consumer relative names, the 8 MiB whole-file bound and the exclusivity of one record transaction. It uses [FileStorage](../../architecture/rust-agent/plugins/FileStorage.md) for every read, write, directory and removal; it defines no file format or exclusion of its own beyond the envelope and the root. Its public face is the `dimcode/plugin` SDK (`npm/plugin.d.ts`). This contract replaces the lease surface in the App Server README, the TypeScript authoring guide and the public binding in process-typescript. + +## Use and scope: responsibility split + +PluginFiles owns: + +- **The root and names.** One authorized product root per provider, and each consumer's relative path below it. A name is a relative path; `..`, an absolute path and the module's reserved names are refused. +- **The text envelope.** `{version: 1, text}` for files written by `withLock`; a file that is not version 1 fails `invalid_data` before a change runs and stays unchanged. +- **The whole-file bound.** `readBytes` and `replaceBytes` handle at most 8 MiB; the bound caps one allocation. +- **The transaction.** One record change is cross-process exclusive through FileStorage's `update`; the change receives the current text and returns the replacement and its own result. +- **The scope lifetime.** A scope is bound to the row that opened it; `quiesce` stops new work, `close` and row unload settle admitted work. + +Callers keep: + +- Their record formats and meanings: Scheduler jobs and runs, EventHub publications, Workflow runs and version token, Modality adapter files. +- Which relative name a record uses and what a result means. +- Their own side effects; an external effect is outside the transaction. +- Their own errors above PluginFiles' kinds. + +| Requirement (callers) | Compose from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Read a small text record whole | Yes: `withLock` with a null replacement returns the current text | Business composes | +| Change a text record while other processes may write it | No: the read and the write must share one exclusion, and only the owner can hold FileStorage's `update` across the change | `withLock` | +| Read a large file in pages | No: the page bound and the size are the owner's, and the caller holds no reader | `read` | +| Read or replace a raw file whole | No: the 8 MiB bound is the owner's and one call must not hold it twice | `readBytes`, `replaceBytes` | +| Replace a file from a stream | No: the temporary file and the atomic rename are FileStorage's | `writeStream` | +| Create a work directory and learn its path | No: per-component validation is FileStorage's | `directory` | +| List one level and remove by a listed name | No: the name rules and removal are FileStorage's | `list`, `remove` | +| Stop and settle a scope | No: admitted work and the row lifetime are the owner's | `quiesce`, `close` | +| Back a file up before rewriting it | Yes: read the text, keep the copy in the caller's own record, then `withLock` | Business composes | +| Do several record edits under one lock | Yes, if they are one record change: compute them inside one `withLock`; otherwise they are several transactions and each is atomic | Business composes | + +## Caller example + +Workflow's run store keeps the run document and a token of the last committed write. Two records need two transactions; the token is derived state, so a reader whose token does not match rereads the document. + +```ts +await scope.withLock("workflow/runs.json", () => ({ text: encode(runs), value: null })) +await scope.withLock("workflow/runs.version", () => ({ text: token, value: null })) +``` + +Scheduler's job record and EventHub's publish record change one text record per call: + +```ts +const result = await scope.withLock("scheduler/jobs.json", (current) => { + const jobs = decode(current) // null when absent + const next = apply(jobs, request) // business rules + return { text: encode(next), value: next } +}) +if (!result.ok) return report(result.error) +``` + +A large file is read in pages by path, with no reader to release: + +```ts +const page = await scope.read("modality/results/42.json", offset, PAGE) +if (page.ok && page.value) { + if (page.value.eof) done() + offset += page.value.data.length +} +``` + +## Own contract + +### Dependencies + +[FileStorage](../../architecture/rust-agent/plugins/FileStorage.md): the provider opens one authorized root (`add_root`/`root_path`) and calls `read`, `write`, `import`, `update`, `create_directory`, `list` and `remove`. No other service is injected. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `open` | Open a scope bound to the calling row | — | scope | While the root is opened | `invalid_path`, `io`, `closed`, `internal` | +| `withLock` | Change one text record under FileStorage's `update` | `{name}` and the `work` callback | the callback's own result | Before the replacement; the file is unchanged | `invalid_data`, `invalid_path`, `io`, `unsynced`, `cancelled`, `closed`, `internal` | +| `read` | One page of a file by path | `{name, offset, length}` | `{data, eof, size}` or none | Before the reply; nothing changes | `invalid_data`, `invalid_path`, `io`, `cancelled`, `closed` | +| `readBytes` | The whole file, envelope included, at most 8 MiB | `{name}` | bytes or none | Before the reply | `invalid_data`, `invalid_path`, `io`, `cancelled`, `closed` | +| `replaceBytes` | Replace the file with raw bytes, at most 8 MiB | `{name, bytes}` | unit | Before the replacement | `invalid_data`, `invalid_path`, `io`, `unsynced`, `cancelled`, `closed` | +| `writeStream` | Replace the file from a stream of chunks | `{name}` and the `next` callback | unit | Before the replacement; the old content stays | `invalid_path`, `io`, `unsynced`, `cancelled`, `closed` | +| `directory` | Make the work directory tree and return its absolute path | `{name}` | path | Between levels; created ancestors stay | `invalid_path`, `io`, `unsynced`, `cancelled`, `closed` | +| `list` | One level below `prefix` | `{prefix}` | entries | Before the reply | `invalid_path`, `io`, `cancelled`, `closed` | +| `remove` | Remove a file or a directory tree; an absent entry counts as removed | `{name}` | unit | Before the unlink; a tree can be partly removed, a retry is safe | `invalid_path`, `io`, `unsynced`, `cancelled`, `closed` | +| `quiesce` | Stop admitting work on the scope | — | unit | None; admitted work keeps its time | `closed` | +| `close` | Stop the scope and settle admitted work | — | unit | None; the owner completes | `closed` | + +`withLock`'s `work` is a direct callback, not a request field. It receives the current text, or none when the file is absent, and returns the replacement text (none keeps the file unchanged, mapped to FileStorage's `update` with a `None` replacement) together with its own result. It only computes: an external wait, another owner or another PluginFiles call inside `work` holds the record for that whole wait. The owner runs `work` under FileStorage's `update`, so two processes cannot interleave; a repeated result is idempotent because the replacement is compared with the current text. + +`read` returns a page of at most 64 KiB and the file's size; an offset equal to the size is an empty page with `eof`, an offset above it is `invalid_data`, and a missing file is none. `readBytes` and `replaceBytes` are one operation each and share the 8 MiB bound. + +### Errors + +| Kind | Retry | What the caller does next | +| --- | --- | --- | +| `invalid_path` | After fixing the name | A relative path escaping the root, an absolute path, a reserved name, or a name that is not one component; nothing changed | +| `invalid_data` | After fixing the data | A text file is not the version-1 envelope, a whole file is over 8 MiB, or a page offset is above the size; nothing changed | +| `io` | Yes, after fixing the environment | A filesystem refusal or an unavailable root; the message says which; a read shows whether the earlier call changed anything | +| `cancelled` | Yes, the same call | The caller's own cancellation ended the call before the replacement; nothing changed | +| `unsynced` | Not as an unchanged write | The bytes are in place but durability is unconfirmed; a read shows them and a repeated call confirms | +| `closed` | Yes, against a new scope | The provider or this scope is unloading; the operation did not run or its result is unknown past the replacement | +| `internal` | No | The host worker failed; the message is diagnostic, and the caller reports it without retrying the side effect | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `withLock` | Resolve the name, call FileStorage's `update`; `work` runs under that hold, the owner writes the replacement or leaves the file when it is none, and FileStorage syncs the parent | Before the replacement: the file is unchanged; the owner's `update` returns `cancelled` | Admitted work settles before the scope closes; an unadmitted call ends `cancelled` | New work is refused; admitted work settles; a later call is `closed` | FileStorage's `update` and temporary file; the scope by the calling row | +| `read` | Resolve the name, call FileStorage's `read`, return the page | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | FileStorage | +| `readBytes`, `replaceBytes` | One FileStorage `read` or `update`; the 8 MiB bound is checked before the call | Before the replacement | The same as `withLock` for `replaceBytes` | Pending calls end `closed` | FileStorage | +| `writeStream` | Resolve the name, pull the next chunk until none, FileStorage replaces atomically | The pull stops; the old content stays | The source is revoked; the old content stays | Pending calls end `closed` | FileStorage | +| `directory` | Resolve the name, FileStorage creates the tree, return the path | Between levels; created ancestors stay | The call ends `cancelled` | Pending calls end `closed` | FileStorage | +| `list`, `remove` | FileStorage `list`/`remove` on the resolved path | Before the reply or the unlink | The call ends `cancelled` | Pending calls end `closed` | FileStorage | +| `open`, `quiesce`, `close` | Bind or stop the scope; `close` joins admitted work | None | The row's unload closes the scope | A new scope needs a new provider generation | The scope by the calling row; the provider by its owner | + +## Callers and migration + +- Workflow's run store has one commit point. A write first writes the new content to `workflow/runs/.json` (a new file), then makes one `update` of `workflow/runs.version`: the callback compares the current token with the one read before the write; on a mismatch it returns `None`, the writer deletes its new file, rereads and retries; on a match it writes the new token. That pointer update is the only commit; after it the writer deletes the old data file, and a failed delete leaves an orphan. A reader reads `runs.version` and reads the data file only when the token changed; if the data file is gone (a later write deleted it), it rereads the token and retries. Startup deletes `runs/*.json` the token does not point to, and when `runs.version` is absent but the old `runs.json` exists, it migrates once. A data-file write failure and a pointer-update failure are both uncommitted and return an error; there is no committed-but-unreadable state. Acceptance: a warm reader plus a write that fails between the data file and the pointer sees the old consistent snapshot and the writer gets an error; two concurrent writers, one retries and succeeds. +- Scheduler (jobs, runs, wakeups), EventHub (publish records) and Modality (adapter files) keep their record shapes and move to `withLock`, `readBytes`/`replaceBytes`, `writeStream` and `read`; each is checked in the delivery. +- `runtime/fixtures/files-*.ts`, `workflow-package.ts` and `crates/dim-app-server/tests/plugin_files_flow.rs` move to the new flows. + +## Exceptions with reasons + +- The scope is an object, not an id: it is the calling row's lifetime, `close` is registered with the row's effect, and the provider owns the root. The shared lifecycle is the process part's own; no caller holds it after its row unloads. +- `read` and `readBytes` return the stored bytes, envelope included, for a text file; decoding is the caller's. `withLock` is the only operation that handles the envelope. +- The 8 MiB bound is the caller's allocation bound, not FileStorage's document bound; a larger file is read in pages by path. + +## Client-visible changes + +The `dimcode/plugin` SDK is visible to third-party trusted plugins. This contract changes it: + +- `FileLease` is deleted, with its `read`, `replace`, `backup`, `readBytes` and `replaceBytes` methods. +- `withLock(name, work, cancelled?)` takes a callback that receives the current text and returns `{text, value}`; it no longer yields a lease. +- `openRead` is replaced by `read(name, offset, length)`. +- `remove` no longer returns `locked`; it waits for the key. +- `FileError` drops `locked` and `exists` and adds `unsynced`. +- `npm/plugin.d.ts` changes in the implementation delivery together with the provider and every caller; this contract states the face they implement. The migration rows are in the delivery tables on [#2016](https://github.com/arcships/dim/issues/2016). + +## Supersedes + +- `crates/dim-app-server/README.md`: the "Trusted plugin storage" section. +- `docs/design/process-typescript.md`: §5.2 "Public PluginFiles binding". +- `docs/typescript-plugin-authoring.md`: the `withLock` transaction paragraph and the scope operations it lists. +- [FileStorage](../../architecture/rust-agent/plugins/FileStorage.md) § "Callers that hold work across an external wait": the PluginFiles paragraph. + +## Verification + +Flow tests on the owner: + +- `withLock` runs the change under one FileStorage `update`; two processes changing one record serialize; a `null` replacement leaves the file unchanged; a change that fails leaves the old text. +- A non-version-1 envelope and a whole file over 8 MiB answer `invalid_data` without changing the file. +- `read` pages at 64 KiB with `size` and `eof`; an offset at the size is empty, above it is `invalid_data`; a missing file is none. +- `readBytes`/`replaceBytes` at the 8 MiB bound and just over it. +- `writeStream` publishes atomically and leaves the old content on a source failure or cancellation. +- `remove` of a held file waits and ends `cancelled`; an absent entry counts as removed; a tree retry after a partial removal finishes. +- `close` and row unload settle admitted work; a later call is `closed`. +- Migration checks: Workflow's two transactions (`workflow/runs.json`, then `workflow/runs.version`; the token is derived and a mismatched token rereads), Scheduler (jobs, runs, wakeups), EventHub (publish records) and Modality (adapter files) keep their record shapes; `runtime/fixtures/files-*.ts`, `workflow-package.ts` and `crates/dim-app-server/tests/plugin_files_flow.rs` move to these flows. + +## Rule check + +The rules are [design rules §7](../../architecture/rust-agent/principles.md#7-所有者与操作) and §1–§6 of `principles.md`. + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process provider and one row-bound scope per caller; no Timeline fact and no Capability. | +| §2 scopes | The provider is process scope; the scope object is bound to the calling row and closes with it. | +| §3 orthogonality | Only FileStorage's operations are used; no other owner's state is read. | +| §4 rule 1 | No command event: PluginFiles writes no Timeline fact. | +| §4 rule 2 | No handoff: files and keys stay with FileStorage. | +| §4 rule 3 | The change runs under FileStorage's update, never inside the Timeline commit lock. | +| §4 rule 4 | Core and assembly carry no business meaning; no record format above the envelope appears here. | +| §4 rule 5 | No batch semantics. | +| §4 rule 6 | File content reaches the model only through tool results; PluginFiles only serves its callers. | +| §4 rule 7 | Callers use the scope operations; no caller reads a key or a descriptor. | +| §4 rule 8 | No mechanism requirement. | +| §4 rule 9 | No Timeline fact. | +| §7.1 resource and lifecycle | The provider owns the root and the scopes; a row's unload closes its scope after admitted work settles. | +| §7.1 operation granularity | One operation is one transaction or one read; no lease or reader id crosses a call. | +| §7.1 owner granularity | One storage owner for plugin files; FileStorage owns the bytes and the exclusion. | +| §7.2 operations | Every caller need maps to one operation above; nothing is proxied from another owner. | +| §7.2 handoff | Values and callbacks cross; the scope is the row's own lifetime with `close` registered by its effect. | +| §7.2 one face | One scope interface; no second API beside it. | +| §7.2 data face | Methods, arguments, replies and errors are data except the callbacks §7 allows; the scope object is the calling row's own. | +| §7.2 business boundary | No caller record format on the face beyond the version-1 envelope; each operation answers why it cannot be composed. | +| §7.2 one change | The SDK, the provider and every caller change in the same delivery. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +The SDK types are the public contract; the Rust binding is the provider's `PluginFiles` and `FileScope` with the same operations. `caller: &Ctx` is the dispatch's calling row. + +```rust +use rutis::host::BoxFuture; +use rutis::Ctx; +use std::sync::Arc; + +pub const WHOLE_FILE_LIMIT: u64 = 8 * 1024 * 1024; +pub const PAGE_LIMIT: u32 = 64 * 1024; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Page { + #[serde(with = "base64_bytes")] + pub data: Vec, + pub eof: bool, + pub size: u64, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct FileEntry { + pub name: String, + pub kind: FileKind, +} + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum FileKind { + File, + Directory, + Other, +} + +/// The change's replacement (none keeps the file) and its own result. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LockChange { + pub text: Option, + pub value: T, +} + +pub type WorkFn = Arc< + dyn Fn(Option) -> BoxFuture<'static, Result, PluginFileError>> + Send + Sync, +>; + +#[derive(Debug, Clone, thiserror::Error, serde::Serialize, serde::Deserialize)] +#[serde(tag = "code", rename_all = "snake_case")] +pub enum PluginFileError { + #[error("{message}")] + InvalidPath { message: String }, + #[error("{message}")] + InvalidData { message: String }, + #[error("{message}")] + Io { message: String }, + #[error("{message}")] + Unsynced { message: String }, + #[error("{message}")] + Cancelled { message: String }, + #[error("{message}")] + Closed { message: String }, + #[error("{message}")] + Internal { message: String }, +} + +pub struct PluginFiles; + +impl PluginFiles { + pub async fn open(&self, caller: &Ctx) -> Result { + // ... + } +} + +pub struct FileScope; + +impl FileScope { + pub async fn with_lock( + &self, + name: String, + work: WorkFn, + cancelled: crate::host::CancelledFn, + ) -> Result { + // ... + } + + pub async fn read( + &self, + name: String, + offset: u64, + length: u32, + cancelled: crate::host::CancelledFn, + ) -> Result, PluginFileError> { + // ... + } + + pub async fn read_bytes( + &self, + name: String, + cancelled: crate::host::CancelledFn, + ) -> Result>, PluginFileError> { + // ... + } + + pub async fn replace_bytes( + &self, + name: String, + bytes: Vec, + cancelled: crate::host::CancelledFn, + ) -> Result<(), PluginFileError> { + // ... + } + + pub async fn write_stream( + &self, + name: String, + next: Arc BoxFuture<'static, Result>, PluginFileError>> + Send + Sync>, + cancelled: crate::host::CancelledFn, + ) -> Result<(), PluginFileError> { + // ... + } + + pub async fn list( + &self, + prefix: String, + cancelled: crate::host::CancelledFn, + ) -> Result, PluginFileError> { + // ... + } + + pub async fn remove( + &self, + name: String, + cancelled: crate::host::CancelledFn, + ) -> Result<(), PluginFileError> { + // ... + } + + pub async fn directory( + &self, + name: String, + cancelled: crate::host::CancelledFn, + ) -> Result { + // ... + } + + pub fn quiesce(&self) {} + + pub async fn close(&self) {} +} +``` + +`base64_bytes` is the same small local serde module FileStorage uses for `Bytes`. Every callback is a direct parameter, not a request field. diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..b35f49d5f2 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,7 @@ 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 | | --- | --- | --- | --- | --- | +| [PluginFiles](PluginFiles.md) (owner contract) | trusted-plugin storage: the v1 envelope, one authorized root, the 8 MiB bound and one cross-process record change per `withLock` | — | — | [#2016](https://github.com/arcships/dim/issues/2016) | | [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 +52,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 | PluginFiles, 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/process-typescript.md b/docs/design/process-typescript.md index bd9deaaa7b..bd06853687 100644 --- a/docs/design/process-typescript.md +++ b/docs/design/process-typescript.md @@ -419,86 +419,7 @@ Timeline, storage or persistence contract changes here. ### 5.2 Public pluginFiles binding -`pluginFiles` is a shared named service with an implemented text/transaction API. -`serve` registers its existing native provider with the authorized product root: - -| Host configuration | Registration | -| --- | --- | -| An embedding host names a root in `ServerConfig::plugin_files` | Register `PluginFilesPlugin` with that root once in the native process rows; availability does not depend on which process, Session, branch or managed rows are configured | -| Otherwise, an authorized `product_home` | Register `PluginFilesPlugin(product_root)` once in the native process rows, as above | -| Otherwise, the execution home `--home` | Register `PluginFilesPlugin(execution_home)` once in the native process rows, as above | -| Only `--database` (no named root, product home or `--home`) | Do not invent a root and never fall back to the database's directory or the working directory; no provider is supplied | - -PluginManager's home is the product home, else `--home`, and it runs only with -a product home or `--home` ([PluginManager §2.1](plugins/PluginManager.md#21-the-plugin-directory-and-its-manifest)), -so the plugin files root and the plugin manager never disagree. A host started -with only a database file therefore runs no PluginManager either. - -This changes only native composition: `pluginFiles.open`, S10 outer v1, -FileStorage authority and provider lifetime are unchanged, and the scope and -lease offer the operations below. No row field, dependency registry, optional -lookup or rutis/core mechanism is added. The managed plugin keeps its existing -binding; public rows use their own ordinary runtime and declarations, without a -managed-plugin slot. The provider depends only on FileStorage, preserving §5.1's -stable boundary. Session and branch parts resolve this same shared service -through the existing catalog; a Session-only configuration must not require a -dummy process row. - -The scope offers `withLock`, `list(prefix)`, `remove(name)`, `directory(name)`, -`openRead(name)` and `writeStream(name, next)`. The lease offers -`read`, `replace`, `backup`, `readBytes` and `replaceBytes`. `list` returns one -level of a directory prefix, sorted, each entry its name relative to the -authorized root and its kind, and never enters a directory entry; a returned -name is the resolved components joined by `/`, so it can be passed straight to -another operation, and on Unix a backslash is part of a name while on Windows -it separates. `remove` takes a file or a directory tree and reports `locked` -while a lease holds it or a file beneath it. Text and binary are separate operations on the same names: -`read` and `replace` use the v1 text envelope, `readBytes` and `replaceBytes` -carry raw bytes. A text read of a raw file fails `invalid_data` and leaves it -untouched, and a binary read of a text file returns its envelope bytes. The byte -operations are whole-buffer and capped at 8 MiB, which bounds one allocation. -A text `replace` is admitted when its serialized record fits the runtime's 16 MiB -frame; a larger one fails that call with a `BindingError` coded `bad-value` -before the file changes, while the row and the file store stay up. Since rutis -0.23 chunks a larger frame, the `pluginFiles` boundary makes this refusal itself; -a rejected write leaves the previous contents intact. A call argument that no Dim -face limits is no longer refused by the runtime at the 16 MiB boundary. -`scope.directory(name)` creates missing parents and returns the node-local work path. -`scope.openRead(name)` returns a pinned reader ID and size, or null for a missing file. -Use `fsHost.readAt` to read. The reader remains valid across `scope.close()` until -`fsHost.closeRead` or unload of the opening row. -`scope.writeStream(name, next)` consumes byte chunks until null and replaces the file atomically. -Source failure or cancellation discards the partial replacement. - -All trusted consumers use that same host-authorized root. A FileScope owns -operations and cleanup; it is not a per-package directory sandbox. Consumers -use their declared relative paths, under their own id directory. PluginManager -creates `//` when it turns a plugin with code on -([PluginManager §2.1](plugins/PluginManager.md#21-the-plugin-directory-and-its-manifest)); -an embedding host that supplies rows itself provisions the consumer directories -at installation. Scheduler uses `scheduler/` and Workflow uses `workflow/`. -Only `scope.directory` creates missing parents. For an absent parent, -`writeStream` returns `io`, `openRead` returns null, and `withLock` returns `io` -before invoking its callback. The consumer surfaces that storage failure and -starts no run effect; it does not create a Session or submit input without the -required durable transition. - -The actual Node acceptance uses isolated product homes. Public process and -Session-only configurations open a scope and replace/read versioned text without -a managed plugin. Closing a scope rejects new acquisitions and waits for a held -transaction to persist. An unprovisioned parent returns `io`, creates no directory -and does not enter the callback; invalid stored bytes return `invalid_data` and -remain unchanged. Without a product root the process row stays Pending while -native Sessions remain usable. Managed and public rows share one provider. -The Session-only flow also holds a transaction across `session.close`: closure -waits for its write to settle, and the next Session reads the persisted value. -The starting method has returned before close; only the file scope owns and -joins that transaction, rather than the admitted method's drain. - -Workflow's persisted-attempt, failed-replacement and host-restart acceptance must -also run under this public binding. Readiness and report-specific evidence follow -each owner's design document. The storage binding alone proves no complete feature -behavior; no-run-effect behavior requires each package's business-flow acceptance. +This section is superseded by the [PluginFiles contract](plugins/PluginFiles.md). ## 6. Rule check diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index e5dd257f13..952d6ae7ad 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -2,7 +2,7 @@ Status: Draft. Issues: [#1295](https://github.com/arcships/dim/issues/1295) (`execHost`), [#1296](https://github.com/arcships/dim/issues/1296) (leaf identity and lifecycle), -[#1297](https://github.com/arcships/dim/issues/1297) (`fsHost`), +[#1297](https://github.com/arcships/dim/issues/1297) (file tools), [#2016](https://github.com/arcships/dim/issues/2016) (`fsHost`), [#1298](https://github.com/arcships/dim/issues/1298) (`store`); parent [#1292](https://github.com/arcships/dim/issues/1292). Policy: [service faces](service-faces.md). Background: [remote plugins §3–§4](research/remote-plugins.md). @@ -16,11 +16,13 @@ Resource and state operations use these public data faces: | Face | Operations | Provided by | Issue | | --- | --- | --- | --- | | `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 | +| `fsHost` | This section is superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). | the file-storage owner | #2016 | | `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 | +The tool family (`resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions`) is the file-tools owner's operations and is not part of `fsHost`; [#1297](https://github.com/arcships/dim/issues/1297) tracks that design. `fsHost` is the storage face of the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). + ```text control node resource leaf (mounted per #1296) WorkspaceTools ── fsHost ─── data ──────► file operations on node files @@ -42,7 +44,7 @@ SQLite or PostgreSQL. Whether a face is reachable over a link is decided by depl classification on the name. The public contract and migration rules are in [service faces](service-faces.md) §2. -For these resource faces, §6 maps `hostPlatform`, `fileStorage`, `sqliteStorage` and `timelineStore` +For these resource faces, §6 maps `hostPlatform`, `fsHost`, `sqliteStorage` and `timelineStore` to their public operations and Rust bindings. What stays on the control side, in every case: Session and branch scope, admission @@ -60,7 +62,7 @@ whether a call may run, or consults who is calling. each; a traversal is one call, not one call per file. 3. **Paths are node paths.** A request carries a node-absolute resolved path; a reply returns node-absolute resolved paths only. A relative path in a request is `invalid`, with one - exception: **`fsHost.resolve` is the resolution entry point**, so it accepts the path as the + exception: **the file-tools face's `resolve` is the resolution entry point**, so it accepts the path as the model gave it — relative to the `cwd` the caller passes, starting with `~`, containing `..`, following symlinks — because only the node can resolve it. `cwd`, `workspace` and the confirmed roots it is given are node-absolute. Every other operation, `execHost.start` and @@ -104,7 +106,7 @@ whether a call may run, or consults who is calling. ### 3.2 `start` and `wait` `start` accepts only `{taskId, command, cwd, workspace, roots}`. `cwd` is a resolved working -directory — the control side obtains it from `fsHost.resolve`, which is also what triggers +directory — the control side obtains it from the file-tools face's `resolve`, which is also what triggers [worktree recognition](#421-session-scoped-recognition-and-association) for a cwd outside the known range; an absent `cwd` is `workspace`. `workspace` is the Session's workspace root and `roots` the mapped subtree paths from the Session's confirmed worktrees. All are node-absolute. @@ -339,11 +341,16 @@ client reads and writes them through the node's own management methods, not thro | `remove_failed` | Removing a persistent-shell output directory or making the removal durable failed | | `cancelled` | The call was cancelled before it changed anything | -## 4. `fsHost` +## 4. File storage (`fsHost`) and the file tools + +The storage family in §4.1 and the error table in §4.7 are superseded by the [FileStorage +contract](../architecture/rust-agent/plugins/FileStorage.md). The tool-family table in §4.1 and subsections §4.2–§4.5 +belong to the file-tools face, whose name [#1297](https://github.com/arcships/dim/issues/1297) +settles, and are not part of `fsHost`. ### 4.1 Methods -Tool family — the file tools' operations, one call each: +Tool family — the file-tools face's operations, one call each (not `fsHost`): | Method | Mode | Request | Reply | | --- | --- | --- | --- | @@ -355,49 +362,7 @@ Tool family — the file tools' operations, one call each: | `grep` | async | `{pattern, path, include?, outputMode?, lineNumbers?, limit?, multiline?, literal?, timeoutMs?}` | `{result: ToolResult}` | | `mentions` | async | `{path, query, limit?}` | `{candidates}` | -Storage family — the raw operations the other file owners use. They take absolute paths and no -tool semantics: no line numbers, no images, no effects. - -| Method | Mode | Request | Reply | -| --- | --- | --- | --- | -| `stat` | async | `{path}` | `{kind: "file" \| "directory" \| "missing" \| "other", size?}` | -| `readBytes` | async | `{path, limit, leaseId?}` | `{bytes, size}` | -| `openRead` | async | `{path}` | `{readId, size}` | -| `readAt` | async | `{readId, offset, limit}` | `{bytes}` | -| `closeRead` | async | `{readId}` | `{}` | -| `lock` | async | `{path}` | `{leaseId}` | -| `unlock` | async | `{leaseId}` | `{}` | -| `backup` | async | `{leaseId, suffix, permissions?}` | `{}` | -| `createDirectory` | async | `{path}` | `{}` | -| `replace` | async | `{path, bytes, permissions?, leaseId?}` | `{}` | -| `list` | async | `{path}` | `{entries: [{name, kind}]}` | -| `remove` | async | `{path}` / `{parent, name}` | `{}` | - -A listed name passes unchanged to `remove({parent, name})`: a Unicode string, `{Unix: number[]}` for native bytes, or `{Windows: number[]}` for native UTF-16 code units. The owner checks that the name is a single component. - -- `readBytes` is the bounded read: `limit` is required, a larger file is `too_large` without - partial bytes, and `bytes` is base64. `size` is the file's length, so a caller can tell "done" - from "cut". -- `readBytes` and `replace` accept a `leaseId`: they then read or write through that lease, so a - read-modify-write keeps one lock from read to replace. `backup` writes the lease's current bytes - to a durable sibling named `.`. `unlock` releases the lease; ending the caller's - connection releases every lease it held. `permissions` is data — `"private"` (owner-only, 0600 - on Unix) or `"preserve"` (the existing file's mode) — because the provider's own permission type - is an OS object and does not cross; absent means `"preserve"`, as today. `replace` also accepts - `"privateReadOnly"` for a newly written Session file (Unix mode `0400`, Windows read-only - attribute). -- `openRead` pins a file for several bounded random reads (`readAt`) and is closed by `closeRead` - or the caller's connection. `readAt` retains the existing 64 KiB maximum per - call; a larger requested limit is clamped, zero or an offset at/past the pinned - length returns empty bytes. UI resource streaming uses these bounded reads. Plugin-file - uploads and work directories stay with the host-local - [PluginFiles service](../../crates/dim-app-server/README.md#trusted-plugin-storage). -- `stat` is one path, never a traversal: existence and kind for configuration discovery (a - project rule file, a hooks file). It is not a `stat`/`open` primitive API; traversals stay - `glob`, `grep` and `mentions`. -- `createDirectory` creates one directory with the existing rules (mode 0700, an existing one - counts as created, the parent must exist), `list` and `remove` serve the Session-file sweep, and - `replace` without a lease is the atomic whole-file write. +Storage family — the raw operations the other file owners use: this section is superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). Only `resolve` takes an unresolved `path`; every other operation takes the node-absolute `path` its caller holds (§2 rule 3). `resolve` is what the file facts owner and process preparation @@ -455,7 +420,7 @@ moves the Git probe away from the Session that has to persist the result. | Concern | Owner | | --- | --- | -| Git probe, repository identity, fixed-prefix mapping, root directory identity | `fsHost.resolve`, on the node holding the files | +| Git probe, repository identity, fixed-prefix mapping, root directory identity | the file-tools face's `resolve`, on the node holding the files | | Session view: confirmed roots with their identities, in-flight recognitions, "already known" answers, branch-independent cache | the file facts Session part — ADR 014's `fileAccessFacts` service — on the control node (worktree access §3) | | Worktree directory record and Session usage association, deduplicated and written atomically | `store.associateWorktree`, provided by SessionStore (worktree access §4, R2) | | Publishing the expanded range, and its revalidation | the Session part, after the store acknowledges (§4.2.2) | @@ -550,7 +515,7 @@ or changed one: - The control side records the returned binding in `FileReads` for the branch; that record stays branch memory on the control node and is not reconstructed from the node. - `write` and `edit` are admitted before they run, so their `path` is the resolved path `resolve` - returned. `ToolHost.resolve_write` asks `fsHost.resolve` for a remote Session instead of + returned. `ToolHost.resolve_write` asks the file-tools face's `resolve` for a remote Session instead of resolving locally; the resolved call is what approval and execution receive, as today. ### 4.4 `glob`, `grep` and `mentions` @@ -583,24 +548,13 @@ 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 files' FileStorage operations are superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). 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). ### 4.7 Errors -| Code | When | -| --- | --- | -| `node_unavailable` | The provider is not connected. Only this call fails | -| `invalid` | A relative path, an unbounded request, an id the provider does not hold | -| `not_found` | A storage operation on a missing path where one is required | -| `too_large` | A bounded read whose file exceeds `limit`; no partial bytes | -| `locked` | A `lock` whose lease is held by another call; the retry policy is the caller's | -| `cancelled` | The call was cancelled before it changed anything | - -Operation refusals are not in this table: they arrive as the tool result's own `isError` with the -code the operation already uses, so one code vocabulary serves the local and the remote path. +This section is superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md#errors). Operation refusals arrive as the tool result's own `isError` with the code the operation already uses. ## 5. `store` and `timelineStore` @@ -844,7 +798,7 @@ original path argument and ownership exclusion. | Old name | Face | What the name is now | | --- | --- | --- | | `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 | +| `fileStorage` | `fsHost` | This row is superseded by the [FileStorage contract](../architecture/rust-agent/plugins/FileStorage.md). | | `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 | @@ -859,13 +813,13 @@ The owners that read node files or start node processes, and the operations they | Owner | Operations | | --- | --- | | WorkspaceTools file tools | `resolve`, `read`, `write`, `edit`, `glob`, `grep`, `mentions` | -| SessionStore Session files and command output | `createDirectory`, `replace`, `list`, `remove`, `execHost.removeOutputDirectory` | -| Settings sources and their CAS writes | `readBytes`, `stat`, `lock`, `readBytes {leaseId}`, `replace {leaseId}`, `unlock` | -| MCP auth store, managed OAuth and OAuth token stores | `readBytes`, `lock`, `readBytes {leaseId}`, `backup`, `replace {leaseId}`, `unlock` | -| Hooks project file (`.dimcode/hooks.json`) | `stat`, `readBytes` | -| PromptSources (environment, project and user rule files) | `execHost.info` (`os`, `home`, `timezone`, `execShell`), `stat`, `readBytes` | -| UI extension resources | `stat`, `openRead`, `readAt`, `closeRead` | -| Migration ledger and snapshots | `createDirectory`, `list`, `remove` | +| SessionStore Session files and command output | `execHost.removeOutputDirectory`; FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| Settings sources and their CAS writes | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| MCP auth store, managed OAuth and OAuth token stores | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| Hooks project file (`.dimcode/hooks.json`) | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| PromptSources (environment, project and user rule files) | `execHost.info` (`os`, `home`, `timezone`, `execShell`); FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| UI extension resources | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | +| Migration ledger and snapshots | FileStorage per its [contract](../architecture/rust-agent/plugins/FileStorage.md) | | Hooks configuration commands | `execHost.configured` | | Worktree association | `store.associateWorktree` | @@ -881,7 +835,7 @@ The owners that read node files or start node processes, and the operations they | §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 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)) | +| §4 rule 8 | The faces add no Timeline, Dispatcher or event-format change, and raise no runtime requirement. | | §4 rule 9 | No new Timeline fact: `exec/started` and `exec/ended` already exist, and the faces write none | | ADR 002 D2 | No wiring plugin: each face is its provider's own service | | ADR 002 D3 | Dependencies follow scope: `execHost` and `fsHost` are process names a leaf can provide; `store` is provided where the Session state is | @@ -898,14 +852,9 @@ The owners that read node files or start node processes, and the operations they ## 8. Requirements raised to mechanism owners -One runtime requirement, already raised: [#861](https://github.com/arcships/dim/issues/861), the -host side resolving a Session's process-scope service per call by the Session's resource node. -[Overview §6.3](overview.md#63-multiple-nodes) states it as a runtime requirement and explicitly -raises nothing to rutis; this design likewise solves it with rutis's current capability, and an -implementer must not use a gated dependency, which would park a consumer while a leaf is offline -instead of failing one call with `node_unavailable`. - -No other requirement is raised: +No runtime requirement is raised. The faces use rutis's current capability, and an implementer +must not use a gated dependency, which would park a consumer while a leaf is offline instead of +failing one call with `io`. - The `timelineStore` face keeps the existing Timeline admission and publish ordering; the only change is that completion is delivered as a notification on the face instead of a Rust callback, which is @@ -953,10 +902,10 @@ are the PTY primitives the shell already has; `info`, `confined` and `configured and starts the platform already performs, including the configuration command Hooks runs. `removeOutputDirectory` carries the existing HostPlatform cleanup across the face. Paging by a registered output path reuses `output` after the provider releases its task record. -`fsHost` adds no primitive file API and no per-file traversal: its storage family is the reads and -leases the node's storage already offers, needed because a path's facts and its bytes cannot be -read on a machine that does not hold the file; `resolve` is where resolution and the worktree -probe belong. `store` publishes the repository operations the state owner already has; +`fsHost` adds no primitive file API and no per-file traversal: its reads, writes and updates are +the reads and locks the node's storage already offers, needed because a path's facts and its bytes +cannot be read on a machine that does not hold the file; the file-tools face's `resolve` is where +resolution and the worktree probe belong. `store` publishes the repository operations the state owner already has; `timelineStore` publishes its Timeline operations and completion notifications. StorageMethods reads database and WAL sizes through the native binding of `sqliteStorage.storageReport({})`; plugins can dispatch the same operation. SQLite owns the connections and SQL. `TimelineStore` is the native binding of `timelineStore`. Admission stays synchronous and completion keeps the callback's ordering as a notification. diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..035ce12ec0 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -124,7 +124,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 | +| `fileStorage` | `FilePath`、根与代次 | 本节由 [FileStorage 契约](../architecture/rust-agent/plugins/FileStorage.md) 取代。 | | `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) | | `promptSourcesBranch` | 分支 prompt 装配 | 按 #1292 确认公共操作与装配内部职责。 | @@ -160,7 +160,7 @@ Proposed target operations: [Resource and repository operations](contracts/resou `backgroundExec.start` 需要活的进程对象,仍是 `exec` 工具的操作,不在数据面上;`backgroundExec.stop` 是 kill。 这些名字在 catalog 里是 `data`,Rust 类型仍由部件在同一实例按类型键读取。 -`hostPlatform`、`fileStorage`、`timelineStore` 不按对象分类保留:数据面就是公开契约,`execHost`、`fsHost`、`store`、`timelineStore` 的操作就是它们的接口,旧名字是提供方和它的 Rust binding,调用方在进程内直接调这组操作,不再有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform`、`fileStorage` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store data faces](resource-faces.md) §6)。 +`hostPlatform`、`fsHost`、`timelineStore` 不按对象分类保留:数据面就是公开契约,它们的操作就是接口,旧名字是提供方和它的 Rust binding,调用方在进程内直接调这组操作,不再有第二套公开 API。凭据是操作内部用的能力,不是保留 `internal` 的理由。`hostPlatform`、`fsHost` 的提供方在持有资源的那个 daemon(控制节点自己的插件,或 #1296 挂载的资源 leaf);`store` 在持有 Session 状态的那个 daemon,SQLite 还是 PostgreSQL 只是实现(#1298,[resource and store data faces](resource-faces.md) §6)。 ### 3.5 热路径与顺序:待操作化 diff --git a/docs/typescript-plugin-authoring.md b/docs/typescript-plugin-authoring.md index 0d1cf4d84d..83f787bb20 100644 --- a/docs/typescript-plugin-authoring.md +++ b/docs/typescript-plugin-authoring.md @@ -290,49 +290,17 @@ export default definePlugin({ ctx.effect(() => files.close()); ctx.provide('notebook', { async read() { - return files.withLock('notebook/state.json', file => file.read()); + return files.withLock('notebook/state.json', current => ({ text: null, value: current })); }, async replace(text: string) { - return files.withLock('notebook/state.json', file => file.replace(text)); + return files.withLock('notebook/state.json', () => ({ text, value: null })); }, }); }, }); ``` -`withLock` holds the native file lease through its complete async callback. The -outer `FileResult` is the transaction result; a callback returning a `FileResult` -produces a nested result. Check each result rather than treating failure as empty -state. `read()` returns `null` only when the file is absent. `replace` atomically -writes and flushes the host's v1 envelope around your opaque text; keep your own -payload schema/version inside that text. Invalid, unversioned or unknown storage -records return `invalid_data` and preserve the original bytes. - -Do not retain a lease after its callback. `backup` uses a fresh alphanumeric/hyphen -suffix and never overwrites a backup; a retained partial backup is not proof of a -successful copy. Quiesce stops new acquisition; close joins admitted work. An -optional cancellation Promise cancels acquisition when it settles. Settle it on -ordinary completion too, so it cannot hold runtime drain open. rutis does -not encode an `AbortSignal` as this argument. - -`readBytes()` and `replaceBytes(bytes)` use the same names and lease for raw -bytes: no text envelope is involved, a text file's bytes are its stored -envelope, and a file over 8 MiB fails `invalid_data` before it is read. The -scope's `list(prefix)` returns one level of a directory, sorted, with each -entry's name relative to the authorized root and its kind; a name is the stored -components joined by `/`, ready to pass to another operation, and on Unix a -backslash is part of a name while on Windows it is a separator. `remove(name)` -removes a file or a directory tree and returns `locked` while a lease holds it -or a file beneath it. Use `scope.openRead(name)` for larger files. A missing file returns null; -a present file returns its size and a pinned reader ID for `fsHost.readAt` and -`fsHost.closeRead`. The opening row's unload closes outstanding readers. -`scope.writeStream(name, next)` pulls chunks until null and preserves the old file -on failure or cancellation. `scope.directory(name)` creates the work directory -and returns its node-local path. A text `replace` whose serialized record would -exceed the runtime's 16 MiB frame fails that call with a `BindingError` coded -`bad-value`; the file is unchanged. rutis 0.23 chunks a larger call frame up to -the deployment's `max_transfer`, so the runtime no longer refuses a call at the -16 MiB boundary; limits that a Dim face does not enforce are not guaranteed. +This section is superseded by the [PluginFiles contract](design/plugins/PluginFiles.md). Native storage locking and durability do not make remote side effects atomic. After an uncertain external outcome, use that system's reconciliation contract diff --git a/docs/zh/design/appserver/mcp-oauth.md b/docs/zh/design/appserver/mcp-oauth.md index a4864604b9..adf67855b6 100644 --- a/docs/zh/design/appserver/mcp-oauth.md +++ b/docs/zh/design/appserver/mcp-oauth.md @@ -33,7 +33,7 @@ OAuth 协议步骤来自工作区里已有的官方 Rust SDK:rmcp 的 `auth` f | [rmcp 版本](../../../../crates/dim-app-server/Cargo.toml),feature `auth`(`src/transport/auth.rs`) | `auth` 模块覆盖元数据发现、DCR 与 CIMD 客户端选择、PKCE 与 `state`、带 `resource` 和 `iss` 的授权码交换,以及带轮换的刷新。`CredentialStore` 与 `StateStore` trait 可替换。它与传输层共用同一个 reqwest 0.13 | 协议引擎;缺口见附录 A | | Claude Code(`/mcp`、`claude mcp login`、[文档](https://code.claude.com/docs/en/mcp)) | `.mcp.json` 中的 `oauth` 对象:`clientId`、`callbackPort`、`authServerMetadataUrl`、`scopes`。重定向为 `http://localhost:PORT/callback`;曾改成 `127.0.0.1`,使按注册 URI 精确匹配的服务器失败,后已改回。重定向失败时粘贴回调 URL。客户端密钥不进配置。遇到 `401` 先刷新,再重试一次 | `oauth` 的字段名和类型、重定向形式、粘贴兜底、密钥不进配置 | | MCP TypeScript 与 Python SDK(`OAuthClientProvider`、`TokenStorage`) | 存储与重定向处理由宿主注入。凭据带 issuer 标记,不匹配时丢弃。`invalid_client` 清除注册,`invalid_grant` 清除令牌 | 所有者提供的存储、issuer 绑定、清除规则 | -| Dim 账号登录(`account.login.browser.begin/complete`、`managed_oauth.rs`、`dim-cli/src/login.rs`) | 守护进程返回 `{attemptId, authorizationUrl, expiresAt}`。客户端把粘贴的回调 URL 送回,输入时隐藏回显。令牌存于 home 根目录的 `auth.json`,经 FileStorage 租约原子替换为 0600 | 尝试的形状、粘贴输入、存储方式 | +| Dim 账号登录(`account.login.browser.begin/complete`、`managed_oauth.rs`、`dim-cli/src/login.rs`) | 守护进程返回 `{attemptId, authorizationUrl, expiresAt}`。客户端把粘贴的回调 URL 送回,输入时隐藏回显。令牌存于 home 根目录的 `auth.json`,经 FileStorage 的 `claim`/`update` 原子替换为 0600 | 尝试的形状、粘贴输入、存储方式 | ## 3. 结构 @@ -81,7 +81,7 @@ OAuth 协议步骤来自工作区里已有的官方 Rust SDK:rmcp 的 `auth` f - **唯一写入者。** 只有 Mcp 写这个文件。 - **自足。** 记录带有令牌端点、撤销端点和客户端的认证方式,因此刷新和登出不需要重新发现。 记录在尝试完成时连同客户端和令牌一起写入;放弃的尝试不留下任何东西。 -- **写入路径。** 写入时取存储的 FileStorage 锁,重读文件,只替换自己 key 的记录,再以 0600 +- **写入路径。** 写入时按 FileStorage 的 `update`(文件键),重读文件,只替换自己 key 的记录,再以 0600 原子替换文件。Windows 上沿用 FileStorage 的 DACL 处理。替换已经生效、只是同步失败的写入算作已 写入:读者已经看到它,崩溃时丢失它的结果与 §7 中进程被杀相同。 - **令牌请求持锁。** 授权码交换、刷新和撤销从重读开始,经过请求,到替换为止一直持有这把锁, diff --git a/docs/zh/design/appserver/session-deletion-and-fork.md b/docs/zh/design/appserver/session-deletion-and-fork.md index c9b49c8e05..17d8cef3d8 100644 --- a/docs/zh/design/appserver/session-deletion-and-fork.md +++ b/docs/zh/design/appserver/session-deletion-and-fork.md @@ -411,7 +411,7 @@ S5c 与 S5a 一样只实现控制节点。在控制节点上,FileStorage 正 | [AcpGateway](../plugins/AcpGateway.md)、[RemoteGateway](../plugins/RemoteGateway.md) | 原文说分叉时重置预设,#26 已改为:预设随事实一起复制 | | [文档索引](../../../INDEX.md) | 链接到本页 | | [Session 文件](session-files.md) | §5.3 和 §12 原说节点离线时删除照样提交。这对其中的 Session 文件步骤成立;整个删除还会先在节点上移除命令输出(§11)。§5.2、§5.4 和 §6 不变,就是本页执行的步骤;§5.4 注明移除现在会同步 | -| [FileStorage](../../../architecture/rust-agent/plugins/FileStorage.md) | 移除会同步被移除条目的父目录(§14) | +| [FileStorage](../../../architecture/rust-agent/plugins/FileStorage.md) | 本节由 FileStorage 契约取代(§14)。 | | [单树装配](../../../architecture/rust-agent/single-tree.md) | `Agents` 重载一行:重载结算只停止重载中的 Session 所领导的成员(#127) | | [Session 访问 A.3](../contracts/session-access.md#a3-sessionconfig-字段) | 状态说明:分叉复制存储的 `SessionConfig` 文本,`interactive` 的省略规则随之保留 | @@ -442,7 +442,7 @@ S5c 与 S5a 一样只实现控制节点。在控制节点上,FileStorage 正 | 对象 | 需求 | 状态 | | --- | --- | --- | -| FileStorage | `remove` 在报告成功之前同步被移除条目的父目录(条目原本就不存在时也同步),同步失败时返回 `Unsynced`。Windows 没有目录同步,与 `replace` 一样依赖 NTFS 元数据日志。用于让删除的移除在提交之前落盘(§4) | 已在 S5c 中实现([FileStorage](../../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal)) | +| FileStorage | 本节由 [FileStorage 契约](../../../architecture/rust-agent/plugins/FileStorage.md#listing-and-removal) 取代。 | 已在 S5c 中实现 | | Loop、InputQueue、BackgroundExec | 作用于固定切点的只读静止点检查:没有未结束的轮次,没有等着驱动轮次的 Queue 或 Steer 输入,每个后台任务都已结束且其唤醒已发出(§6.2)。某个能力的重载规则以后要从其他事实开始工作时,就把这些事实加入检查,分叉因此始终不会开始任何工作 | Agents 通过 Timeline 数据面查询这些能力的公开事实(§16 D1)。某条重载规则以后要从其他事实开始工作时,由其所有者扩展 [agents/fork.rs](../../../../crates/dim-app-server/src/agents/fork.rs) 中的检查。BackgroundExec 拥有包含代边界的共享唤醒谓词 | | Collaboration | 分支重建时,已送达但没有结果的请求以失败结算;只有成员关系指明本 Session 是 leader 时才停止该成员。一般地,重载结算只处理本 Session 持有的资源。原先重建会停止事实中指名的任何已加载 Session([collaboration.rs](../../../../crates/dim-app-server/src/collaboration.rs) 的 `rebuild`),因此分叉一个 leader 会停止源的成员 | 已实现([#127](https://github.com/arcships/dim/issues/127))。#127 之前,这种重载会停止已加载的该成员;现在成员自身重载规则启动的工作会继续运行,leader 已把请求结算为失败,成员发给 leader 分叉的 `agent` 消息因没有成员关系而被拒绝(`TeamMemberNotFound`)([#97 评审](https://github.com/arcships/dim/pull/97))。重启后 Team 保留:关系由存储的 leader 重建([Collaboration §6](../plugins/Collaboration.md#6-委派的所有权与寿命))。验收第 7 条 | | Goal(P5,[#69](https://github.com/arcships/dim/issues/69)) | 复制来的目标不得在 F 中驱动轮次,也不是 F 的目标。分叉在其事务中、复制来的事实之后写 `session/forked`(§6.5);Goal 从该事实之后折叠 `main`,并对复制来的生效目标清除一次([Goal](../plugins/Goal.md) A11) | 随 Goal 验收实现([#209](https://github.com/arcships/dim/pull/209)) |