Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
b129465
design(fileStorage): target contract
eric8810 Nov 23, 2026
e26093e
docs(fileStorage): name the fact owner
eric8810 Nov 23, 2026
37bf11a
design(fileStorage): data-shaped writes
eric8810 Nov 23, 2026
54e2390
design(fileStorage): align add_root errors and the binding note
eric8810 Nov 23, 2026
5237375
design(fileStorage): callbacks for writes and updates
eric8810 Nov 23, 2026
1bb2dac
design(fileStorage): name the caller's own revision
eric8810 Nov 23, 2026
0bae617
design(fileStorage): fold the revision check into the business helper
eric8810 Nov 23, 2026
ab89e22
design(fileStorage): whole-document read and unbounded waits
eric8810 Nov 23, 2026
c0c7e35
design(fileStorage): answer the external review
eric8810 Nov 23, 2026
6c59e95
design(fileStorage): answer the round-four review
eric8810 Nov 24, 2026
db635d5
design(fileStorage): claim the account marker for refreshes
eric8810 Nov 24, 2026
5a53564
docs(fileStorage): state the page-past-end rule SessionFiles relies on
eric8810 Nov 24, 2026
0f9db4f
design(fileStorage): close the round-five findings
eric8810 Nov 24, 2026
2ff358b
docs(fileStorage): move the owner contract to the plugin page
eric8810 Nov 24, 2026
b4eb832
docs(fileStorage): one account lock and claim settlement
eric8810 Nov 24, 2026
ad78d3e
docs(fileStorage): settle the pre-review findings
eric8810 Nov 24, 2026
08c34d2
docs(fileStorage): settle the second pre-review
eric8810 Nov 24, 2026
ed23162
docs(pluginFiles): add the owner contract and retire the lease
eric8810 Nov 24, 2026
5b56b49
docs(fileStorage): claim only on update and a single Workflow commit
eric8810 Nov 24, 2026
e21dc90
docs(fileStorage): fix the write examples after the claim move
eric8810 Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 1 addition & 99 deletions crates/dim-app-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<FileScope>` 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-<UUID>`. 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

Expand Down
4 changes: 2 additions & 2 deletions crates/dim-oauth/docs/runtime-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ terminal and returns `cancelled`. DimOAuth never writes Session metadata or choo

## Account record

`<product home>/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.
`<product home>/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).

Expand Down
Loading