From 74957660caa628b31079725c552beb47c46ebaa9 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 14:32:13 +0800 Subject: [PATCH 1/8] design(settings): owner contracts for Settings and the settings sections MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the target contracts for Settings, its client namespace and the settings section owners under design rules §7. The Settings contract replaces the settingsService owner API and the settings facade with one service: register returns a source id, owners read a document as a value and change it through a callback that the owner runs under its exclusion, user edits carry the draft revision, the agent reads a redacted document and sets one member, and the authorized-project table is a value plus one admission operation. workflowFiles, commandRules and the three prompt host names are removed; the workflow definition files, the command rules value and the prompt texts are requested from their owners. Requirements raised to SessionStore, Provider and Workflow are stated in the Settings contract. Refs #2017 Refs #2015 --- .../plugins/CollaborationModelPolicy.md | 140 ++++++++ docs/design/plugins/ExecutionSettings.md | 120 +++++++ docs/design/plugins/ModelLog.md | 117 +++++++ docs/design/plugins/PermissionRules.md | 141 ++++++++ docs/design/plugins/PromptSettings.md | 124 +++++++ .../plugins/PromptSuggestionSettings.md | 120 +++++++ docs/design/plugins/ProviderSettings.md | 115 ++++++ docs/design/plugins/README.md | 9 + docs/design/plugins/Settings.md | 330 ++++++++++++++++++ docs/design/plugins/SettingsMethods.md | 111 ++++++ 10 files changed, 1327 insertions(+) create mode 100644 docs/design/plugins/CollaborationModelPolicy.md create mode 100644 docs/design/plugins/ExecutionSettings.md create mode 100644 docs/design/plugins/ModelLog.md create mode 100644 docs/design/plugins/PermissionRules.md create mode 100644 docs/design/plugins/PromptSettings.md create mode 100644 docs/design/plugins/PromptSuggestionSettings.md create mode 100644 docs/design/plugins/ProviderSettings.md create mode 100644 docs/design/plugins/Settings.md create mode 100644 docs/design/plugins/SettingsMethods.md diff --git a/docs/design/plugins/CollaborationModelPolicy.md b/docs/design/plugins/CollaborationModelPolicy.md new file mode 100644 index 0000000000..167f52cfe0 --- /dev/null +++ b/docs/design/plugins/CollaborationModelPolicy.md @@ -0,0 +1,140 @@ +# CollaborationModelPolicy + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [Subagent model policy](../subagent-model-policy.md). + +CollaborationModelPolicy owns the `collaboration` document: which model a new Collaboration member runs. Collaboration asks this owner for the policy each time it creates a member. This document is the owner's target contract; it replaces the store read with the policy's own value read. + +## Use and scope: responsibility split + +CollaborationModelPolicy owns: + +- The `collaboration` source: its file, its document type and its validation — a `fixed` policy needs both a provider id and a model id. +- The value `policy`: `agent` (the profile's model, or the existing default), `inherit` (the requesting branch's adopted model) or `fixed {model}`. +- The `collaboration` management namespace: `collaboration.model_policy` and `collaboration.set_model_policy` for a local client. + +Callers keep: + +- What each policy means when a member starts: Collaboration's business, including the startup override that always inherits. +- When the policy is read: at each member creation. +- What an absent policy means: `agent`, as if the user had chosen it. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| Collaboration needs the policy for a new member | No: the file, the type and its validation belong to this owner | `policy` | +| Collaboration uses `agent` when nothing is stored | Yes: the read answers the default document | Business | +| A local client reads the policy with a draft base | No: the client reaches this owner's namespace only | `collaboration.model_policy` | +| A local client replaces the policy at a revision | No: a stale draft is reported | `collaboration.set_model_policy` | +| A consumer reacts to a changed policy | Yes: follow the `settings/collaboration` fact and read again | Business | + +## Caller example + +Collaboration reads the policy when it creates a member. + +```rust +let policy = if startup { + ModelPolicy::Inherit +} else { + collaboration_policy.policy(cancelled.clone()).await?.policy +}; +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `collaboration` source and `read`/`change` for its value. +- `managementMethods`: the two client methods. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `policy` | The policy in force now | `{}` | `{policy}` | The caller's token; nothing changes | `failed`, `cancelled` | +| `collaboration.model_policy` | The policy with the revision a draft starts from | `{}` | `{revision, policy}` | The call is dropped | `collaboration_model_policy_failed`, reloading | +| `collaboration.set_model_policy` | Replace the policy at the revision read | `{expectedRevision, policy}` | `{revision}` | The call is dropped | invalid params, `collaboration_model_policy_conflict`, `collaboration_model_policy_failed`, reloading | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Use the default policy (`agent`) for this member; the member still starts | +| `cancelled` | The member creation is abandoned with the call | +| invalid params | Fix the request: an unknown mode, or a `fixed` policy without a provider and a model | +| `collaboration_model_policy_conflict` | Read again; the user's draft is stale | +| `collaboration_model_policy_failed` | Read again before retrying | +| reloading | The daemon is restarting; retry after it is back | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `policy` | Read the source through [Settings](Settings.md), return the policy | The call ends `cancelled` | The call ends `failed`; the member uses the default policy | Settings | +| `collaboration.model_policy`, `collaboration.set_model_policy` | [Settings](Settings.md) `read_user`/`replace_user`, map the reply and the errors | The call is dropped; a write before the commit does not happen | In-flight calls finish or end `reloading` | Settings | + +## Exceptions with reasons + +- The policy document is a Rust type rather than a JSON Schema: the closed mode set with a typed model is the owner's validation, so the client reaches it through this owner's namespace. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document; not a Capability. | +| §2 scopes | Process: the policy applies to every new member of the process. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | Settings publishes the `settings/collaboration` fact; this owner writes none. | +| §4 rule 6 | The policy never enters model context. | +| §4 rule 7 | Collaboration calls `policy`; the client calls the namespace; no caller names the file or the type. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Replies are values; no object or path crosses. | +| §7 no proxy | The policy belongs to this owner; Collaboration asks this owner, not the store. | +| §7 one face | One service value read and one namespace; no second read path. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The file, the type and the validation stay with this owner. | +| §7 one change | The new value read, Collaboration's migration and the store read's deletion are one change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | Collaboration depends on this owner's value; this owner depends on Settings. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use dim_agent_types::ModelId; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "mode", rename_all = "lowercase", deny_unknown_fields)] +pub enum ModelPolicy { + Agent {}, + Inherit {}, + Fixed { model: ModelId }, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Policy { + pub policy: ModelPolicy, +} + +#[derive(Debug, thiserror::Error)] +pub enum CollaborationPolicyError { + #[error("the collaboration model policy could not be read: {0}")] + Failed(String), + #[error("the collaboration model policy read was cancelled")] + Cancelled, +} + +impl PublicService for CollaborationModelPolicy {} + +#[rutis::service(name = "collaborationPolicy")] +impl CollaborationModelPolicy { + pub async fn policy(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/ExecutionSettings.md b/docs/design/plugins/ExecutionSettings.md new file mode 100644 index 0000000000..34352b8343 --- /dev/null +++ b/docs/design/plugins/ExecutionSettings.md @@ -0,0 +1,120 @@ +# ExecutionSettings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Decision: [ADR 011](../../adr/011-execution-settings.md). + +ExecutionSettings owns the `execution` document and the process execution switches it carries. The plugin also registers the `settings` tool ([AgentSettings](AgentSettings.md)) and the execution snapshot branch ([EnvironmentSettings](EnvironmentSettings.md)); those documents own the tool and the snapshot contract. This document is the owner's target contract; it replaces the `executionSettingsHost` name with `executionSettings`. + +## Use and scope: responsibility split + +ExecutionSettings owns: + +- The `execution` source: its file, its schema, and the two switches `sandbox` and `network`, both defaulting to `false` and changed only by the user. +- The value `{sandbox, network}`: the switches in force now, read at each use. + +Callers keep: + +- When the switches take effect: at process preparation; a running process, including the persistent shell, keeps the boundary it started with. +- What a switch means for a command: the sandbox and network properties of a spawn are HostPlatform's business. +- When to show the value to the model: the snapshot branch and the tool are their own designs. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A process part reads the boundary at process preparation | No: the file, its schema and the user-only rule belong to this owner | `read` | +| The model-facing tool lists and reads the switches | Yes: the tool calls the same read | AgentSettings | +| The branch shows a snapshot on open and on a change | Yes: the branch calls the same read and follows the fact | EnvironmentSettings | +| A user changes the switches | Yes: the user edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | + +## Caller example + +HostPlatform reads the switches when it prepares a process. + +```rust +let switches = execution_settings.read(cancelled.clone()).await.map_err(|error| { + HostError::failed(format!("execution settings: {error}")) +})?; +// A missing or unreadable source fails preparation; it never runs unsandboxed. +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `execution` source and `read` for its value. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `read` | The switches in force now | `{}` | `{sandbox, network}` | The caller's token; nothing changes | `failed` | + +`failed` covers a read that could not produce the document: an unreadable source, a cancelled read, or an absent registration. The reply is the document itself, so no member is invented. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Fail process preparation; never prepare a process without knowing the boundary | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `read` | Read the source through [Settings](Settings.md), return the two switches | The call ends `failed` | The call ends `failed`; the caller fails preparation | Settings | + +## Exceptions with reasons + +- A missing value fails preparation instead of defaulting to unsandboxed: the built-in default is already "off", and silently running unsandboxed is the one failure the feature exists to prevent. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | The process part owns the document. The snapshot branch writes one input at branch open and on a change, so that part is a Capability ([EnvironmentSettings](EnvironmentSettings.md)); the tool part is a Session tool registration, not a Capability. | +| §2 scopes | The document and the value are process state; the branch part reads the value and appends an input to its branch. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | The snapshot is an input message, not a command event. | +| §4 rule 6 | The value reaches the model as an appended input; no Prompt source and no second context path. | +| §4 rule 7 | HostPlatform calls the read; no caller names the file or the schema. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Replies are values; no object or path crosses. | +| §7 no proxy | The switches belong to this owner; consumers ask this owner. | +| §7 one face | One service with one read; the `executionSettingsHost` name is deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | Nothing of the source, its file or the user-only rule reaches the caller. | +| §7 one change | The name change and its callers migrate in the same change. | +| ADR 002 D1 | Process scope: the switch applies to the process, not a Session. | +| ADR 002 D3 | HostPlatform depends on the port; the port has no Settings or file dependency. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None new. HostPlatform's read at process preparation is unchanged in shape; only the service name changes. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Switches { + pub sandbox: bool, + pub network: bool, +} + +#[derive(Debug, thiserror::Error)] +pub enum ExecutionSettingsError { + #[error("the execution settings could not be read: {0}")] + Failed(String), +} + +impl PublicService for ExecutionSettings {} + +#[rutis::service(name = "executionSettings")] +impl ExecutionSettings { + pub async fn read(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/ModelLog.md b/docs/design/plugins/ModelLog.md new file mode 100644 index 0000000000..b029211e8a --- /dev/null +++ b/docs/design/plugins/ModelLog.md @@ -0,0 +1,117 @@ +# ModelLog + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [Model request log](../appserver/model-log.md). + +ModelLog owns the `model-log` document: whether the process records its model wire exchanges. The recorder itself is aimux's and writes the JSONL file under the home root. This document is the owner's target contract; it replaces the push into the recorder with a value read. + +## Use and scope: responsibility split + +ModelLog owns: + +- The `model-log` source: its file, its schema and the `enabled` switch, defaulting to `false`. +- The value `recording`: the directory the recorder writes to when the switch is on, or none when off. + +Callers keep: + +- The recording format, the file name and the write path: aimux's recorder. +- When the value is read: at each request, or after following the `settings/model-log` fact. +- Failing or not failing a request on a read error: a read error records nothing. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The request recorder needs its destination | No: the file and the switch belong to this owner | `recording` | +| The recorder is off when unset | Yes: the read answers none | Business | +| A user turns recording on or off | Yes: the user edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | + +## Caller example + +The recorder reads the destination while it starts a request. + +```rust +let destination = model_log.recording().await.ok().flatten(); +if let Some(directory) = destination.directory { + // aimux owns the file under this directory. +} +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `model-log` source and `read` for its value. +- FileStorage: `root_path` for the home root, once, to build the destination directory. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `recording` | Where the request recorder writes now | `{}` | `{directory}` or none | The caller's token; nothing changes | `failed` | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Record nothing for this request; the model request itself proceeds | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `recording` | Read the source through [Settings](Settings.md), answer the directory or none | Nothing changes; the caller records nothing | The call ends `failed`; the caller records nothing | Settings | + +## Exceptions with reasons + +- The directory is computed from the home root at each read instead of being pushed into the recorder: the recorder belongs to aimux, and a value read keeps the write inside its owner. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document; not a Capability. | +| §2 scopes | Process: the switch applies to the whole process. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers and the home root FileStorage answers. | +| §4 rule 1 | Settings publishes the `settings/model-log` fact; this owner writes none. | +| §4 rule 6 | The switch never enters model context. | +| §4 rule 7 | The recorder calls the read; no caller names the file or the schema. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | The reply is a value; no path crosses as a resource. | +| §7 no proxy | The switch and the destination belong to this owner. | +| §7 one face | One service with one read; the old push into the process recorder is deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The file, the switch and the home root stay with their owners. | +| §7 one change | The new read, aimux's migration and the deletion of the setter are one change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | The recorder depends on the value; ModelLog depends on Settings and FileStorage. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- **Provider, [#2019](https://github.com/arcships/dim/issues/2019):** aimux's request recorder reads this value instead of receiving a process-global destination; a read error records nothing and never fails a request. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Recording { + pub directory: Option, +} + +#[derive(Debug, thiserror::Error)] +pub enum ModelLogError { + #[error("the model-log setting could not be read: {0}")] + Failed(String), +} + +impl PublicService for ModelLog {} + +#[rutis::service(name = "modelLog")] +impl ModelLog { + pub async fn recording(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/PermissionRules.md b/docs/design/plugins/PermissionRules.md new file mode 100644 index 0000000000..8c011cea5e --- /dev/null +++ b/docs/design/plugins/PermissionRules.md @@ -0,0 +1,141 @@ +# PermissionRules + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [Permission command rules](../appserver/permission-command-rules.md). + +PermissionRules owns the `permission` document: the user's command rules. The permission decision that applies the rules is the `CommandRules` capability; this owner answers the rules. This document is the owner's target contract; it replaces the `commandRules` Session service and the Session part that read the rules from the store. + +## Use and scope: responsibility split + +PermissionRules owns: + +- The `permission` source: its file, its document type (`command_rules`) and its validation — at least one word per rule, no shell separator. +- The value `rules`: the user's command rules as stored now. +- The `permission` management namespace: `permission.rules` and `permission.set_rules` for a local client. + +Callers keep: + +- The permission decision: whether a command is allowed, asked or denied, and how a rule matches a command. +- When the rules are read: at each decision. +- What a conflict means for the user's edit: the draft is stale; read again. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The permission decision needs the user's rules | No: the document, its type and its validation belong to this owner | `rules` | +| A local client reads the rules with a draft base | No: the client reaches this owner's namespace only | `permission.rules` | +| A local client replaces the rules at a revision | No: the whole list is replaced and a stale draft is reported | `permission.set_rules` | +| A consumer reacts to a changed rule set | Yes: follow the `settings/permission` fact and read again | Business | + +## Caller example + +The permission decision reads the rules once per call. + +```rust +let rules = permission_rules.rules(cancelled.clone()).await?; +let decision = decide(&rules.rules, &command); +``` + +The CLI replaces the list with the revision it read. + +```rust +client + .typed( + "permission.set_rules", + json!({"expectedRevision": revision, "commandRules": rules}), + ) + .await?; +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `permission` source and `read`/`change` for its value. +- `managementMethods`: the two client methods. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `rules` | The user's command rules as stored now | `{}` | `{rules}` | The caller's token; nothing changes | `failed`, `cancelled` | +| `permission.rules` | The rules with the revision a draft starts from | `{}` | `{revision, commandRules}` | The call is dropped | `permission_rules_failed`, reloading | +| `permission.set_rules` | Replace the whole list at the revision read | `{expectedRevision, commandRules}` | `{revision}` | The call is dropped | invalid params, `permission_rules_conflict`, `permission_rules_failed`, reloading | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Deny or ask for the command; a rules read that failed never allows it | +| `cancelled` | The decision is abandoned with the call | +| invalid params | Fix the request: a rule without a command word, or with a shell separator | +| `permission_rules_conflict` | Read again; the user's draft is stale | +| `permission_rules_failed` | Read again before retrying | +| reloading | The daemon is restarting; retry after it is back | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `rules` | Read the source through [Settings](Settings.md), return the list | The call ends `cancelled` | The call ends `failed`; the decision denies or asks | Settings | +| `permission.rules`, `permission.set_rules` | [Settings](Settings.md) `read_user`/`replace_user`, map the reply and the errors | The call is dropped; a write before the commit does not happen | In-flight calls finish or end `reloading` | Settings | + +## Exceptions with reasons + +- The rules' validation is Rust code rather than a JSON Schema: a shell separator and an empty command word are expressible only as code, so the source is a Rust document and the client reaches it through this owner's namespace instead of `settings.*`. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document. The `CommandRules` capability owns the decision and folds no rule state: it reads this owner's value. | +| §2 scopes | Process: the rules apply to every Session. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | Settings publishes the `settings/permission` fact; this owner writes none. | +| §4 rule 6 | The rules never enter model context. | +| §4 rule 7 | The decision calls `rules`; the client calls the namespace; no caller names the file or the type. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Replies are values; no object or path crosses. | +| §7 no proxy | The rules belong to this owner; the decision asks this owner, not the store, and the `commandRules` Session service is deleted. | +| §7 one face | One service for the value and one namespace for the client; no second read path. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The file, the type and the validation stay with this owner. | +| §7 one change | The new value read, the decision's migration and the deletion of `commandRules` are one change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | The decision depends on this owner's value; this owner depends on Settings. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use dim_agent_types::CommandRule; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Rules { + pub rules: Vec, +} + +#[derive(Debug, thiserror::Error)] +pub enum PermissionRulesError { + #[error("the command rules could not be read: {0}")] + Failed(String), + #[error("the command rules read was cancelled")] + Cancelled, +} + +impl PublicService for PermissionRules {} + +#[rutis::service(name = "permissionRules")] +impl PermissionRules { + pub async fn rules(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` + +The client methods are registered with `managementMethods`; their request and reply types are the JSON shapes in the operations table. diff --git a/docs/design/plugins/PromptSettings.md b/docs/design/plugins/PromptSettings.md new file mode 100644 index 0000000000..1c2b078aa7 --- /dev/null +++ b/docs/design/plugins/PromptSettings.md @@ -0,0 +1,124 @@ +# PromptSettings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature design: [Prompt overrides](../appserver/prompt-overrides.md). + +PromptSettings owns the `prompts` document and the three model-facing texts it carries: the base identity and rules, the compaction summary prompt, and the Skills instructions. This document is the owner's target contract; it replaces the three `*PromptSettingsHost` services with one service. + +## Use and scope: responsibility split + +PromptSettings owns: + +- The `prompts` source: its file, its schema, and the rule that each of the three texts is non-empty and changed only by the user. +- The three values `base`, `summary` and `skills`: the text in force, or none when the user set no override. + +Callers keep: + +- The precedence: a factory configuration outranks the user's text, which outranks the built-in text. The consumer applies the precedence and keeps the built-in text on a missing value or a failed read. +- When the text is adopted: at the Session part's `apply`, fixed for that Session; a change applies to Sessions loaded after it. +- The text's meaning and how it is composed into the prompt. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A capability reads its own override text before a Session starts | No: the document belongs to this owner, and the consumer must not name another text's member | One read per text on the owner's service | +| A capability falls back when the user set nothing | Yes: the read answers none | Business | +| A user edits a text | Yes: the client edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | +| A capability reacts to a changed text mid-Session | Yes: the value is fixed at `apply`; a changed text applies to the next Session | Business | + +## Caller example + +PromptSources reads the base text once, while its Session part applies. + +```rust +let base = prompt_settings.base().await.ok().flatten(); +let text = factory.base.or(base).unwrap_or_else(|| BUILT_IN.into()); +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `prompts` source and `read` for its value. PromptSettings registers the source from its own process row and keeps the source id. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `base` | The user's replacement of `dim/base`, when set | `{}` | `{text}` or none | The caller's token; nothing changes | `failed` | +| `summary` | The user's replacement of the compaction summary prompt, when set | `{}` | `{text}` or none | The caller's token; nothing changes | `failed` | +| `skills` | The user's replacement of the Skills instructions, when set | `{}` | `{text}` or none | The caller's token; nothing changes | `failed` | + +A read returns the member as stored after the schema check; an absent member is none, never an empty string. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Use the factory configuration or the built-in text; the Session opens. The message names the source, never the text. | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `base`, `summary`, `skills` | Read the source through [Settings](Settings.md), return the member or none | Nothing changes | The call ends `failed`; the consumer keeps its built-in text | Settings | + +## Exceptions with reasons + +- The three texts share one document and one registering row: a file has one owner, while each text belongs to a different capability; the schema keeps each member independent, and a user-only member cannot be changed by the owner. +- A read failure does not fail the Session: the text is policy with a safe default, and the consumer keeps the built-in text. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part that owns a document. It publishes facts through Settings and folds no state: not a Capability. | +| §2 scopes | Process: the document is shared by every Session; the values are read at a Session part's `apply`. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | Settings publishes the `settings/prompts` fact; this owner writes none. | +| §4 rule 6 | The text reaches the model through the existing adopted prompt sources; no context path is added. | +| §4 rule 7 | Consumers call the three reads; no consumer names the other members. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Replies are values; no object or path crosses. | +| §7 no proxy | The texts belong to this owner; the consumers ask this owner, not the store. | +| §7 one face | One service with three reads, one per text; the three `*SettingsHost` names are deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | Nothing of the store, the schema or the file name reaches the consumer. | +| §7 one change | The one service replaces the three names, and all three consumers migrate in the same change. | +| ADR 002 D1 | Process scope: the setting is shared configuration, not Session state. | +| ADR 002 D3 | The consumers' crates depend on the port type, not on the App Server. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None new. The consumers ([PromptSources](../../architecture/rust-agent/plugins/PromptSources.md), Skills and ContextCompaction) call one service name instead of three; each consumer's own contract records the fallback rule. + +## Binding appendix + +The three reads are one service on the owner type; the old `BasePromptSettingsHost`, `SkillsInstructionsSettingsHost` and `SummaryPromptSettingsHost` types and their traits are deleted. + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Text { + pub text: Option, +} + +#[derive(Debug, thiserror::Error)] +pub enum PromptSettingsError { + #[error("the prompts setting could not be read: {0}")] + Failed(String), +} + +impl PublicService for PromptSettings {} + +#[rutis::service(name = "promptSettings")] +impl PromptSettings { + pub async fn base(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn summary(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn skills(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/PromptSuggestionSettings.md b/docs/design/plugins/PromptSuggestionSettings.md new file mode 100644 index 0000000000..a476f3aeaa --- /dev/null +++ b/docs/design/plugins/PromptSuggestionSettings.md @@ -0,0 +1,120 @@ +# PromptSuggestionSettings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [PromptSuggestion](../../architecture/rust-agent/plugins/PromptSuggestion.md). + +PromptSuggestionSettings owns the `prompt-suggestion` document and the value the Session part reads at each decision. This document is the owner's target contract; it replaces the `promptSuggestionSettingsHost` name with `promptSuggestionSettings`. + +## Use and scope: responsibility split + +PromptSuggestionSettings owns: + +- The `prompt-suggestion` source: its file, its schema, the switch `enabled` and the length limit `maxChars` in `[10, 200]`, defaulting to `false` and `80`. +- The value `{enabled, maxChars}` as stored now. + +Callers keep: + +- When the feature offers a suggestion and how the reply is validated. +- That a missing port or a failed read turns the feature off. +- The text the model sees; the limit bounds the reply, not the instruction. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| The Session part reads the switch and the limit at each decision | No: the file, the schema and the range belong to this owner | `read` | +| The Session part treats an absent port as "off" | Yes: the read is optional at assembly; a failed read is its own error | Business | +| A user changes the switch or the limit | Yes: the user edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | + +## Caller example + +PromptSuggestion reads the value before it decides. + +```rust +let settings = settings_host.read(token.clone()).await?; +if !settings.enabled { + return Ok(Decision::Refused("disabled")); +} +let max_chars = settings.max_chars; // the owner's schema already bounded it +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `prompt-suggestion` source and `read` for its value. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `read` | The switch and the limit in force now | `{}` | `{enabled, maxChars}` | The caller's token; nothing changes | `failed` | + +The reply carries both members because the schema gives both a default; a document that misses one is invalid, not a value with a missing field. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Turn the feature off for this decision; the message names the source | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `read` | Read the source through [Settings](Settings.md), return both members | The call ends `failed`; the feature stays off for this decision | The call ends `failed`; the feature stays off | Settings | + +## Exceptions with reasons + +- The assembler may leave the port absent: an evaluation or a host without Settings then keeps the feature off, so the read is optional at assembly. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document; the Session part that reads it is a Capability of the PromptSuggestion feature, designed in that plugin's page. | +| §2 scopes | The document and the value are process state; the Session part reads the value. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | No event from this owner. | +| §4 rule 6 | The value reaches the model through the feature's own request; no context path is added. | +| §4 rule 7 | The Session part calls the read; no caller names the file or the schema. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | Request and reply are data; no object or path crosses. | +| §7 no proxy | The value belongs to this owner. | +| §7 one face | One service with one read; `promptSuggestionSettingsHost` is deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The range and the defaults stay in this owner's schema; the consumer does not clamp or fill them. | +| §7 one change | The name change and its caller migrate in the same change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | The Session part depends on the port type, not on the App Server. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SuggestionSettings { + pub enabled: bool, + pub max_chars: u32, +} + +#[derive(Debug, thiserror::Error)] +pub enum PromptSuggestionSettingsError { + #[error("the prompt-suggestion setting could not be read: {0}")] + Failed(String), +} + +impl PublicService for PromptSuggestionSettings {} + +#[rutis::service(name = "promptSuggestionSettings")] +impl PromptSuggestionSettings { + pub async fn read(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/ProviderSettings.md b/docs/design/plugins/ProviderSettings.md new file mode 100644 index 0000000000..eae436f504 --- /dev/null +++ b/docs/design/plugins/ProviderSettings.md @@ -0,0 +1,115 @@ +# ProviderSettings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [Provider management](../appserver/provider-management.md) §2. + +ProviderSettings owns the `provider` document: the User-Agent dim puts on its model requests when the operator replaces the built-in one. The document holds no Provider record; a record's own `headers` stay that record's, and a User-Agent there still wins for that Provider alone. This document is the owner's target contract; it replaces the push into the process identity with a value read. + +## Use and scope: responsibility split + +ProviderSettings owns: + +- The `provider` source: its file, its schema, the `userAgent` member and the rule that only the user changes it. +- The value `userAgent`: the operator's replacement, or none when unset. The environment variable `DIM_USER_AGENT` still wins when set. + +Callers keep: + +- Which request carries which User-Agent: Provider's model request, including a record's own `headers`. +- When the value is read: at request time, or after following the `settings/provider` fact. +- Failing or not failing a request on a read error: a read error keeps the built-in User-Agent. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A model request needs the operator's User-Agent | No: the file and the user-only rule belong to this owner | `user_agent` | +| A model request keeps the built-in User-Agent when unset | Yes: the read answers none | Business | +| A user replaces the User-Agent | Yes: the user edits the source through [Settings](Settings.md) and [SettingsMethods](SettingsMethods.md) | Business | +| The request path learns of a change | Yes: follow the `settings/provider` fact and read again | Business | + +## Caller example + +Provider reads the value when it builds a request. + +```rust +let configured = provider_settings.user_agent().await.ok().flatten(); +let user_agent = configured.unwrap_or_else(|| dim_user_agent()); +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `register` for the `provider` source and `read` for its value. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `user_agent` | The operator's User-Agent replacement, when set | `{}` | `{userAgent}` or none | The caller's token; nothing changes | `failed` | + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `failed` | Use the built-in User-Agent; never fail the model request for this setting | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `user_agent` | Read the source through [Settings](Settings.md), return the member or none | Nothing changes; the caller uses the built-in value | The call ends `failed`; the caller uses the built-in value | Settings | + +## Exceptions with reasons + +- The value is read per request instead of being published into the process identity: the identity belongs to Provider, and a value read keeps the write inside its owner. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part owning a document; not a Capability. | +| §2 scopes | Process: the value applies to every request of this process. | +| §3 orthogonality | No other owner's state beyond the Settings source it registers. | +| §4 rule 1 | Settings publishes the `settings/provider` fact; this owner writes none. | +| §4 rule 6 | The value never enters model context; it is a request header. | +| §4 rule 7 | Provider calls the read; no caller names the file or the schema. | +| §4 rule 8 | No infrastructure change. | +| §7 objects | The reply is a value; no object or path crosses. | +| §7 no proxy | The value belongs to this owner; Provider asks this owner, not the store. | +| §7 one face | One service with one read; the old registration-and-push shape is deleted. | +| §7 cross-language | Request, reply and error are data. | +| §7 caller complexity | The file, the user-only rule and the fallback ordering stay with their owners; the caller sees a value or none. | +| §7 one change | The new read, Provider's migration and the deletion of the identity push are one change. | +| ADR 002 D1 | Process scope. | +| ADR 002 D3 | Provider depends on the value; ProviderSettings depends only on Settings. | +| ADR 002 D4 | Business configuration in the owner's named source, read at use time. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | + +## Requirements raised to mechanism owners + +- **Provider, [#2019](https://github.com/arcships/dim/issues/2019):** the model request reads this value instead of receiving a pushed process identity; the request keeps its own `headers` precedence and its built-in fallback. + +## Binding appendix + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; + +// `CancelledFn` is the binding's cancellation argument, not a request field. +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct UserAgent { + pub user_agent: Option, +} + +#[derive(Debug, thiserror::Error)] +pub enum ProviderSettingsError { + #[error("the provider setting could not be read: {0}")] + Failed(String), +} + +impl PublicService for ProviderSettings {} + +#[rutis::service(name = "providerSettings")] +impl ProviderSettings { + pub async fn user_agent(&self, cancelled: CancelledFn) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 206ed6d609..753aa21603 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -8,6 +8,15 @@ 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 | | --- | --- | --- | --- | --- | +| [Settings](Settings.md) (owner contract) | sources, documents, revisions, change application, authorized projects and the change facts behind `settings` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [SettingsMethods](SettingsMethods.md) (owner contract) | the local client's `settings.*` methods | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [PromptSettings](PromptSettings.md) (owner contract) | the `prompts` source and the base, summary and Skills texts behind `promptSettings` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [ExecutionSettings](ExecutionSettings.md) (owner contract) | the `execution` source and its switches behind `executionSettings` | the `settings` tool ([AgentSettings](AgentSettings.md)) | the execution snapshot ([EnvironmentSettings](EnvironmentSettings.md)) | [#2017](https://github.com/arcships/dim/issues/2017) | +| [PromptSuggestionSettings](PromptSuggestionSettings.md) (owner contract) | the `prompt-suggestion` source and its value behind `promptSuggestionSettings` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [ProviderSettings](ProviderSettings.md) (owner contract) | the `provider` source and the User-Agent value behind `providerSettings` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [ModelLog](ModelLog.md) (owner contract) | the `model-log` source and the recording destination behind `modelLog` | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [PermissionRules](PermissionRules.md) (owner contract) | the `permission` source, its rules value behind `permissionRules` and the `permission.*` methods | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | +| [CollaborationModelPolicy](CollaborationModelPolicy.md) (owner contract) | the `collaboration` source, its policy value behind `collaborationPolicy` and the `collaboration.*` methods | — | — | [#2017](https://github.com/arcships/dim/issues/2017) | | [Migration](Migration.md) | on-demand import tasks, source mappings, progress and retry records; unloaded after settlement | — | — | [Delivery plan](../../plan/analysis/legacy-migration.md) | | [Provider management](../appserver/provider-management.md) | existing Provider: configuration, catalogs, client preferences and management methods | — | — | #329 | | [Questions](Questions.md) | — | `ask_user` tool, `session.question.respond`, waiters of running `ask_user` calls; no events | — | M2; #262 | diff --git a/docs/design/plugins/Settings.md b/docs/design/plugins/Settings.md new file mode 100644 index 0000000000..83f72f8e9a --- /dev/null +++ b/docs/design/plugins/Settings.md @@ -0,0 +1,330 @@ +# Settings + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). + +Settings owns the process's configuration documents and the process's authorized projects. This document is the owner's target contract. It replaces the public face described in [Settings service](../appserver/settings-service.md) §4.2–§4.5; the feature's persistence profiles, schema validation, defaults, user-only and `writeOnly` rules, revision semantics and events stay as that document describes. Each source's meaning belongs to the plugin that registers it; those owners have their own contracts ([PromptSettings](PromptSettings.md), [ExecutionSettings](ExecutionSettings.md), [PermissionRules](PermissionRules.md), and so on). + +## Use and scope: responsibility split + +Settings owns: + +- **Sources.** The registry of named documents: each source's file names, project scope, and how its content is checked — a JSON Schema or a Rust document type. A registration belongs to the registering row and ends when that row unloads. +- **Documents and revisions.** The user document (a file, or a row in the native store) and the project document (a file under an authorized project); the opaque revision that changes on every committed write; one writer at a time per document. +- **Change application.** Running a caller's change against the current document under the owner's exclusion, checking the result, writing it, publishing the fact, and reporting whether durability is confirmed. +- **Authority.** An owner change and an agent change may not alter a user-only member; a user edit may. Members marked `writeOnly` are never returned to the agent, and the agent may not set them. +- **Authorized projects.** The cwd → project table, the directory opened for each authorized project, and the fact announcing a new one. +- **Facts.** `settings/` with `{source, scope, revision}` after a commit, and `settings/projects` with `{project, cwd}` after a new authorization. + +Callers keep: + +- Document meaning: the type, schema, defaults and validation rules of each source, and the business name of every member. +- Which source, member or project a business edits, and what a refused or conflicting edit means for that business. +- When a value is fresh enough: a reader reads at use time, or follows the fact and reads again. +- Permission and approval decisions; Settings never decides whether a write is allowed beyond the authority rules above. +- File bytes of non-Settings files, including workflow definitions: those are FileStorage's operations, requested by the file's owner. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A source owner reads its own document now | No: addressing by source name lets every row read every source, and makes the owner re-resolve its registration on each call | `register` answers the source id; `read` takes the id | +| A source owner changes its own document | No: a read-then-replace makes the caller hold the revision and retry a competing write — the owner's exclusion and revision are its own mechanism | `change` | +| A source owner reacts to a committed write | Yes: the `settings/` fact carries the revision; read again | Business | +| A user edits a document from a local client | No: the client needs the current revision and a whole-document replace, and a refused write means the user's draft is stale | `read_user`, `replace_user` through [SettingsMethods](SettingsMethods.md) | +| A user edits a Rust-typed source whose rules JSON Schema cannot express | Yes: the source owner's own management namespace performs the write | Business (the source owner's methods) | +| The agent reads one plugin's configuration | No: hiding `writeOnly` members is this owner's schema rule | `agent_read` | +| The agent sets one member of another plugin's configuration | No: refusing user-only and `writeOnly` members is this owner's rule, and a whole-document replace would overwrite members the agent did not read | `agent_set` | +| The plugin tool lists the sources a live row registered | No: the registry is this owner's state | `declared_sources` | +| A process part admits a cwd as a project root | No: the project table and the opened directory are this owner's state | `authorize_project` | +| A business learns the authorized projects | No: the table is this owner's state | `authorized_projects` | +| A business needs a project's cwd or id | Yes: `authorized_projects` is a value with `{project, cwd}` | Business | +| A business reads or writes a project's non-Settings files | Yes: compose the project's cwd with FileStorage's path operations | Business | +| A capability reads a text, switch or policy another part maintains | Yes, but not from Settings: the value's owner provides its own read | The value owner's contract | + +## Caller example + +ExecutionSettings declares its document in `apply` and keeps the source id for the life of its row. + +```rust +let execution = settings + .register(Register { + source: "execution".into(), + user_file: "execution.json".into(), + project_file: None, + schema: execution_schema(), + })?; + +// The value as stored now. +let snapshot = settings + .read(Read { id: execution.clone(), scope: Scope::User }, cancelled.clone()) + .await?; + +// A change sees the current document and returns the next one. Settings holds the document for +// the whole call, checks the result and writes it; a competing writer waits. +settings + .change(Change { + id: execution.clone(), + scope: Scope::User, + change: Arc::new(|current: Option| { + Box::pin(async move { + let mut document = current.map(|document| document.0).unwrap_or_default(); + document.insert("network".into(), true.into()); + Ok(Document(document)) + }) + }), + }, cancelled.clone()) + .await?; +``` + +A local client edits the operator's prompts: the revision the client read is the base of the write. + +```rust +let snapshot = settings + .read_user(ReadUser { source: "prompts".into() }, cancelled.clone()) + .await?; +// The user edits `snapshot.document`; a stale draft is a business outcome. +settings + .replace_user(ReplaceUser { + source: "prompts".into(), + expected_revision: snapshot.revision, + document: edited, + }, cancelled.clone()) + .await?; +``` + +The plugin tool reads a plugin's configuration for the agent, and sets one member. + +```rust +let view = settings + .agent_read(AgentRead { source: "web".into() }, cancelled.clone()) + .await?; +// `view.write_only` lists the members withheld from the agent. +settings + .agent_set( + AgentSet { source: "web".into(), member: "/proxyDns".into(), value: true.into() }, + cancelled.clone(), + ) + .await?; +``` + +Workflow resolves its project and touches its own definition files through FileStorage. + +```rust +let projects = settings.authorized_projects(); +let project = projects + .projects + .iter() + .find(|project| project.cwd == cwd) + .ok_or(WorkflowError::WorkspaceNotAuthorized)?; +let definitions = format!("{}/.dimcode/workflows/{}", project.cwd, name); +let bytes = storage.read(definitions, cancelled).await?; // FileStorage's operation +``` + +## Own contract + +### Dependencies + +- [FileStorage](FileStorage.md): `add_root` for an authorized project, `read` and `update` for a document stored as a file, and `create_directory` for the project's directory under `.dimcode`. Settings passes no path outside an authorized root. +- The native store ([#2018](https://github.com/arcships/dim/issues/2018)): read a source's user document, import a file's content when the row is absent, and apply a change under the row's exclusion. The requirement is stated in [Requirements raised to mechanism owners](#requirements-raised-to-mechanism-owners). +- The caller's row: a source id and the registration are bound to the row that registered them; an id from another row is `invalid`. + +### Operations + +| Operation | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `register` | Make a document addressable under the calling row, checked once | `{source, userFile, projectFile?, schema}` | `{id}` | None; a refusal fails the row's `apply` | `invalid` | +| `read` | The document a source id names, as stored now | `{id, scope}` | `{document}` | While the document is read | `invalid`, `invalid_document`, `too_large`, `closed`, `cancelled` | +| `change` | Apply one change to a document under the owner's exclusion | `{id, scope, change}` | `{}` | Before the write; the change's future is dropped | `invalid`, `invalid_document`, `user_only`, `rejected`, `too_large`, `unsynced`, `closed`, `cancelled` | +| `read_user` | The user's draft base for a document | `{source}` | `{revision, document}` | While the document is read | `unknown_source`, `invalid_document`, `too_large`, `closed`, `cancelled` | +| `replace_user` | Replace a document with the draft the user edited at the revision read | `{source, expectedRevision, document}` | `{revision}` | Before the write | `unknown_source`, `invalid_document`, `conflict`, `too_large`, `unsynced`, `closed`, `cancelled` | +| `agent_read` | A document for the agent, user-only secrets withheld | `{source}` | `{document, writeOnly}` | While the document is read | `unknown_source`, `invalid_document`, `too_large`, `closed`, `cancelled` | +| `agent_set` | Set one member of a document on the agent's behalf | `{source, member, value}` | `{document, writeOnly}` | Before the write | `unknown_source`, `invalid`, `user_only`, `invalid_document`, `too_large`, `unsynced`, `closed`, `cancelled` | +| `declared_sources` | The declarations a live row registered | `{instance}` | `{sources}` | None; the owner completes the read | None | +| `authorize_project` | Admit a cwd as a project root; the same cwd answers the same project | `{cwd}` | `{project}` | While FileStorage opens the directory | `invalid`, `closed`, `cancelled` | +| `authorized_projects` | The projects authorized in this process | `{}` | `{projects: [{project, cwd}]}` | None | `closed` | + +Data: + +- `SourceId` is the id `register` assigns; it is bound to the row that registered it, and a caller from another row is `invalid`. +- `Document` is one JSON object; a missing user document reads as its default document. +- `Scope` is `"user"` or `{"project": ProjectId}`. `ProjectId` is this process's project id; a project id from another process is not accepted. +- `ChangeFn` is `Fn(Option) -> Result`: it is called once, under the document's exclusion, with the current document, and returns the next document or its own refusal. It must only compute; waiting on another owner or on I/O inside the change holds the document for that whole wait. +- `Revision` is an opaque value that changes on every committed write. Only the user path carries a revision. +- `writeOnly` lists the JSON Pointers of members withheld from the agent and holding a value. + +### Facts + +| Fact | Channel | Payload | +| --- | --- | --- | +| A document was written | `settings/` | `{source, scope, revision}` | +| A project was authorized | `settings/projects` | `{project, cwd}` | + +A fact is published after the commit and never carries a document. A failed fact delivery is recorded and does not undo the write. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| `invalid` | Fix the input: a declaration whose name or file is taken or whose schema or default document is refused, a source id from another row, an unknown project, a project scope for a source without a project file, a member pointer that names no member | +| `unknown_source` | The source is not registered now: retry after its owner registers it, or report that the feature is off | +| `invalid_document` | The document as stored, or the one the change produced, fails its check; repair the user's document or fix the change | +| `user_only` | The change or the agent named a member only the user changes; ask the user, or leave the member as it is | +| `rejected` | The change refused with its own `code` and `message`; act on that code | +| `conflict` | The user's draft is stale; read again and let the user decide | +| `too_large` | The document exceeds the document limit; the caller must not treat the value as a document | +| `unsynced` | The document is in place but its durability is unconfirmed; a read sees the write, and a repeated change confirms it | +| `closed` | This generation is unloading; call the replacement generation | +| `cancelled` | Nothing changed: the read stopped, or the change stopped before the write | + +### Flows + +| Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | --- | +| `change` | Take the document's exclusion, read the current document, call the change, check the result, write it, publish, release | Before the write: the change's future is dropped, the document is unchanged, the exclusion is released, `cancelled` | The row's `apply` future ends; the same release applies | New calls are refused; an in-flight change finishes or ends `closed`; the generation releases its exclusions | Exclusion by Settings; the change's future by the calling row | +| `replace_user` | Take the exclusion, read the current revision, refuse a stale base, check and write the document, publish, release | Before the write: nothing changed, `cancelled` | The call ends `cancelled` | In-flight calls finish or end `closed` | Exclusion by Settings | +| `read`, `agent_read` | Open the document through its profile, check it, return the value | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | File handle or row read by Settings or its store | +| `authorize_project` | Open the directory through FileStorage's `add_root`, append to the project table, publish the fact | Before the directory is opened or the row is appended | The call ends `cancelled`; a later call for the same cwd completes the authorization | New calls are refused; the table survives for the next generation, so a project id stays valid | Directory by FileStorage; the project table by Settings | +| `register` | Check the declaration, insert under the calling row, return the id | Not cancellable; a failed `apply` ends the row | The registration is withdrawn with the row; its documents stay | The new generation starts with no registrations; the documents stay | Registration lifetime by the calling row | + +## Exceptions with reasons + +- The user path carries a revision and the owner path does not: the user's write depends on the revision the user read, so the value carries it; an owner change depends only on the current document. +- A document's revision is a value for consumers of the fact, not a write parameter on the owner path: two owners that must agree on a version read the fact and compare revisions. +- `unsynced` reports a write that is in place with unconfirmed durability: a later read sees it, and a repeated change is idempotent, so the caller must not assume the first call failed. +- On the native profile the first read imports the user file into the row when the row is absent: the import is internal state migration, not an operation, and the file stays where it is. +- A project id stays valid across a reload because FileStorage's root table is append-only ([FileStorage](FileStorage.md)); the id is a value, not a handle and not an authority. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | Settings is one process part. It publishes facts and folds no state, so it is not a Capability. | +| §2 scopes | Process: documents and the project table outlive Sessions. Session and branch parts read values or follow facts; none registers a source. | +| §3 orthogonality | Settings reads no other owner's state except through FileStorage's operations and the native store's operations; no plugin's business appears in this contract. | +| §4 rule 1 | A committed write is a fact on `settings/`; a refused write publishes nothing. | +| §4 rule 2 | No handoff. | +| §4 rule 3 | No `before` callback. `change` runs under the document's exclusion, never inside the Timeline's commit lock. | +| §4 rule 4 | No document meaning, schema or business rule for a source in the core; each source owner keeps its own. | +| §4 rule 5 | No Timeline batch. Settings documents never enter the Timeline. | +| §4 rule 6 | Settings documents never enter model context; the agent path is the `plugin` tool's result, decided by PluginManager. | +| §4 rule 7 | Callers use these operations; no caller reads a file path, a lock or a stage. | +| §4 rule 8 | Supported by the native store's operations ([#2018](https://github.com/arcships/dim/issues/2018)); stated below. | +| §4 rule 9 | A revision fact is written only after the commit; no scratch state is persisted. | +| §7 objects | Only values cross: documents, source ids, project ids, revisions and the `change` callback by reference. No object, handle or path crosses. | +| §7 no proxy | No operation answers another owner's data: a value is requested from the part that owns it, and workflow definition bytes come from FileStorage for the Workflow plugin. | +| §7 one face | One service on the `Settings` type; no facade, no wrapper type, no second name. | +| §7 cross-language | Every operation's request, reply and errors are data; the Rust binding is the appendix. | +| §7 caller complexity | The revision, exclusion, retry and durability stay inside Settings; the caller handles `conflict`, `user_only` and `rejected` only. | +| §7 one change | The old `settings`/`settingsService` surfaces and their callers are migrated in one change; PluginManager, SettingsMethods and every source owner appear in the delivery table. | +| ADR 002 D1 | Process scope; documents and the project table outlive Sessions. | +| ADR 002 D2 | No wiring plugin; the service is on the owner type. | +| ADR 002 D3 | Dependencies point to FileStorage and the native store; no plugin depends on Settings' internals. | +| ADR 002 D4 | Business configuration lives in the owner's named source, read at use time; structural items stay in PluginManager. | +| ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| §7.2 checks | Every caller need lands on one operation; no handle, object or proxy crosses; one face; no Rust-only method on the face; no caller mechanism; one change. | + +## Requirements raised to mechanism owners + +- **SessionStore / native store, [#2018](https://github.com/arcships/dim/issues/2018):** the native user-document operations Settings needs — read one source's document, import a file's content when the row is absent, and apply a change under the row's exclusion, returning the committed document and entering the revision. No object or transaction crosses. +- **Provider, [#2019](https://github.com/arcships/dim/issues/2019):** the model request's User-Agent is read from [ProviderSettings](ProviderSettings.md)'s value instead of being pushed into the process identity; the model-log recorder reads its destination from [ModelLog](ModelLog.md)'s value instead of a process-global setter. +- **Workflow, [#2033](https://github.com/arcships/dim/issues/2033):** definition files are read and replaced through FileStorage's path operations, with the project resolved from `authorized_projects`; `workflowFiles` is removed with no replacement face on Settings. + +## Binding appendix + +The service is marked on the owner type; the wire name stays `settings`. The `Settings` facade and the `SettingsService` type merge into this type. + +```rust +use dim_agent_runtime::PublicService; +use rutis::host::BoxFuture; +use serde_json::Value; +use std::sync::Arc; + +pub type SourceId = String; +pub type ProjectId = String; +pub type Revision = String; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Registered { + pub id: SourceId, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub struct Document(pub Value); + +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Scope { + User, + Project { project: ProjectId }, +} + +#[derive(Debug, thiserror::Error)] +#[error("{code}: {message}")] +pub struct Rejected { + pub code: String, + pub message: String, +} + +pub type ChangeFn = + Arc) -> BoxFuture<'static, Result> + Send + Sync>; + +#[derive(Debug, thiserror::Error)] +pub enum SettingsError { + #[error("{0}")] + Invalid(String), + #[error("the settings source is not registered: {0}")] + UnknownSource(String), + #[error("the settings document is invalid: {0}")] + InvalidDocument(String), + #[error("the member {0} is changed only by the user")] + UserOnly(String), + #[error("{code}: {message}")] + Rejected { code: String, message: String }, + #[error("the settings revision is stale")] + Conflict, + #[error("the settings document is {size} bytes, over the document limit")] + TooLarge { size: u64 }, + #[error("the settings document is in place but its durability is unconfirmed")] + Unsynced, + #[error("the settings service is unloading")] + Closed, + #[error("the settings call was cancelled")] + Cancelled, +} + +impl PublicService for Settings {} + +#[rutis::service(name = "settings")] +impl Settings { + pub fn register(&self, request: Register) -> Result { /* ... */ } + pub async fn read(&self, request: Read, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn change(&self, request: Change, cancelled: CancelledFn) -> Result<(), SettingsError> { /* ... */ } + pub async fn read_user(&self, request: ReadUser, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn replace_user( + &self, + request: ReplaceUser, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub async fn agent_read(&self, request: ReadUser, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn agent_set( + &self, + request: SetMember, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub fn declared_sources(&self, request: ByInstance) -> Declarations { /* ... */ } + pub async fn authorize_project( + &self, + request: AuthorizeProject, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub fn authorized_projects(&self) -> AuthorizedProjects { /* ... */ } +} + +// `CancelledFn` is the binding's cancellation argument, not a request field. + +/// The Rust binding of `register` for a Rust document type: the same operation, with the type as +/// its codec instead of a schema. +impl Settings { + pub fn register_typed(&self) -> Result { /* ... */ } +} +``` diff --git a/docs/design/plugins/SettingsMethods.md b/docs/design/plugins/SettingsMethods.md new file mode 100644 index 0000000000..9908409d55 --- /dev/null +++ b/docs/design/plugins/SettingsMethods.md @@ -0,0 +1,111 @@ +# SettingsMethods + +Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). + +SettingsMethods registers the local client's `settings.*` management methods and calls [Settings](Settings.md)' user operations. This document is the owner's target contract; the client surfaces are in [Settings service](../appserver/settings-service.md) §4.3 and §7. + +## Use and scope: responsibility split + +SettingsMethods owns: + +- The `settings` management namespace: which methods exist, their request and reply data, and the mapping from Settings' errors to the client's error codes. +- The local-only rule: the methods are never served to paired devices or a remote entry. + +Callers keep: + +- The user's draft, its editing flow and what a stale draft means in the client. +- Which source the client edits; the client names sources it knows, and it never learns another owner's document. + +| Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | +| --- | --- | --- | +| A local client reads a document to edit it | No: the client reaches management methods only, and the draft base is [Settings](Settings.md) `read_user` | `settings.read` | +| A local client writes the draft it edited | No: the write must carry the draft's base revision and report a stale draft | `settings.update` | +| A client discovers every declared source and its schema | Yes, and no client asks: the CLI reads four sources by name | Not an operation; `settings.sources` is deleted | +| A client lists authorized projects to pass a project scope | Yes, and no client asks: no declared source declares a project file | Not an operation; `settings.projects` is deleted | + +## Caller example + +The CLI edits the operator's prompts with the revision it read. + +```rust +let snapshot: PromptSetting = client + .typed("settings.read", json!({"source": SOURCE})) + .await?; +// The user edits one field; the write is the whole document at the revision read. +client + .typed( + "settings.update", + json!({ + "source": SOURCE, + "expectedRevision": snapshot.revision, + "document": document, + }), + ) + .await?; +``` + +## Own contract + +### Dependencies + +- [Settings](Settings.md): `read_user` and `replace_user`. SettingsMethods adds no state and forwards nothing else. + +### Operations + +No service. Two management methods, registered with `managementMethods`: + +| Method | Intent | Request | Reply | Cancellation | Errors | +| --- | --- | --- | --- | --- | --- | +| `settings.read` | The user's draft base for one document | `{source}` | `{revision, document}` | The call is dropped | invalid params, `settings_unknown_source`, `settings_failed`, reloading | +| `settings.update` | Replace a document with the draft at the revision read | `{source, expectedRevision, document}` | `{revision}` | The call is dropped | invalid params, `settings_unknown_source`, `settings_conflict`, `settings_unsynced`, `settings_failed`, reloading | + +`settings_conflict` means the draft is stale: the client reads again and lets the user decide. `settings_unsynced` means the bytes are in place with unconfirmed durability: read again instead of repeating the write. + +### Errors + +| Kind | What the caller does next | +| --- | --- | +| invalid params | Fix the request: an unknown field, a missing revision, or a document that is not an object | +| `settings_unknown_source` | The source is not registered now; report that the feature is off and retry after its owner registers it | +| `settings_conflict` | Read again; the user's draft is stale | +| `settings_unsynced` | Read again; the write is in place | +| `settings_failed` | Read again before retrying; the store refused or failed without a code the client can act on | +| reloading | The daemon is restarting; retry after it is back | + +### Flows + +| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| --- | --- | --- | --- | --- | +| `settings.read` | Call [Settings](Settings.md) `read_user`, map the reply | Nothing changes | Pending calls end `reloading` | Settings | +| `settings.update` | Call [Settings](Settings.md) `replace_user`, map the reply | Before Settings writes: nothing changes, `settings_failed` or `reloading` | In-flight calls finish or end `reloading` | Settings | + +## Exceptions with reasons + +- `managementMethods` is a mechanism registration point, not a forwarding facade: the namespace belongs to this part because Rpc reaches Settings through Agents and may not reach a management owner ([ADR 004](../../adr/004-loader-plugin-management.md) D4), and the mapping from Settings' kinds to the client's codes is this part's own contract. + +## Rule check + +| Rule | Application | +| --- | --- | +| §1 parts and Capabilities | One process part, no Timeline facts, no folded state: not a Capability. | +| §2 scopes | Process; the methods are client surfaces, not Session state. | +| §3 orthogonality | No state of its own; one dependency, [Settings](Settings.md). | +| §4 rule 1 | No event. | +| §4 rule 7 | Clients use management methods; they learn no file name, path or lock. | +| §4 rule 8 | No infrastructure change; the existing `managementMethods` mechanism is used. | +| §7 objects | Request and reply are data; no object, handle or path crosses. | +| §7 no proxy | Settings answers the document; SettingsMethods maps the errors and owns the namespace. | +| §7 one face | The management namespace exists once; the service operations stay on [Settings](Settings.md). | +| §7 cross-language | Both methods are data. | +| §7 caller complexity | The revision reaches the client because the user's draft depends on it; nothing else of Settings' mechanism does. | +| §7 one change | `settings.sources` and `settings.projects` are deleted with this change; the CLI is the only caller migrated. | +| ADR 002 D2 | No wiring plugin: the namespace owner is a process part that depends on Settings, as PermissionRules owns `permission`. | +| ADR 002 D4 | Business configuration stays in Settings sources; the methods carry no structural item. | + +## Requirements raised to mechanism owners + +None. + +## Binding appendix + +No service and no Rust binding: the two methods are registered with `managementMethods`. The request and reply types are the client's JSON shapes in the operations table. From 31032253370635a4cf3947de78b12e2343dc0878 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 14:43:37 +0800 Subject: [PATCH 2/8] design(settings): keep the draft revision on the client path The user's revision is the draft base the client holds, business concurrency control between the user's read and write. State that in the responsibility split, keep it out of the owner-path caller examples, and point the client example at SettingsMethods. --- docs/design/plugins/Settings.md | 21 ++++----------------- docs/design/plugins/SettingsMethods.md | 4 ++-- 2 files changed, 6 insertions(+), 19 deletions(-) diff --git a/docs/design/plugins/Settings.md b/docs/design/plugins/Settings.md index 83f72f8e9a..17ef3937f6 100644 --- a/docs/design/plugins/Settings.md +++ b/docs/design/plugins/Settings.md @@ -29,6 +29,7 @@ Callers keep: | A source owner changes its own document | No: a read-then-replace makes the caller hold the revision and retry a competing write — the owner's exclusion and revision are its own mechanism | `change` | | A source owner reacts to a committed write | Yes: the `settings/` fact carries the revision; read again | Business | | A user edits a document from a local client | No: the client needs the current revision and a whole-document replace, and a refused write means the user's draft is stale | `read_user`, `replace_user` through [SettingsMethods](SettingsMethods.md) | +| A user's write is based on a revision | Yes: the client holds the revision it read; that revision is the client's business concurrency control between the user's read and write, not this owner's version — the owner's exclusion and revision stay inside `change` | Business; `read_user` returns the draft base and `replace_user` compares it | | A user edits a Rust-typed source whose rules JSON Schema cannot express | Yes: the source owner's own management namespace performs the write | Business (the source owner's methods) | | The agent reads one plugin's configuration | No: hiding `writeOnly` members is this owner's schema rule | `agent_read` | | The agent sets one member of another plugin's configuration | No: refusing user-only and `writeOnly` members is this owner's rule, and a whole-document replace would overwrite members the agent did not read | `agent_set` | @@ -74,21 +75,7 @@ settings .await?; ``` -A local client edits the operator's prompts: the revision the client read is the base of the write. - -```rust -let snapshot = settings - .read_user(ReadUser { source: "prompts".into() }, cancelled.clone()) - .await?; -// The user edits `snapshot.document`; a stale draft is a business outcome. -settings - .replace_user(ReplaceUser { - source: "prompts".into(), - expected_revision: snapshot.revision, - document: edited, - }, cancelled.clone()) - .await?; -``` +A local client's edit is [SettingsMethods](SettingsMethods.md)'s caller example: the client keeps the draft revision it read, and only that path carries a revision. The plugin tool reads a plugin's configuration for the agent, and sets one member. @@ -147,7 +134,7 @@ Data: - `Document` is one JSON object; a missing user document reads as its default document. - `Scope` is `"user"` or `{"project": ProjectId}`. `ProjectId` is this process's project id; a project id from another process is not accepted. - `ChangeFn` is `Fn(Option) -> Result`: it is called once, under the document's exclusion, with the current document, and returns the next document or its own refusal. It must only compute; waiting on another owner or on I/O inside the change holds the document for that whole wait. -- `Revision` is an opaque value that changes on every committed write. Only the user path carries a revision. +- `Revision` is an opaque value that changes on every committed write. Only the user path carries it, as the draft base the client holds: a business concurrency control between the user's read and write. An owner change carries no revision; the owner's exclusion and any waiting stay inside `change`. - `writeOnly` lists the JSON Pointers of members withheld from the agent and holding a value. ### Facts @@ -186,7 +173,7 @@ A fact is published after the commit and never carries a document. A failed fact ## Exceptions with reasons -- The user path carries a revision and the owner path does not: the user's write depends on the revision the user read, so the value carries it; an owner change depends only on the current document. +- The user path carries a draft revision and the owner path does not: the client's business decides whether a write still applies to the document the user read, while an owner change always applies to the current document; the revision is not a version the owner checks on the owner path. - A document's revision is a value for consumers of the fact, not a write parameter on the owner path: two owners that must agree on a version read the fact and compare revisions. - `unsynced` reports a write that is in place with unconfirmed durability: a later read sees it, and a repeated change is idempotent, so the caller must not assume the first call failed. - On the native profile the first read imports the user file into the row when the row is absent: the import is internal state migration, not an operation, and the file stays where it is. diff --git a/docs/design/plugins/SettingsMethods.md b/docs/design/plugins/SettingsMethods.md index 9908409d55..74e147694f 100644 --- a/docs/design/plugins/SettingsMethods.md +++ b/docs/design/plugins/SettingsMethods.md @@ -19,13 +19,13 @@ Callers keep: | Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | | A local client reads a document to edit it | No: the client reaches management methods only, and the draft base is [Settings](Settings.md) `read_user` | `settings.read` | -| A local client writes the draft it edited | No: the write must carry the draft's base revision and report a stale draft | `settings.update` | +| A local client writes the draft it edited | No: the write must carry the draft's base revision, the client's business concurrency control between the user's read and write, and report a stale draft | `settings.update` | | A client discovers every declared source and its schema | Yes, and no client asks: the CLI reads four sources by name | Not an operation; `settings.sources` is deleted | | A client lists authorized projects to pass a project scope | Yes, and no client asks: no declared source declares a project file | Not an operation; `settings.projects` is deleted | ## Caller example -The CLI edits the operator's prompts with the revision it read. +The CLI edits the operator's prompts with the revision it read. The revision is the draft's base, a business value the client holds; the daemon compares it and never exposes the owner's internal version. ```rust let snapshot: PromptSetting = client From cfaa2b272cdd78d6c420e4818e116e0611b9d46d Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 15:14:59 +0800 Subject: [PATCH 3/8] design(permission): name the value read that replaces commandRules Consumers that read commandRules call permissionRules.rules; the delivery migration names the register operation, not its Rust helper. --- docs/design/plugins/PermissionRules.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/plugins/PermissionRules.md b/docs/design/plugins/PermissionRules.md index 8c011cea5e..4f405a9601 100644 --- a/docs/design/plugins/PermissionRules.md +++ b/docs/design/plugins/PermissionRules.md @@ -2,7 +2,7 @@ Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). Feature: [Permission command rules](../appserver/permission-command-rules.md). -PermissionRules owns the `permission` document: the user's command rules. The permission decision that applies the rules is the `CommandRules` capability; this owner answers the rules. This document is the owner's target contract; it replaces the `commandRules` Session service and the Session part that read the rules from the store. +PermissionRules owns the `permission` document: the user's command rules. The permission decision that applies the rules is the `CommandRules` capability; this owner answers the rules. This document is the owner's target contract; it replaces the `commandRules` Session service and the Session part that read the rules from the store. `permissionRules.rules` replaces `commandRules.read`: a consumer that read `commandRules` calls `permissionRules.rules` and handles this owner's errors. ## Use and scope: responsibility split From 187d20bc3be893832d72a566161764348d53e40c Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 19:32:09 +0800 Subject: [PATCH 4/8] design(settings): own the user-document rows The native profile's row operations (readUser, importUserIfAbsent, changeUser, replaceUser) belong to the Settings contract; the storage engine executes them as crate-private transactions and its public face keeps only storageReport and the offline operations. The client examples use typed requests instead of inline JSON literals. --- docs/design/plugins/PermissionRules.md | 12 ++++++++++- docs/design/plugins/Settings.md | 21 ++++++++++++++---- docs/design/plugins/SettingsMethods.md | 30 ++++++++++++++++++++------ 3 files changed, 51 insertions(+), 12 deletions(-) diff --git a/docs/design/plugins/PermissionRules.md b/docs/design/plugins/PermissionRules.md index 4f405a9601..804453f01b 100644 --- a/docs/design/plugins/PermissionRules.md +++ b/docs/design/plugins/PermissionRules.md @@ -37,10 +37,20 @@ let decision = decide(&rules.rules, &command); The CLI replaces the list with the revision it read. ```rust +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +struct SetRulesRequest<'a> { + expected_revision: &'a str, + command_rules: &'a [CommandRule], +} + client .typed( "permission.set_rules", - json!({"expectedRevision": revision, "commandRules": rules}), + serde_json::to_value(SetRulesRequest { + expected_revision: &revision, + command_rules: &rules, + })?, ) .await?; ``` diff --git a/docs/design/plugins/Settings.md b/docs/design/plugins/Settings.md index 17ef3937f6..f11b5e02d6 100644 --- a/docs/design/plugins/Settings.md +++ b/docs/design/plugins/Settings.md @@ -110,7 +110,7 @@ let bytes = storage.read(definitions, cancelled).await?; // FileStorage's operat ### Dependencies - [FileStorage](FileStorage.md): `add_root` for an authorized project, `read` and `update` for a document stored as a file, and `create_directory` for the project's directory under `.dimcode`. Settings passes no path outside an authorized root. -- The native store ([#2018](https://github.com/arcships/dim/issues/2018)): read a source's user document, import a file's content when the row is absent, and apply a change under the row's exclusion. The requirement is stated in [Requirements raised to mechanism owners](#requirements-raised-to-mechanism-owners). +- The storage engine ([#2018](https://github.com/arcships/dim/issues/2018)) as the native profile's crate-private implementation: it executes this owner's transactions over the `settings_documents` rows. The rows and their request, reply and error shapes are this contract's ([Native-profile row operations](#native-profile-row-operations)); the engine answers no Settings read or write on its public face. - The caller's row: a source id and the registration are bound to the row that registered them; an id from another row is `invalid`. ### Operations @@ -137,6 +137,19 @@ Data: - `Revision` is an opaque value that changes on every committed write. Only the user path carries it, as the draft base the client holds: a business concurrency control between the user's read and write. An owner change carries no revision; the owner's exclusion and any waiting stay inside `change`. - `writeOnly` lists the JSON Pointers of members withheld from the agent and holding a value. +### Native-profile row operations + +The native profile stores each user document as a `settings_documents` row. These four operations belong to this contract and are crate-private to the storage crate: the engine executes each as one transaction and returns the stored form, and no caller outside Settings calls them. The file profile has no counterpart; it calls FileStorage's `read` and `update` instead. + +| Operation | Intent | Request | Reply | Errors | +| --- | --- | --- | --- | --- | +| `readUser` | One source's stored user document | `{source}` | `{version, document}` or none | `storage` | +| `importUserIfAbsent` | Import the validated file content when the row is absent, in one transaction, and return the winning row | `{source, document, importedRevision}` | `{version, document}` | `storage` | +| `changeUser` | Apply one change under the row's exclusion | `{source, change}` | `{version, document}` | `rejected`, `storage` | +| `replaceUser` | Replace a user document at an expected version | `{source, expectedVersion, document}` | `{version}` | `conflict`, `missing`, `overflow`, `storage` | + +`change` in the public operations is `changeUser` on the native profile and FileStorage's `update` on the file profile; `replace_user` is `replaceUser` and FileStorage's `update`, which compares the revision Settings carries. `importUserIfAbsent` runs on the first read of a source whose file exists and whose row does not; a version is a positive integer that increases on every committed write, and the revision Settings publishes is derived from it. + ### Facts | Fact | Channel | Payload | @@ -193,7 +206,7 @@ A fact is published after the commit and never carries a document. A failed fact | §4 rule 5 | No Timeline batch. Settings documents never enter the Timeline. | | §4 rule 6 | Settings documents never enter model context; the agent path is the `plugin` tool's result, decided by PluginManager. | | §4 rule 7 | Callers use these operations; no caller reads a file path, a lock or a stage. | -| §4 rule 8 | Supported by the native store's operations ([#2018](https://github.com/arcships/dim/issues/2018)); stated below. | +| §4 rule 8 | The storage engine executes this owner's crate-private row operations ([#2091](https://github.com/arcships/dim/pull/2091)); no new infrastructure. | | §4 rule 9 | A revision fact is written only after the commit; no scratch state is persisted. | | §7 objects | Only values cross: documents, source ids, project ids, revisions and the `change` callback by reference. No object, handle or path crosses. | | §7 no proxy | No operation answers another owner's data: a value is requested from the part that owns it, and workflow definition bytes come from FileStorage for the Workflow plugin. | @@ -203,14 +216,14 @@ A fact is published after the commit and never carries a document. A failed fact | §7 one change | The old `settings`/`settingsService` surfaces and their callers are migrated in one change; PluginManager, SettingsMethods and every source owner appear in the delivery table. | | ADR 002 D1 | Process scope; documents and the project table outlive Sessions. | | ADR 002 D2 | No wiring plugin; the service is on the owner type. | -| ADR 002 D3 | Dependencies point to FileStorage and the native store; no plugin depends on Settings' internals. | +| ADR 002 D3 | Dependencies point to FileStorage and the storage engine; the rows belong to Settings and no plugin depends on Settings' internals. | | ADR 002 D4 | Business configuration lives in the owner's named source, read at use time; structural items stay in PluginManager. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | | §7.2 checks | Every caller need lands on one operation; no handle, object or proxy crosses; one face; no Rust-only method on the face; no caller mechanism; one change. | ## Requirements raised to mechanism owners -- **SessionStore / native store, [#2018](https://github.com/arcships/dim/issues/2018):** the native user-document operations Settings needs — read one source's document, import a file's content when the row is absent, and apply a change under the row's exclusion, returning the committed document and entering the revision. No object or transaction crosses. +- **Storage engine, [#2018](https://github.com/arcships/dim/issues/2018) and [#2091](https://github.com/arcships/dim/pull/2091):** no requirement. The engine executes this owner's crate-private row operations as transactions; the rows, versions and conflicts are Settings', and the engine publishes none of them under `sqliteStorage`. - **Provider, [#2019](https://github.com/arcships/dim/issues/2019):** the model request's User-Agent is read from [ProviderSettings](ProviderSettings.md)'s value instead of being pushed into the process identity; the model-log recorder reads its destination from [ModelLog](ModelLog.md)'s value instead of a process-global setter. - **Workflow, [#2033](https://github.com/arcships/dim/issues/2033):** definition files are read and replaced through FileStorage's path operations, with the project resolved from `authorized_projects`; `workflowFiles` is removed with no replacement face on Settings. diff --git a/docs/design/plugins/SettingsMethods.md b/docs/design/plugins/SettingsMethods.md index 74e147694f..6f3378c0bc 100644 --- a/docs/design/plugins/SettingsMethods.md +++ b/docs/design/plugins/SettingsMethods.md @@ -28,22 +28,38 @@ Callers keep: The CLI edits the operator's prompts with the revision it read. The revision is the draft's base, a business value the client holds; the daemon compares it and never exposes the owner's internal version. ```rust -let snapshot: PromptSetting = client - .typed("settings.read", json!({"source": SOURCE})) +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +struct ReadRequest<'a> { + source: &'a str, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +struct UpdateRequest<'a> { + source: &'a str, + expected_revision: &'a str, + document: &'a JsonObject, +} + +let snapshot: SettingsDraft = client + .typed("settings.read", serde_json::to_value(ReadRequest { source: SOURCE })?) .await?; // The user edits one field; the write is the whole document at the revision read. client .typed( "settings.update", - json!({ - "source": SOURCE, - "expectedRevision": snapshot.revision, - "document": document, - }), + serde_json::to_value(UpdateRequest { + source: SOURCE, + expected_revision: &snapshot.revision, + document: &document, + })?, ) .await?; ``` +The request is one typed struct, serialized at the client boundary; no request is assembled as an inline JSON literal. + ## Own contract ### Dependencies From be0b5171fde56b7cfbe978042deef635984e0034 Mon Sep 17 00:00:00 2001 From: scotares Date: Mon, 23 Nov 2026 21:36:25 +0800 Subject: [PATCH 5/8] design(settings): apply the contract review Declare user-only members in the registration, keep the client methods' request and reply shapes, serve declared sources only and resolve their ids, keep the process-local project number and the {root, cwd} fact, and state the project table's generation lifetime. Errors carry {code, message} with snake_case codes; the change callback is a positional parameter and keeps the callback's code. Name the capability-side ports, link FileStorage through its PR, and supersede the paragraphs this board replaces in the existing design documents. --- docs/design/appserver/management-methods.md | 3 +- docs/design/appserver/model-log.md | 6 +- .../appserver/permission-command-rules.md | 14 +- docs/design/appserver/prompt-overrides.md | 19 +- docs/design/appserver/provider-management.md | 4 +- docs/design/appserver/settings-service.md | 162 +------- .../contracts/resource-owner-operations.md | 19 +- .../plugins/CollaborationModelPolicy.md | 24 +- docs/design/plugins/ExecutionSettings.md | 18 +- docs/design/plugins/ModelLog.md | 15 +- docs/design/plugins/PermissionRules.md | 24 +- docs/design/plugins/PromptSettings.md | 27 +- .../plugins/PromptSuggestionSettings.md | 15 +- docs/design/plugins/ProviderSettings.md | 15 +- docs/design/plugins/README.md | 2 +- docs/design/plugins/Settings.md | 355 ++++++++++++++---- docs/design/plugins/SettingsMethods.md | 81 ++-- docs/design/service-faces.md | 6 +- docs/design/subagent-model-policy.md | 2 +- 19 files changed, 459 insertions(+), 352 deletions(-) diff --git a/docs/design/appserver/management-methods.md b/docs/design/appserver/management-methods.md index 9b7a9bee27..554cebefc6 100644 --- a/docs/design/appserver/management-methods.md +++ b/docs/design/appserver/management-methods.md @@ -56,7 +56,8 @@ the profile enables account methods. Settings supplies generic BusinessDocument persistence and the declared sources of [the settings service](settings-service.md), not approvals, a method contribution or a configuration namespace; SettingsMethods, which depends on it, owns -`settings.read`/`settings.update`/`settings.sources`/`settings.projects`. +`settings.read`/`settings.update` for declared sources ([SettingsMethods](../plugins/SettingsMethods.md)); a Rust source is +served by its owner's own namespace. StorageMethods serves `storage.report` through the native binding of the same SQLite owner operation exposed as `sqliteStorage.storageReport({})`. MCP owns its configuration types in `mcp/config.rs`; the Skills owner supplies the existing `SkillSettingsHost`. App Server's SkillsCatalog mounts the reusable catalog diff --git a/docs/design/appserver/model-log.md b/docs/design/appserver/model-log.md index 0c7d4b3484..4eae049b46 100644 --- a/docs/design/appserver/model-log.md +++ b/docs/design/appserver/model-log.md @@ -8,9 +8,9 @@ aimux's RFC-0023 JSONL (`aimux-core`'s `recording.rs`). | Owner | Responsibility | | --- | --- | -| ModelLog, process | Register the `model-log` Settings source, start and stop the recorder, follow its changes | -| Aimux, process | Bind a request to the recorder that is on when the request is built, and close the recording when its stream ends | -| Settings service | Validate and persist `model-log.json`, user scope only | +| ModelLog, process | Register the `model-log` Settings source and answer its `recording` value ([ModelLog](../plugins/ModelLog.md)) | +| Aimux, process | Read the recording value when a request is built and close the recording when its stream ends | +| Settings | Validate and persist `model-log.json`, user scope only | The switch is user scope only: recordings hold prompts, code and tool output, so project content must not turn them on. diff --git a/docs/design/appserver/permission-command-rules.md b/docs/design/appserver/permission-command-rules.md index b7fabf37eb..00ac5e0e5b 100644 --- a/docs/design/appserver/permission-command-rules.md +++ b/docs/design/appserver/permission-command-rules.md @@ -109,23 +109,15 @@ restore and fork neither restore nor widen them. ### 4.1 Language-neutral (ADR 002 D5) -**Session service `commandRules`**, Session scope, no instance key, provided by the profile. - -| Method | Mode | Request | Reply | -| --- | --- | --- | --- | -| `read` | async | `{}` | `{rules: CommandRule[]}` | - -`CommandRule = {command: string, match: "exact" | "prefix", decision: "allow" | "deny"}`. Errors -are data: `unavailable` (the source could not be read, including an invalid persisted file), -`cancelled` (the caller dropped the call or the provider is unloading). +**Session service `commandRules`** is deleted. Rule consumers call [PermissionRules](../plugins/PermissionRules.md)'s `permissionRules.rules` (`{}` → `{rules}`); `CommandRule = {command: string, match: "exact" | "prefix", decision: "allow" | "deny"}`. **Management methods**, namespace `permission`, which the process part registers with `managementMethods` (overview §6.2 rule 9; never served to paired devices). | Method | Request | Reply | Errors | | --- | --- | --- | --- | -| `permission.rules` | `{}` | `{revision, commandRules}` | `permission_rules_failed` | -| `permission.set_rules` | `{expectedRevision, commandRules}` | `{revision}` | invalid params (validation), `permission_rules_conflict` (stale revision), `permission_rules_failed` | +| `permission.rules` | `{}` | `{revision, commandRules}` | `permission_rules_failed`, `operation_interrupted` | +| `permission.set_rules` | `{expectedRevision, commandRules}` | `{revision}` | invalid params (validation), `permission_rules_conflict` (stale revision), `permission_rules_failed`, `operation_interrupted` | `set_rules` replaces the whole list. The reply's `revision` is the Settings revision. Settings emits its existing `settings.changed` event for the write; F2 adds no listener. diff --git a/docs/design/appserver/prompt-overrides.md b/docs/design/appserver/prompt-overrides.md index b24e17b073..8bbacf562f 100644 --- a/docs/design/appserver/prompt-overrides.md +++ b/docs/design/appserver/prompt-overrides.md @@ -100,24 +100,7 @@ Each owner declares its own port, so a capability depends only on its own text: ### 3.1 Data operations -The same three read ports are available to plugins of any language: - -| Service | Async operation | Request | Reply | -| --- | --- | --- | --- | -| `basePromptSettingsHost` | `base` | `{}` | string or `null` | -| `skillsInstructionsSettingsHost` | `instructions` | `{}` | string or `null` | -| `summaryPromptSettingsHost` | `systemPrompt` | `{}` | string or `null` | - -Each reply is that port's existing override text; `null` means no user override. -The ports read through the same PromptSettings owner and source. They add no cache, -extra source read, configuration field or change to the precedence above. - -Errors are `{code, message}`. The product owner reports `failed` for a settings read -error, including a settings read ended by cancellation, retaining its existing error -text. Malformed wire requests are `invalid_request`. Dropping a wire call cancels -its read token and abandons its reply; this does not introduce a new product error -code. Native callers retain their existing cancellation token and error behavior; -a failed port read does not change the source. +Superseded by [PromptSettings](../plugins/PromptSettings.md): one service `promptSettings` with `base`, `summary` and `skills`, each answering `{text}` or none. The precedence above and the client entry below stay in force. ## 4. Client entry diff --git a/docs/design/appserver/provider-management.md b/docs/design/appserver/provider-management.md index 86c50ac553..00676a1e0e 100644 --- a/docs/design/appserver/provider-management.md +++ b/docs/design/appserver/provider-management.md @@ -50,7 +50,7 @@ with its existing owner; management never writes another owner's state. | Account namespaces | Account owners provide login, usage and logout. The [ChatGPT plan provider](chatgpt-plan.md) owns `account.chatgpt`. | | `ProviderConnectionResolver`, `ModelSelectionHost` | Provider implements catalog/route decisions through existing types; no new core port | | `auxiliaryModel.complete` | Existing caller-selected S4 contract, unchanged | -| `provider` Settings source, user scope (`provider.json`) | The Provider part registers it; it holds `userAgent`, the User-Agent override (§2, Model request identity), so a user's choice is a declared, validated document rather than a request-local input | +| `provider` Settings source, user scope (`provider.json`) | [ProviderSettings](../plugins/ProviderSettings.md) owns it; it holds `userAgent`, the User-Agent override (§2, Model request identity), and publishes it as a value a model request reads | | Native CLI Provider flows | Migrate discovery, create, update and disconnect together with the new owner methods | Business logic stays in Provider, not `connection.rs`, `protocol.rs` or a wiring @@ -101,7 +101,7 @@ default identity like any other Provider. | Override | Where | Notes | | --- | --- | --- | -| `provider` settings source, `userAgent` | `provider.json`, user scope, owned by the Provider part | Replaces the whole User-Agent string; 1–512 printable ASCII characters, refused by the source's schema otherwise. The part serving one App Server holds it, so two Servers in one process keep theirs apart | +| `provider` settings source, `userAgent` | `provider.json`, user scope ([ProviderSettings](../plugins/ProviderSettings.md)) | Replaces the whole User-Agent string; 1–512 printable ASCII characters, refused by the source's schema otherwise. A model request reads the value from ProviderSettings at request time, so two Servers in one process keep theirs apart | | `DIM_USER_AGENT` | Environment of the process that hosts models | The same validation; wins over the setting. Read once by the App Server command line, beside the other startup inputs, and passed to each Server it builds, so a value a request cannot carry fails that process's startup | `DIM_USER_AGENT` wins over the setting because it is set for one run of the diff --git a/docs/design/appserver/settings-service.md b/docs/design/appserver/settings-service.md index 10ad7b029e..3cfe2b2f19 100644 --- a/docs/design/appserver/settings-service.md +++ b/docs/design/appserver/settings-service.md @@ -207,78 +207,11 @@ plugin unloads. Nothing else is new. Nothing enters the Timeline. ### 4.2 Service `settings` (owner path) -Process scope, no instance key, provided by Settings. - -| Method | Mode | Request | Reply | -| --- | --- | --- | --- | -| `register` | async | a declaration (§3.1) | nothing; rejects when refused | -| `read` | async | `{source, scope: Scope}` | `Snapshot` | -| `update` | async | `{source, scope: Scope, expectedRevision, document}` | `Snapshot` (the stored document) | -| `declaredBy` | sync | `{instanceId: string}` (the live loader instance ID in decimal) | The JSON Schema declarations registered by that instance, ordered by source name. An instance with no live declarations returns an empty array. | -| `projects` | sync | `{}` | `{projects: [{root, cwd}]}`: the authorized project roots now | - -- `register` is a registration of the calling row, withdrawn when that row unloads. It is called - from the row's own `apply`; a refusal (§3.1) rejects the call rather than returning an - envelope, so it fails that `apply` as every owner's `register` does. -- `update` is CAS: it fails with `conflict` unless `expectedRevision` is the current revision. -- `update` is an owner write. It fails with `user_only_field` when the stored document and the new - one differ at any `userOnly` pointer (a value changed, added or removed). The comparison uses - the documents after defaults. -- `projects` is what an owner reads first. Afterwards it follows `settings/projects` (§4.4). -- Cancellation: the caller drops the call. A write that has already committed stays committed, - as in S8a. -- Errors of `read`, `update` and `projects` (§6): `unknown_source`, `invalid_scope`, - `invalid_document`, `user_only_field`, `conflict`, `unsynced`, `failed`, `closed`, `cancelled`. - -Only `register` uses the caller's identity, to withdraw the registration with the calling row. -Ownership comes from the registering row: each source has one owner, and only that package is -written against it. This is the trust model of in-process plugins -(AGENTS.md rule 11): dependency declarations are not a sandbox. +Superseded by [Settings](../plugins/Settings.md): one service on the `Settings` type, one source id per registration, a value read, a change callback, the user draft path and the agent path. §4.1 and §4.4 stay in force. ### 4.3 Management methods `settings.*` (client path) -Namespace `settings`, which `SettingsMethods`, a process part that depends on Settings, registers -with `managementMethods` (§4.5). They are never served to paired devices (overview §6.2 rule 9). - -| Method | Request | Reply | Errors | -| --- | --- | --- | --- | -| `settings.read` | `{source, scope}` | `{revision, document}` | invalid params (bad scope), `settings_unknown_source`, `settings_failed` | -| `settings.update` | `{source, scope, expectedRevision, document}` | `{revision, document}` | invalid params (bad scope, schema violation), `settings_unknown_source`, `settings_conflict`, `settings_unsynced`, `settings_failed` | -| `settings.sources` | `{}` | `{dialect, sources: [...]}` (`Sources`, §4.1) | invalid params | -| `settings.projects` | `{}` | `{projects: [{root, cwd}]}`: the authorized project roots now, as the service's `projects` answers them (§4.2) | invalid params | - -- Only registered declared sources are served. A Rust source (for example `mcp`) is - `settings_unknown_source`. - Its owner's methods stay the way to change it. -- A client write may change user-only fields. There is no other difference from the owner path. -- `closed` maps to the existing retryable reloading error. -- `settings.sources` lists every registered declared source in source-name order, and never a - Rust source; an empty registry is an empty `sources` array, not an error. An item is the - declaration without its file names or its owner (§4.1). The `schema` member round-trips what - the owner registered, and the schema's own `title`/`description` annotations are the display - metadata, if the owner added them. -- A client reads the declarations here, through a public method, rather than from a plugin - package or manifest (§9, §4 rule 7: public interfaces only). The agent-side counterpart stays - the `plugin` tool's `config` command, which additionally returns the user document with - `writeOnly` members redacted and listed in `writeOnlySet` (PluginManager §6). -- `schedule` is not a declared source. `ScheduleDocument` is a Rust `BusinessDocument`, - registered with `settings.register::`, validated by its own `validate()`, - served by `schedule.*`, and `settings_unknown_source` on every `settings.*` path. A Rust - source keeps its own typed methods and is out of a schema-driven surface; `settings.sources` - lists declared sources only and therefore never lists it. -- `settings.sources` is never served to paired devices (§4.3 opening) and is absent from the - Web entry's allowlist, so the Web entry answers `unknown_method` (§11 items 7–8): discovery - is local-only like the rest of the namespace. -- `settings.projects` is the read a client needs before it can pass `{project: root}`: it - answers the same `{projects: [{root, cwd}]}` as the owner-facing `projects` service (§4.2), - in cwd order, and the same Web-entry and paired-device rule applies (absent from the - allowlist, so `unknown_method`). **`root` is a process-local number** (§4.1): it holds for the - life of the daemon process, is not a durable identity, and a client re-reads - `settings.projects` after it reconnects to a restarted daemon rather than storing a root. The - list only grows while the process runs — authorizing the same cwd again adds no item and - emits nothing (§4.4) — so no event or push carries it; the client reads it when it opens a - project-scoped form. A `{project: root}` this process has not authorized is invalid params, - the same answer as for a source without project scope. +Superseded by [SettingsMethods](../plugins/SettingsMethods.md): `settings.read` and `settings.update` serve declared sources only, keep their request and reply shapes, and admit a write that survives a dropped client wait. `settings.sources` and `settings.projects` are deleted; the Web entry is served for its allowlisted sources. ### 4.4 Events @@ -312,97 +245,8 @@ Permission does). ### 4.5 Rust binding -The `Settings` binding exposes the owner operations of the public `settings` data face. -It provides `register(ctx, declaration)`, `read(source, scope, cancel)`, -`update(source, scope, expected, document, cancel)` and `projects()`. -The dispatcher calls these same operations, and native consumers call them directly -without JSON conversion. Registration retains the caller's lifetime; updates are owner -writes and preserve user-only fields. The existing Settings owner still supplies the -source registry, validation and persistence. - -`SettingsService` retains the native `BusinessDocument` and client management paths below. -PluginManager's declared-source tools also use it for reads and owner writes. -This binding does not make native sources visible through declared-source operations or -change the local-client boundary in §4.3 and §7. - -In `dim-app-server::settings` (S8a types, changed only where noted): - -```rust -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum SettingsScope { User, Project(usize) } // + Serialize/Deserialize - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct SettingsChanged { pub source: String, // was &'static str - pub scope: SettingsScope, pub revision: String } - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ProjectAuthorized { pub root: usize, pub cwd: PathBuf } // + Serialize/Deserialize - -/// A declaration (§3.1), as `register` receives it. -pub struct SourceDeclaration { pub source: String, pub user_file: String, - pub project_file: Option, pub schema: serde_json::Value, - pub user_only: Vec } - -pub enum Writer { Owner, Client } - -impl SettingsService { - /// Registers `D` (or a declaration) until the plugin owning `ctx` unloads. - pub fn register(&self, ctx: &Ctx) -> rutis::Result<()>; - pub fn register_declared(&self, ctx: &Ctx, declaration: SourceDeclaration) -> rutis::Result<()>; - pub fn declarations(&self) -> Vec; - pub async fn read_declared(&self, source: &str, scope: SettingsScope, - cancel: &CancellationToken) -> Result>; - pub async fn update_declared(self: &Arc, source: &str, scope: SettingsScope, - expected: &str, document: Value, writer: Writer, - cancel: &CancellationToken) -> Result>; -} -``` +Superseded by the binding appendix of [Settings](../plugins/Settings.md). The error variants, events, security boundary and state descriptions of this document stay in force. -- `declarations()` is the registry-wide listing behind `settings.sources` (§4.3): every - registered declared source in name order, never a Rust source. Unlike `declared_by`, it does - not filter to one registering fiber. -- Both registrations are effects of the plugin owning `ctx`, withdrawn when it unloads, and are - checked under one registry state (§3.1). `register_declared` compiles the schema with - `jsonschema`. The process owners register in their `apply`: Mcp (`mcp`, `mcp-projects`, `mcp-plugins`), - SkillsCatalog (`skills`), PermissionRules (`permission`), CollaborationModelPolicy - (`collaboration`) and the App Server's ExecutionSettings (`execution`). Readers in other plugins - only read; `read::`/`update::` of a type that is not the registered one for its name is - `UnknownSource`. The `settings` service's `register` calls `register_declared` with the calling - row's context. -- `execution` is user scope only: it declares no project file, so a project-scope read or write is - refused. It holds two booleans, `sandbox` and `network`, both defaulting to `false`, and its - revisions are the ordinary CAS ones. The TUI's `Process isolation` control and any local management client use - `settings.read`/`settings.update`; the owner's reader reaches the document through the - `ExecutionSettingsHost` port, which is an in-process read contract and not a management method - ([ADR 011](../../adr/011-execution-settings.md) D1). The visible choices map to these existing - booleans as defined by [process isolation](../host-platform-isolation.md#process-isolation); - Permission presets and tool lists do not write this source. -- The file and native paths are shared with `BusinessDocument`, keyed by source name instead of - `D::NAMESPACE`. CAS, the gate, leases, the unsynced case and `publish` stay as they are. -- `SettingsError` gains `UnknownSource`, `UserOnlyField(pointer)`, `InvalidScope`, - `Document(message)` and `DocumentShape { reason, position }`. A written document that - breaks the schema or is not an object is `Document` with the validator's message (the - instance path, never the value). `DocumentShape` is how `McpSettings` refuses an MCP - document as a whole — not an object, no `mcpServers` object, `mcpServers` not an object, - an empty server entry id, a file that is not JSON: the owner's static `reason`, which a - client may see, and `position` when the document was read from bytes. Its `Display` is - byte for byte what `Document` printed for the same text. No other owner has adopted it: - HooksSettings refuses a hook document as `Invalid("invalid hook document")`, and a - persisted file that the default `BusinessDocument` decode or a declared source cannot - parse is `Invalid("invalid settings document")`. `reason()` reports the static message of `Invalid` and of `DocumentShape`, and - `None` for every other variant, `Document` included, whose text is arbitrary. The - client path maps `Document` and `DocumentShape` to invalid params. A persisted document - that breaks the schema stays `Invalid` (`invalid_document` / `settings_failed`). -- The `settings` service is a `HostDispatch` under `host_key("settings")`, and assembly registers - `settings` in the `ServiceCatalog`, as `pluginFiles` is done today. Replies use - the envelope of `sessions`: `{ok: true, value}` or `{ok: false, error: {code, message}}`. -- The `ManagementMethods` for `settings` come from `SettingsMethods`, a process part that depends - on Settings (module `settings_methods`), the way PermissionRules owns `permission`. Settings - itself cannot own a namespace: Rpc reaches Settings through Agents, Rpc may not reach a - management owner (methods contract §3.2), and the module boundary keeps Settings persistence - infrastructure (ADR 004 D4, `xtask check`). Assembly lists the `SettingsMethods` row as the - owner of `settings`. ## 5. Flows ### 5.1 Owner reads and updates diff --git a/docs/design/contracts/resource-owner-operations.md b/docs/design/contracts/resource-owner-operations.md index 5b2be8c345..cf8ea4b569 100644 --- a/docs/design/contracts/resource-owner-operations.md +++ b/docs/design/contracts/resource-owner-operations.md @@ -131,21 +131,4 @@ serves declared sources and excludes the native `mcp-secrets` document. ## Settings -| Caller → Settings | Current operation and contract | -| --- | --- | -| PluginManager; declared-source consumers | Filter declarations by live loader instance using declaredBy above. Reuse settings.read/update/projects for owner edits and reads. SettingsMethods uses its client path and lists only declared sources. | -| Agents create/restore, Hooks and MCP management | authorize_project(cwd,cancelled) → root registers the authorized root and publishes the existing notice. It is a write performed at trusted admission. project_root/path/sources are reads covered by settings.projects. | -| PermissionRules and CommandRules; CollaborationModelPolicy and optional Collaboration runtime | User permission and collaboration policy reads/writes. Expose the existing commandRules.read projection to rule consumers; use the policy owner's read returning {revision,policy} for Collaboration. Preserve absent-profile fallback. | -| 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. | -| 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. | - -The source codec has two operations. `decode(bytes or null) → document` uses the source's -existing decoder for stored bytes, its default for absence, and validates the result. -`validate(document) → void` applies BusinessDocument write validation before admitting a -replacement. Settings performs serialization, version checks and persistence. Both calls -propagate the original Settings error and end with the registration generation. Foreign codec -calls occur outside SQLite transactions. Declared-schema sources reuse their existing codec. +The Settings operations, the authorized-project table and each source's own contract are defined by [Settings](../plugins/Settings.md) and [SettingsMethods](../plugins/SettingsMethods.md). The `settingsService` owner API and the `registerDocument` operation are replaced by the one `settings` service: a source id per registration, a value read, a change callback, the user draft path and the agent path. diff --git a/docs/design/plugins/CollaborationModelPolicy.md b/docs/design/plugins/CollaborationModelPolicy.md index 167f52cfe0..09b92457f7 100644 --- a/docs/design/plugins/CollaborationModelPolicy.md +++ b/docs/design/plugins/CollaborationModelPolicy.md @@ -44,14 +44,15 @@ let policy = if startup { - [Settings](Settings.md): `register` for the `collaboration` source and `read`/`change` for its value. - `managementMethods`: the two client methods. +- Collaboration: the App Server's `Collaboration` calls `policy` directly in-process; it is in the same crate as this owner, so no port type is needed. The policy type stays in this owner's module. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `policy` | The policy in force now | `{}` | `{policy}` | The caller's token; nothing changes | `failed`, `cancelled` | -| `collaboration.model_policy` | The policy with the revision a draft starts from | `{}` | `{revision, policy}` | The call is dropped | `collaboration_model_policy_failed`, reloading | -| `collaboration.set_model_policy` | Replace the policy at the revision read | `{expectedRevision, policy}` | `{revision}` | The call is dropped | invalid params, `collaboration_model_policy_conflict`, `collaboration_model_policy_failed`, reloading | +| `collaboration.model_policy` | The policy with the revision a draft starts from | `{}` | `{revision, policy}` | The call is dropped | `collaboration_model_policy_failed`, `operation_interrupted`, reloading | +| `collaboration.set_model_policy` | Replace the policy at the revision read | `{expectedRevision, policy}` | `{revision}` | The call is dropped | invalid params, `collaboration_model_policy_conflict`, `collaboration_model_policy_failed`, `operation_interrupted`, reloading | ### Errors @@ -62,6 +63,7 @@ let policy = if startup { | invalid params | Fix the request: an unknown mode, or a `fixed` policy without a provider and a model | | `collaboration_model_policy_conflict` | Read again; the user's draft is stale | | `collaboration_model_policy_failed` | Read again before retrying | +| `operation_interrupted` | The call was cancelled or the owner is unloading; read again before retrying | | reloading | The daemon is restarting; retry after it is back | ### Flows @@ -75,8 +77,14 @@ let policy = if startup { - The policy document is a Rust type rather than a JSON Schema: the closed mode set with a typed model is the owner's validation, so the client reaches it through this owner's namespace. +## Supersedes + +- [Subagent model policy](../subagent-model-policy.md)'s row that persists and edits the policy through `SettingsService::read/update`; the `collaboration.*` management methods keep their shapes. + ## Rule check +Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part owning a document; not a Capability. | @@ -96,6 +104,7 @@ let policy = if startup { | ADR 002 D3 | Collaboration depends on this owner's value; this owner depends on Settings. | | ADR 002 D4 | Business configuration in the owner's named source, read at use time. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a process part reading a process value. | ## Requirements raised to mechanism owners @@ -123,12 +132,13 @@ pub struct Policy { pub policy: ModelPolicy, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum CollaborationPolicyError { - #[error("the collaboration model policy could not be read: {0}")] - Failed(String), - #[error("the collaboration model policy read was cancelled")] - Cancelled, + #[error("{message}")] + Failed { message: String }, + #[error("{message}")] + Cancelled { message: String }, } impl PublicService for CollaborationModelPolicy {} diff --git a/docs/design/plugins/ExecutionSettings.md b/docs/design/plugins/ExecutionSettings.md index 34352b8343..208b476b83 100644 --- a/docs/design/plugins/ExecutionSettings.md +++ b/docs/design/plugins/ExecutionSettings.md @@ -8,7 +8,7 @@ ExecutionSettings owns the `execution` document and the process execution switch ExecutionSettings owns: -- The `execution` source: its file, its schema, and the two switches `sandbox` and `network`, both defaulting to `false` and changed only by the user. +- The `execution` source: its file, its schema, and the two switches `sandbox` and `network`, both defaulting to `false` and declared as user-only members. This contract changes their authority: today the source declares no user-only member, so an owner or agent write could change the switches; under this contract such a write is `user_only`, and the delivery lists the change. - The value `{sandbox, network}`: the switches in force now, read at each use. Callers keep: @@ -40,6 +40,7 @@ let switches = execution_settings.read(cancelled.clone()).await.map_err(|error| ### Dependencies - [Settings](Settings.md): `register` for the `execution` source and `read` for its value. +- The Rust port, for consumers outside the App Server: the trait `ExecutionSettingsRead` and the reply type `ExecutionSettings` live in `dim-agent-capabilities` ([`execution_settings`](../../../crates/dim-agent-capabilities/src/execution_settings.rs)). HostPlatform and the `settings` tool depend on the trait; the App Server's `ExecutionSettings` implements it and serves the same read on the wire. ### Operations @@ -65,8 +66,15 @@ let switches = execution_settings.read(cancelled.clone()).await.map_err(|error| - A missing value fails preparation instead of defaulting to unsandboxed: the built-in default is already "off", and silently running unsandboxed is the one failure the feature exists to prevent. +## Supersedes + +- [ADR 011](../../adr/011-execution-settings.md) D1's port name `executionSettingsHost`: the decision is unchanged, the port is `executionSettings` and its Rust binding is `ExecutionSettingsRead`. +- [Service faces](../service-faces.md) §3.2's and §4.10's `executionSettingsHost` entries. + ## Rule check +Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). + | Rule | Application | | --- | --- | | §1 parts and Capabilities | The process part owns the document. The snapshot branch writes one input at branch open and on a change, so that part is a Capability ([EnvironmentSettings](EnvironmentSettings.md)); the tool part is a Session tool registration, not a Capability. | @@ -86,6 +94,7 @@ let switches = execution_settings.read(cancelled.clone()).await.map_err(|error| | ADR 002 D3 | HostPlatform depends on the port; the port has no Settings or file dependency. | | ADR 002 D4 | Business configuration in the owner's named source, read at use time. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumers are process or Session parts reading a process value. | ## Requirements raised to mechanism owners @@ -105,10 +114,11 @@ pub struct Switches { pub network: bool, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum ExecutionSettingsError { - #[error("the execution settings could not be read: {0}")] - Failed(String), + #[error("{message}")] + Failed { message: String }, } impl PublicService for ExecutionSettings {} diff --git a/docs/design/plugins/ModelLog.md b/docs/design/plugins/ModelLog.md index b029211e8a..dd1cf81df4 100644 --- a/docs/design/plugins/ModelLog.md +++ b/docs/design/plugins/ModelLog.md @@ -39,6 +39,7 @@ if let Some(directory) = destination.directory { ### Dependencies - [Settings](Settings.md): `register` for the `model-log` source and `read` for its value. +- The Rust port, for the consumer outside the App Server: the trait `RecordingDestination` lives in `dim-agent-aimux` where the recorder is, and the App Server's `ModelLog` implements it and serves the same read on the wire. - FileStorage: `root_path` for the home root, once, to build the destination directory. ### Operations @@ -63,8 +64,14 @@ if let Some(directory) = destination.directory { - The directory is computed from the home root at each read instead of being pushed into the recorder: the recorder belongs to aimux, and a value read keeps the write inside its owner. +## Supersedes + +- [Model request log](../appserver/model-log.md)'s sentence that ModelLog starts and stops the recorder by pushing a directory into it. + ## Rule check +Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part owning a document; not a Capability. | @@ -84,6 +91,7 @@ if let Some(directory) = destination.directory { | ADR 002 D3 | The recorder depends on the value; ModelLog depends on Settings and FileStorage. | | ADR 002 D4 | Business configuration in the owner's named source, read at use time. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a process part reading a process value. | ## Requirements raised to mechanism owners @@ -102,10 +110,11 @@ pub struct Recording { pub directory: Option, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum ModelLogError { - #[error("the model-log setting could not be read: {0}")] - Failed(String), + #[error("{message}")] + Failed { message: String }, } impl PublicService for ModelLog {} diff --git a/docs/design/plugins/PermissionRules.md b/docs/design/plugins/PermissionRules.md index 804453f01b..30bed4aab0 100644 --- a/docs/design/plugins/PermissionRules.md +++ b/docs/design/plugins/PermissionRules.md @@ -61,14 +61,15 @@ client - [Settings](Settings.md): `register` for the `permission` source and `read`/`change` for its value. - `managementMethods`: the two client methods. +- The Rust port, for consumers outside the App Server: the trait `ReadCommandRules` stays in `dim-agent-capabilities` ([`permission`](../../../crates/dim-agent-capabilities/src/permission.rs)); the App Server binds it to this owner's `rules`, not to the store. The command rules' type stays in `dim-agent-types`. ### Operations | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | | `rules` | The user's command rules as stored now | `{}` | `{rules}` | The caller's token; nothing changes | `failed`, `cancelled` | -| `permission.rules` | The rules with the revision a draft starts from | `{}` | `{revision, commandRules}` | The call is dropped | `permission_rules_failed`, reloading | -| `permission.set_rules` | Replace the whole list at the revision read | `{expectedRevision, commandRules}` | `{revision}` | The call is dropped | invalid params, `permission_rules_conflict`, `permission_rules_failed`, reloading | +| `permission.rules` | The rules with the revision a draft starts from | `{}` | `{revision, commandRules}` | The call is dropped | `permission_rules_failed`, `operation_interrupted`, reloading | +| `permission.set_rules` | Replace the whole list at the revision read | `{expectedRevision, commandRules}` | `{revision}` | The call is dropped | invalid params, `permission_rules_conflict`, `permission_rules_failed`, `operation_interrupted`, reloading | ### Errors @@ -79,6 +80,7 @@ client | invalid params | Fix the request: a rule without a command word, or with a shell separator | | `permission_rules_conflict` | Read again; the user's draft is stale | | `permission_rules_failed` | Read again before retrying | +| `operation_interrupted` | The call was cancelled or the owner is unloading; read again before retrying | | reloading | The daemon is restarting; retry after it is back | ### Flows @@ -92,8 +94,14 @@ client - The rules' validation is Rust code rather than a JSON Schema: a shell separator and an empty command word are expressible only as code, so the source is a Rust document and the client reaches it through this owner's namespace instead of `settings.*`. +## Supersedes + +- [Permission command rules](../appserver/permission-command-rules.md) §4.1's `commandRules` service; the `permission.*` management methods stay with the same shapes. + ## Rule check +Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part owning a document. The `CommandRules` capability owns the decision and folds no rule state: it reads this owner's value. | @@ -113,6 +121,7 @@ client | ADR 002 D3 | The decision depends on this owner's value; this owner depends on Settings. | | ADR 002 D4 | Business configuration in the owner's named source, read at use time. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a Session part reading a process value. | ## Requirements raised to mechanism owners @@ -132,12 +141,13 @@ pub struct Rules { pub rules: Vec, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum PermissionRulesError { - #[error("the command rules could not be read: {0}")] - Failed(String), - #[error("the command rules read was cancelled")] - Cancelled, + #[error("{message}")] + Failed { message: String }, + #[error("{message}")] + Cancelled { message: String }, } impl PublicService for PermissionRules {} diff --git a/docs/design/plugins/PromptSettings.md b/docs/design/plugins/PromptSettings.md index 1c2b078aa7..ef6cc85a14 100644 --- a/docs/design/plugins/PromptSettings.md +++ b/docs/design/plugins/PromptSettings.md @@ -29,7 +29,7 @@ Callers keep: PromptSources reads the base text once, while its Session part applies. ```rust -let base = prompt_settings.base().await.ok().flatten(); +let base = prompt_settings.base(cancelled.child_token()).await.ok().flatten(); let text = factory.base.or(base).unwrap_or_else(|| BUILT_IN.into()); ``` @@ -38,6 +38,7 @@ let text = factory.base.or(base).unwrap_or_else(|| BUILT_IN.into()); ### Dependencies - [Settings](Settings.md): `register` for the `prompts` source and `read` for its value. PromptSettings registers the source from its own process row and keeps the source id. +- The Rust port, for consumers outside the App Server: the three traits `BasePromptSettings`, `SkillsInstructionsSettings` and `SummaryPromptSettings` stay in `dim-agent-capabilities` ([`prompt_sources`](../../../crates/dim-agent-capabilities/src/prompt_sources.rs), [`skills`](../../../crates/dim-agent-capabilities/src/skills/mod.rs), [`summary_strategy`](../../../crates/dim-agent-capabilities/src/summary_strategy.rs)), each covering one text. The App Server's `PromptSettings` implements all three and serves the same reads on the wire; a consumer in `dim-agent-capabilities` depends on the trait, never on the App Server. ### Operations @@ -66,8 +67,14 @@ A read returns the member as stored after the schema check; an absent member is - The three texts share one document and one registering row: a file has one owner, while each text belongs to a different capability; the schema keeps each member independent, and a user-only member cannot be changed by the owner. - A read failure does not fail the Session: the text is policy with a safe default, and the consumer keeps the built-in text. +## Supersedes + +- [Prompt overrides](../appserver/prompt-overrides.md) §3.1: the three services and their bare string replies are replaced by `promptSettings` and `{text}`. The precedence rules above and §4's client entry stay in force. + ## Rule check +Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part that owns a document. It publishes facts through Settings and folds no state: not a Capability. | @@ -84,7 +91,8 @@ A read returns the member as stored after the schema check; an absent member is | §7 caller complexity | Nothing of the store, the schema or the file name reaches the consumer. | | §7 one change | The one service replaces the three names, and all three consumers migrate in the same change. | | ADR 002 D1 | Process scope: the setting is shared configuration, not Session state. | -| ADR 002 D3 | The consumers' crates depend on the port type, not on the App Server. | +| ADR 002 D3 | The consumers' crates depend on the port traits, not on the App Server. | +| ADR 027 | Not applicable: the consumers are process or Session parts reading a process value. | | ADR 002 D4 | Business configuration in the owner's named source, read at use time. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | @@ -103,22 +111,23 @@ use rutis::host::BoxFuture; // `CancelledFn` is the binding's cancellation argument, not a request field. #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Text { +pub struct PromptText { pub text: Option, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum PromptSettingsError { - #[error("the prompts setting could not be read: {0}")] - Failed(String), + #[error("{message}")] + Failed { message: String }, } impl PublicService for PromptSettings {} #[rutis::service(name = "promptSettings")] impl PromptSettings { - pub async fn base(&self, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn summary(&self, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn skills(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn base(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn summary(&self, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn skills(&self, cancelled: CancelledFn) -> Result { /* ... */ } } ``` diff --git a/docs/design/plugins/PromptSuggestionSettings.md b/docs/design/plugins/PromptSuggestionSettings.md index a476f3aeaa..6f63b50452 100644 --- a/docs/design/plugins/PromptSuggestionSettings.md +++ b/docs/design/plugins/PromptSuggestionSettings.md @@ -40,6 +40,7 @@ let max_chars = settings.max_chars; // the owner's schema already bounded it ### Dependencies - [Settings](Settings.md): `register` for the `prompt-suggestion` source and `read` for its value. +- The Rust port, for consumers outside the App Server: the trait `PromptSuggestionSettingsRead` and the reply type `SuggestionSettings` live in `dim-agent-capabilities` ([`prompt_suggestion`](../../../crates/dim-agent-capabilities/src/prompt_suggestion.rs)). The PromptSuggestion Session part depends on the trait; the App Server's `PromptSuggestionSettings` implements it and serves the same read on the wire. ### Operations @@ -65,8 +66,14 @@ The reply carries both members because the schema gives both a default; a docume - The assembler may leave the port absent: an evaluation or a host without Settings then keeps the feature off, so the read is optional at assembly. +## Supersedes + +- [Service faces](../service-faces.md) §3.2's and §4.10's `promptSuggestionSettingsHost` entries. + ## Rule check +Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part owning a document; the Session part that reads it is a Capability of the PromptSuggestion feature, designed in that plugin's page. | @@ -86,6 +93,7 @@ The reply carries both members because the schema gives both a default; a docume | ADR 002 D3 | The Session part depends on the port type, not on the App Server. | | ADR 002 D4 | Business configuration in the owner's named source, read at use time. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a Session part reading a process value. | ## Requirements raised to mechanism owners @@ -105,10 +113,11 @@ pub struct SuggestionSettings { pub max_chars: u32, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum PromptSuggestionSettingsError { - #[error("the prompt-suggestion setting could not be read: {0}")] - Failed(String), + #[error("{message}")] + Failed { message: String }, } impl PublicService for PromptSuggestionSettings {} diff --git a/docs/design/plugins/ProviderSettings.md b/docs/design/plugins/ProviderSettings.md index eae436f504..ed370fe68b 100644 --- a/docs/design/plugins/ProviderSettings.md +++ b/docs/design/plugins/ProviderSettings.md @@ -38,6 +38,7 @@ let user_agent = configured.unwrap_or_else(|| dim_user_agent()); ### Dependencies - [Settings](Settings.md): `register` for the `provider` source and `read` for its value. +- The Rust port, for the consumer outside the App Server: the trait `ProviderUserAgent` lives in `dim-agent-capabilities` where the model request is built, and the App Server's `ProviderSettings` implements it and serves the same read on the wire. ### Operations @@ -61,8 +62,14 @@ let user_agent = configured.unwrap_or_else(|| dim_user_agent()); - The value is read per request instead of being published into the process identity: the identity belongs to Provider, and a value read keeps the write inside its owner. +## Supersedes + +- [Provider management](../appserver/provider-management.md) §2's sentences that say the Provider part holds the value and pushes it into the model identity. + ## Rule check +Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part owning a document; not a Capability. | @@ -82,6 +89,7 @@ let user_agent = configured.unwrap_or_else(|| dim_user_agent()); | ADR 002 D3 | Provider depends on the value; ProviderSettings depends only on Settings. | | ADR 002 D4 | Business configuration in the owner's named source, read at use time. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: the consumer is a process part reading a process value. | ## Requirements raised to mechanism owners @@ -100,10 +108,11 @@ pub struct UserAgent { pub user_agent: Option, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, thiserror::Error, serde::Serialize)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum ProviderSettingsError { - #[error("the provider setting could not be read: {0}")] - Failed(String), + #[error("{message}")] + Failed { message: String }, } impl PublicService for ProviderSettings {} diff --git a/docs/design/plugins/README.md b/docs/design/plugins/README.md index 753aa21603..4d3a1e354f 100644 --- a/docs/design/plugins/README.md +++ b/docs/design/plugins/README.md @@ -60,6 +60,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 | Settings, SettingsMethods and the settings sections (PromptSettings, ExecutionSettings, PromptSuggestionSettings, ProviderSettings, ModelLog, PermissionRules, CollaborationModelPolicy), Provider (management supplement), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RuntimeManager, RemoteGateway, Skills (installation), `CodeMode` when installed, light-ocr in the daemon, EventHub, Report; AcpGateway in its client host process; ClientView (the connection's viewed line) | | Session parts | Questions, ShellInput, Attachments, SessionTitle, Report, PromptSuggestion, Goal, Web, Recall, ImageUnderstanding, EventHub, Hooks, Scheduler, Workflow, PromptSources, Prompt (the entries table), Code Mode when enabled, SettingsTool (the one `settings` tool, registered by ExecutionSettings in v1) | | Branch parts | Goal (with Pursuit), ModelRecovery (proposed), Hooks, Prompt, Code Mode when enabled, EnvironmentClientsBranch (registered by Connection), SettingsSnapshotBranch (registered by ExecutionSettings) | diff --git a/docs/design/plugins/Settings.md b/docs/design/plugins/Settings.md index f11b5e02d6..635f13f42c 100644 --- a/docs/design/plugins/Settings.md +++ b/docs/design/plugins/Settings.md @@ -2,18 +2,18 @@ Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). -Settings owns the process's configuration documents and the process's authorized projects. This document is the owner's target contract. It replaces the public face described in [Settings service](../appserver/settings-service.md) §4.2–§4.5; the feature's persistence profiles, schema validation, defaults, user-only and `writeOnly` rules, revision semantics and events stay as that document describes. Each source's meaning belongs to the plugin that registers it; those owners have their own contracts ([PromptSettings](PromptSettings.md), [ExecutionSettings](ExecutionSettings.md), [PermissionRules](PermissionRules.md), and so on). +Settings owns the process's configuration documents and the process's authorized projects. This document is the owner's target contract. Each source's meaning belongs to the plugin that registers it; those owners have their own contracts ([PromptSettings](PromptSettings.md), [ExecutionSettings](ExecutionSettings.md), [PermissionRules](PermissionRules.md), and so on). ## Use and scope: responsibility split Settings owns: -- **Sources.** The registry of named documents: each source's file names, project scope, and how its content is checked — a JSON Schema or a Rust document type. A registration belongs to the registering row and ends when that row unloads. +- **Sources.** The registry of named documents: each source's file names, project scope, the members only the user changes, and how its content is checked — a JSON Schema or a Rust document type. A registration belongs to the registering row and ends when that row unloads. - **Documents and revisions.** The user document (a file, or a row in the native store) and the project document (a file under an authorized project); the opaque revision that changes on every committed write; one writer at a time per document. - **Change application.** Running a caller's change against the current document under the owner's exclusion, checking the result, writing it, publishing the fact, and reporting whether durability is confirmed. - **Authority.** An owner change and an agent change may not alter a user-only member; a user edit may. Members marked `writeOnly` are never returned to the agent, and the agent may not set them. - **Authorized projects.** The cwd → project table, the directory opened for each authorized project, and the fact announcing a new one. -- **Facts.** `settings/` with `{source, scope, revision}` after a commit, and `settings/projects` with `{project, cwd}` after a new authorization. +- **Facts.** `settings/` with `{source, scope, revision}` after a commit, and `settings/projects` with `{root, cwd}` after a new authorization. Callers keep: @@ -28,15 +28,15 @@ Callers keep: | A source owner reads its own document now | No: addressing by source name lets every row read every source, and makes the owner re-resolve its registration on each call | `register` answers the source id; `read` takes the id | | A source owner changes its own document | No: a read-then-replace makes the caller hold the revision and retry a competing write — the owner's exclusion and revision are its own mechanism | `change` | | A source owner reacts to a committed write | Yes: the `settings/` fact carries the revision; read again | Business | -| A user edits a document from a local client | No: the client needs the current revision and a whole-document replace, and a refused write means the user's draft is stale | `read_user`, `replace_user` through [SettingsMethods](SettingsMethods.md) | +| A user edits a declared document from a client | No: the client needs the current revision and a whole-document replace, and a refused write means the user's draft is stale | `read_user`, `replace_user` through [SettingsMethods](SettingsMethods.md), which resolves the source name and refuses a Rust source | | A user's write is based on a revision | Yes: the client holds the revision it read; that revision is the client's business concurrency control between the user's read and write, not this owner's version — the owner's exclusion and revision stay inside `change` | Business; `read_user` returns the draft base and `replace_user` compares it | -| A user edits a Rust-typed source whose rules JSON Schema cannot express | Yes: the source owner's own management namespace performs the write | Business (the source owner's methods) | +| A user edits a Rust-typed source whose rules JSON Schema cannot express | Yes: the source owner's own management namespace performs the write with its source id | Business (the source owner's methods) | | The agent reads one plugin's configuration | No: hiding `writeOnly` members is this owner's schema rule | `agent_read` | | The agent sets one member of another plugin's configuration | No: refusing user-only and `writeOnly` members is this owner's rule, and a whole-document replace would overwrite members the agent did not read | `agent_set` | | The plugin tool lists the sources a live row registered | No: the registry is this owner's state | `declared_sources` | | A process part admits a cwd as a project root | No: the project table and the opened directory are this owner's state | `authorize_project` | | A business learns the authorized projects | No: the table is this owner's state | `authorized_projects` | -| A business needs a project's cwd or id | Yes: `authorized_projects` is a value with `{project, cwd}` | Business | +| A business needs a project's cwd or number | Yes: `authorized_projects` is a value with `{root, cwd}` | Business | | A business reads or writes a project's non-Settings files | Yes: compose the project's cwd with FileStorage's path operations | Business | | A capability reads a text, switch or policy another part maintains | Yes, but not from Settings: the value's owner provides its own read | The value owner's contract | @@ -45,37 +45,42 @@ Callers keep: ExecutionSettings declares its document in `apply` and keeps the source id for the life of its row. ```rust -let execution = settings - .register(Register { +let execution: SourceId = settings.register( + ctx, + Register { source: "execution".into(), user_file: "execution.json".into(), project_file: None, schema: execution_schema(), - })?; + user_only: vec!["/sandbox".into(), "/network".into()], + }, +)?; // The value as stored now. let snapshot = settings - .read(Read { id: execution.clone(), scope: Scope::User }, cancelled.clone()) + .read(ctx, Read { id: execution.clone(), scope: Scope::User }, cancelled.clone()) .await?; // A change sees the current document and returns the next one. Settings holds the document for // the whole call, checks the result and writes it; a competing writer waits. settings - .change(Change { - id: execution.clone(), - scope: Scope::User, - change: Arc::new(|current: Option| { + .change( + ctx, + execution.clone(), + Scope::User, + Arc::new(|current: Option| { Box::pin(async move { let mut document = current.map(|document| document.0).unwrap_or_default(); - document.insert("network".into(), true.into()); + document["network"] = true.into(); Ok(Document(document)) }) }), - }, cancelled.clone()) + cancelled.clone(), + ) .await?; ``` -A local client's edit is [SettingsMethods](SettingsMethods.md)'s caller example: the client keeps the draft revision it read, and only that path carries a revision. +A user edit is [SettingsMethods](SettingsMethods.md)'s caller example: the client names a declared source, keeps the draft revision it read, and only that path carries a revision. The plugin tool reads a plugin's configuration for the agent, and sets one member. @@ -83,7 +88,7 @@ The plugin tool reads a plugin's configuration for the agent, and sets one membe let view = settings .agent_read(AgentRead { source: "web".into() }, cancelled.clone()) .await?; -// `view.write_only` lists the members withheld from the agent. +// `view.writeOnly` lists the members withheld from the agent. settings .agent_set( AgentSet { source: "web".into(), member: "/proxyDns".into(), value: true.into() }, @@ -109,7 +114,7 @@ let bytes = storage.read(definitions, cancelled).await?; // FileStorage's operat ### Dependencies -- [FileStorage](FileStorage.md): `add_root` for an authorized project, `read` and `update` for a document stored as a file, and `create_directory` for the project's directory under `.dimcode`. Settings passes no path outside an authorized root. +- [FileStorage](https://github.com/arcships/dim/pull/2080): `add_root` for an authorized project, `read` and `update` for a document stored as a file, and `create_directory` for the project's directory under `.dimcode`. Settings passes no path outside an authorized root. - The storage engine ([#2018](https://github.com/arcships/dim/issues/2018)) as the native profile's crate-private implementation: it executes this owner's transactions over the `settings_documents` rows. The rows and their request, reply and error shapes are this contract's ([Native-profile row operations](#native-profile-row-operations)); the engine answers no Settings read or write on its public face. - The caller's row: a source id and the registration are bound to the row that registered them; an id from another row is `invalid`. @@ -117,23 +122,24 @@ let bytes = storage.read(definitions, cancelled).await?; // FileStorage's operat | Operation | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `register` | Make a document addressable under the calling row, checked once | `{source, userFile, projectFile?, schema}` | `{id}` | None; a refusal fails the row's `apply` | `invalid` | -| `read` | The document a source id names, as stored now | `{id, scope}` | `{document}` | While the document is read | `invalid`, `invalid_document`, `too_large`, `closed`, `cancelled` | -| `change` | Apply one change to a document under the owner's exclusion | `{id, scope, change}` | `{}` | Before the write; the change's future is dropped | `invalid`, `invalid_document`, `user_only`, `rejected`, `too_large`, `unsynced`, `closed`, `cancelled` | -| `read_user` | The user's draft base for a document | `{source}` | `{revision, document}` | While the document is read | `unknown_source`, `invalid_document`, `too_large`, `closed`, `cancelled` | -| `replace_user` | Replace a document with the draft the user edited at the revision read | `{source, expectedRevision, document}` | `{revision}` | Before the write | `unknown_source`, `invalid_document`, `conflict`, `too_large`, `unsynced`, `closed`, `cancelled` | -| `agent_read` | A document for the agent, user-only secrets withheld | `{source}` | `{document, writeOnly}` | While the document is read | `unknown_source`, `invalid_document`, `too_large`, `closed`, `cancelled` | -| `agent_set` | Set one member of a document on the agent's behalf | `{source, member, value}` | `{document, writeOnly}` | Before the write | `unknown_source`, `invalid`, `user_only`, `invalid_document`, `too_large`, `unsynced`, `closed`, `cancelled` | -| `declared_sources` | The declarations a live row registered | `{instance}` | `{sources}` | None; the owner completes the read | None | -| `authorize_project` | Admit a cwd as a project root; the same cwd answers the same project | `{cwd}` | `{project}` | While FileStorage opens the directory | `invalid`, `closed`, `cancelled` | -| `authorized_projects` | The projects authorized in this process | `{}` | `{projects: [{project, cwd}]}` | None | `closed` | +| `register` | Make a document addressable under the calling row, checked once | `{source, userFile, projectFile?, schema, userOnly}` | a source id | None; a refusal fails the row's `apply` | `invalid` | +| `read` | The document a source id names, as stored now | `{id, scope}` | `{document}` | While the document is read | `invalid`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled` | +| `change` | Apply one change to a document under the owner's exclusion | `{id, scope}` and the change callback | `{}` | Before the write; the change's future is dropped | `invalid`, `invalid_document`, `user_only`, `rejected`, `too_large`, `unsynced`, `failed`, `closed`, `cancelled` | +| `read_user` | The user's draft base for a document, by source id | `{id, scope}` | `{revision, document}` | While the document is read | `invalid`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled` | +| `replace_user` | Replace a document with the draft the user edited at the revision read | `{id, scope, expectedRevision, document}` | `{revision, document}` | Before the write; an admitted write still commits | `invalid`, `invalid_document`, `conflict`, `too_large`, `unsynced`, `failed`, `closed`, `cancelled` | +| `agent_read` | A declared document for the agent, `writeOnly` members withheld | `{source}` | `{document, writeOnly}` | While the document is read | `unknown_source`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled` | +| `agent_set` | Set one member of a declared document for the agent | `{source, member, value}` | `{document, writeOnly}` | Before the write | `unknown_source`, `invalid`, `user_only`, `invalid_document`, `too_large`, `unsynced`, `failed`, `closed`, `cancelled` | +| `declared_sources` | The declared sources, by name: all of them, or those a live row registered | `{instance?}` | `{sources: [{id, source, schema, scopes, userOnly, writeOnly}]}` | None; the owner completes the read | None | +| `authorize_project` | Admit a cwd as a project root; the same cwd answers the same number | `{cwd}` | `{root}` | While FileStorage opens the directory | `invalid`, `failed`, `closed`, `cancelled` | +| `authorized_projects` | The projects authorized in this process generation | `{}` | `{projects: [{root, cwd}]}` | None | None | Data: -- `SourceId` is the id `register` assigns; it is bound to the row that registered it, and a caller from another row is `invalid`. +- `SourceId` is the id `register` assigns; it is bound to the row that registered it, and a caller from another row is `invalid`. `declared_sources` lists only declared sources; a Rust source's id is not listed. - `Document` is one JSON object; a missing user document reads as its default document. -- `Scope` is `"user"` or `{"project": ProjectId}`. `ProjectId` is this process's project id; a project id from another process is not accepted. -- `ChangeFn` is `Fn(Option) -> Result`: it is called once, under the document's exclusion, with the current document, and returns the next document or its own refusal. It must only compute; waiting on another owner or on I/O inside the change holds the document for that whole wait. +- `Scope` is `"user"` or `{"project": }`. The number is this process's project number, assigned by `authorize_project`; it is not durable and it is not FileStorage's root id. +- `userOnly` lists JSON Pointers to members only the user changes. Each pointer must name a member reachable through the schema's `properties`; otherwise `register` is `invalid`. +- `ChangeFn` is `Fn(Option) -> Result`: it is called once, under the document's exclusion, with the current document, and returns the next document or its own refusal. It must only compute; waiting on another owner or on I/O inside the change holds the document for that whole wait. - `Revision` is an opaque value that changes on every committed write. Only the user path carries it, as the draft base the client holds: a business concurrency control between the user's read and write. An owner change carries no revision; the owner's exclusion and any waiting stay inside `change`. - `writeOnly` lists the JSON Pointers of members withheld from the agent and holding a value. @@ -143,19 +149,19 @@ The native profile stores each user document as a `settings_documents` row. Thes | Operation | Intent | Request | Reply | Errors | | --- | --- | --- | --- | --- | -| `readUser` | One source's stored user document | `{source}` | `{version, document}` or none | `storage` | -| `importUserIfAbsent` | Import the validated file content when the row is absent, in one transaction, and return the winning row | `{source, document, importedRevision}` | `{version, document}` | `storage` | -| `changeUser` | Apply one change under the row's exclusion | `{source, change}` | `{version, document}` | `rejected`, `storage` | -| `replaceUser` | Replace a user document at an expected version | `{source, expectedVersion, document}` | `{version}` | `conflict`, `missing`, `overflow`, `storage` | +| `readUser` | One source's stored user document | `{source}` | `{version, document}` or none | `failed` | +| `importUserIfAbsent` | Import the validated file content when the row is absent, in one transaction, and return the winning row | `{source, document, importedRevision}` | `{version, document}` | `failed` | +| `changeUser` | Apply one change under the row's exclusion | `{source}` and the change callback | `{version, document}` | `rejected`, `failed` | +| `replaceUser` | Replace a user document at an expected version | `{source, expectedVersion, document}` | `{version}` | `conflict`, `missing`, `overflow`, `failed` | -`change` in the public operations is `changeUser` on the native profile and FileStorage's `update` on the file profile; `replace_user` is `replaceUser` and FileStorage's `update`, which compares the revision Settings carries. `importUserIfAbsent` runs on the first read of a source whose file exists and whose row does not; a version is a positive integer that increases on every committed write, and the revision Settings publishes is derived from it. +`change` in the public operations is `changeUser` on the native profile and FileStorage's `update` on the file profile; `replace_user` is `replaceUser` and FileStorage's `update`. On the file profile, Settings reads the current revision inside the FileStorage `update` callback and compares `expectedRevision` there; FileStorage holds only the file key and knows no version. `importUserIfAbsent` runs on the first read of a source whose file exists and whose row does not; a version is a positive integer that increases on every committed write, and the revision Settings publishes is derived from it. ### Facts | Fact | Channel | Payload | | --- | --- | --- | | A document was written | `settings/` | `{source, scope, revision}` | -| A project was authorized | `settings/projects` | `{project, cwd}` | +| A project was authorized | `settings/projects` | `{root, cwd}` | A fact is published after the commit and never carries a document. A failed fact delivery is recorded and does not undo the write. @@ -163,14 +169,15 @@ A fact is published after the commit and never carries a document. A failed fact | Kind | What the caller does next | | --- | --- | -| `invalid` | Fix the input: a declaration whose name or file is taken or whose schema or default document is refused, a source id from another row, an unknown project, a project scope for a source without a project file, a member pointer that names no member | -| `unknown_source` | The source is not registered now: retry after its owner registers it, or report that the feature is off | +| `invalid` | Fix the input: a declaration whose name or file is taken, whose schema is refused, or whose user-only pointer names no reachable member; a source id from another row; an unknown project; a project scope for a source without a project file; a member pointer that names no member | +| `unknown_source` | The declared source is not registered now, or it is a Rust source that the client and agent paths do not serve: retry after its owner registers it, or report that the feature is off | | `invalid_document` | The document as stored, or the one the change produced, fails its check; repair the user's document or fix the change | | `user_only` | The change or the agent named a member only the user changes; ask the user, or leave the member as it is | | `rejected` | The change refused with its own `code` and `message`; act on that code | | `conflict` | The user's draft is stale; read again and let the user decide | | `too_large` | The document exceeds the document limit; the caller must not treat the value as a document | -| `unsynced` | The document is in place but its durability is unconfirmed; a read sees the write, and a repeated change confirms it | +| `unsynced` | The document is in place but its durability is unconfirmed; read it and do not repeat a change without reading | +| `failed` | Storage or persistence failed: a FileStorage read or write, a row transaction, or a worker; read again before retrying | | `closed` | This generation is unloading; call the replacement generation | | `cancelled` | Nothing changed: the read stopped, or the change stopped before the write | @@ -179,26 +186,38 @@ A fact is published after the commit and never carries a document. A failed fact | Operation | Normal path | Caller cancels | Caller unloads | Owner closes or reloads | Settled by | | --- | --- | --- | --- | --- | --- | | `change` | Take the document's exclusion, read the current document, call the change, check the result, write it, publish, release | Before the write: the change's future is dropped, the document is unchanged, the exclusion is released, `cancelled` | The row's `apply` future ends; the same release applies | New calls are refused; an in-flight change finishes or ends `closed`; the generation releases its exclusions | Exclusion by Settings; the change's future by the calling row | -| `replace_user` | Take the exclusion, read the current revision, refuse a stale base, check and write the document, publish, release | Before the write: nothing changed, `cancelled` | The call ends `cancelled` | In-flight calls finish or end `closed` | Exclusion by Settings | -| `read`, `agent_read` | Open the document through its profile, check it, return the value | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | File handle or row read by Settings or its store | -| `authorize_project` | Open the directory through FileStorage's `add_root`, append to the project table, publish the fact | Before the directory is opened or the row is appended | The call ends `cancelled`; a later call for the same cwd completes the authorization | New calls are refused; the table survives for the next generation, so a project id stays valid | Directory by FileStorage; the project table by Settings | +| `replace_user` | Take the exclusion, read the current revision, refuse a stale base, check and write the document, publish, release | An admitted write still commits or ends `unsynced`; a wait dropped before admission changes nothing | The admitted write completes; the reply may be lost | In-flight calls finish or end `closed` | Exclusion by Settings; the admitted write by Settings | +| `read`, `read_user`, `agent_read`, `declared_sources`, `authorized_projects` | Open the document through its profile or read the registry, check it, return the value | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | File handle or row read by Settings | +| `authorize_project` | Open the directory through FileStorage's `add_root`, append to the project table, publish the fact | Before the directory is opened or the row is appended | The call ends `cancelled`; a later call for the same cwd completes the authorization | The table is generation state: a new generation starts empty and a cwd is authorized again at admission | Directory by FileStorage; the project table by Settings | | `register` | Check the declaration, insert under the calling row, return the id | Not cancellable; a failed `apply` ends the row | The registration is withdrawn with the row; its documents stay | The new generation starts with no registrations; the documents stay | Registration lifetime by the calling row | ## Exceptions with reasons - The user path carries a draft revision and the owner path does not: the client's business decides whether a write still applies to the document the user read, while an owner change always applies to the current document; the revision is not a version the owner checks on the owner path. -- A document's revision is a value for consumers of the fact, not a write parameter on the owner path: two owners that must agree on a version read the fact and compare revisions. -- `unsynced` reports a write that is in place with unconfirmed durability: a later read sees it, and a repeated change is idempotent, so the caller must not assume the first call failed. +- `unsynced` reports a write that is in place with unconfirmed durability: a read sees it, and a repeated change applies again, so the caller reads before repeating. - On the native profile the first read imports the user file into the row when the row is absent: the import is internal state migration, not an operation, and the file stays where it is. -- A project id stays valid across a reload because FileStorage's root table is append-only ([FileStorage](FileStorage.md)); the id is a value, not a handle and not an authority. +- The project table is process-generation state: a project number is not durable and does not survive a Settings reload; a caller that needs a project after a reload resolves its cwd again at admission, which re-authorizes it. +- A client write is admitted when it starts: a disconnected client does not undo it, so the reply may be lost while the document is written or `unsynced`. + +## Supersedes + +- [Settings service](../appserver/settings-service.md) §4.2 (the `settings` service) and §4.5 (the Rust binding); §4.3 is [SettingsMethods](SettingsMethods.md)'s. The document's §3 state, §4.1 shapes, §4.4 events, §6 errors' state meanings, §7 security and §11 acceptance stay in force; §4.1's `Scope` is the `Scope` below and §4.4's `project_authorized` payload keeps `{root, cwd}`. +- [Settings service](../appserver/settings-service.md) §8.1's note that Rust owners keep their own methods stays; the methods' shapes are in each owner's contract. +- [Resource owner operations](../contracts/resource-owner-operations.md) §Settings. +- [Service faces](../service-faces.md) §3.3's `settingsService` row, §3.2's host-port sentence for the three prompt ports, and §4.1's `settingsService` paragraph. +- [Management methods](../appserver/management-methods.md)'s `settings.read`/`update`/`sources`/`projects` list. +- [Prompt overrides](../appserver/prompt-overrides.md) §3.1 (the three prompt ports are one service; see [PromptSettings](PromptSettings.md)). +- [Permission command rules](../appserver/permission-command-rules.md) §4.1's `commandRules` service (see [PermissionRules](PermissionRules.md)). ## Rule check +Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). + | Rule | Application | | --- | --- | | §1 parts and Capabilities | Settings is one process part. It publishes facts and folds no state, so it is not a Capability. | | §2 scopes | Process: documents and the project table outlive Sessions. Session and branch parts read values or follow facts; none registers a source. | -| §3 orthogonality | Settings reads no other owner's state except through FileStorage's operations and the native store's operations; no plugin's business appears in this contract. | +| §3 orthogonality | Settings reads no other owner's state except through FileStorage's operations and the storage engine's transactions; no plugin's business appears in this contract. | | §4 rule 1 | A committed write is a fact on `settings/`; a refused write publishes nothing. | | §4 rule 2 | No handoff. | | §4 rule 3 | No `before` callback. `change` runs under the document's exclusion, never inside the Timeline's commit lock. | @@ -208,17 +227,18 @@ A fact is published after the commit and never carries a document. A failed fact | §4 rule 7 | Callers use these operations; no caller reads a file path, a lock or a stage. | | §4 rule 8 | The storage engine executes this owner's crate-private row operations ([#2091](https://github.com/arcships/dim/pull/2091)); no new infrastructure. | | §4 rule 9 | A revision fact is written only after the commit; no scratch state is persisted. | -| §7 objects | Only values cross: documents, source ids, project ids, revisions and the `change` callback by reference. No object, handle or path crosses. | +| §7 objects | Only values cross: documents, source ids, project numbers, revisions and the change callback by reference. No object, handle or path crosses. | | §7 no proxy | No operation answers another owner's data: a value is requested from the part that owns it, and workflow definition bytes come from FileStorage for the Workflow plugin. | | §7 one face | One service on the `Settings` type; no facade, no wrapper type, no second name. | | §7 cross-language | Every operation's request, reply and errors are data; the Rust binding is the appendix. | -| §7 caller complexity | The revision, exclusion, retry and durability stay inside Settings; the caller handles `conflict`, `user_only` and `rejected` only. | +| §7 caller complexity | The revision, exclusion, retry and durability stay inside Settings; the caller handles `conflict`, `user_only`, `rejected` and `unsynced` only. | | §7 one change | The old `settings`/`settingsService` surfaces and their callers are migrated in one change; PluginManager, SettingsMethods and every source owner appear in the delivery table. | | ADR 002 D1 | Process scope; documents and the project table outlive Sessions. | | ADR 002 D2 | No wiring plugin; the service is on the owner type. | | ADR 002 D3 | Dependencies point to FileStorage and the storage engine; the rows belong to Settings and no plugin depends on Settings' internals. | | ADR 002 D4 | Business configuration lives in the owner's named source, read at use time; structural items stay in PluginManager. | | ADR 002 D5 | The contract is language-neutral; the Rust binding is the appendix. | +| ADR 027 | Not applicable: every caller is at the process scope or depends outward, so no cross-scope id resolution is involved. | | §7.2 checks | Every caller need lands on one operation; no handle, object or proxy crosses; one face; no Rust-only method on the face; no caller mechanism; one change. | ## Requirements raised to mechanism owners @@ -234,17 +254,23 @@ The service is marked on the owner type; the wire name stays `settings`. The `Se ```rust use dim_agent_runtime::PublicService; use rutis::host::BoxFuture; +use rutis::Ctx; use serde_json::Value; use std::sync::Arc; pub type SourceId = String; -pub type ProjectId = String; +/// The process-local project number `authorize_project` assigns; it is not durable. +pub type ProjectId = u64; pub type Revision = String; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Registered { - pub id: SourceId, +pub struct Register { + pub source: String, + pub user_file: String, + pub project_file: Option, + pub schema: Value, + pub user_only: Vec, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -255,60 +281,234 @@ pub struct Document(pub Value); #[serde(rename_all = "camelCase")] pub enum Scope { User, - Project { project: ProjectId }, + Project(ProjectId), } +impl Scope { + fn project(&self) -> Option { + match self { + Self::User => None, + Self::Project(project) => Some(*project), + } + } +} + +/// One document's replacement from the change callback: its own `code` and `message`. #[derive(Debug, thiserror::Error)] #[error("{code}: {message}")] -pub struct Rejected { +pub struct ChangeRefused { pub code: String, pub message: String, } -pub type ChangeFn = - Arc) -> BoxFuture<'static, Result> + Send + Sync>; +/// A callback's refusal arrives as the wire's own error; its code and message are kept. +impl From for ChangeRefused { + fn from(error: rutis::host::CallError) -> Self { + let code = error + .raw() + .and_then(|raw| raw.downcast_ref::()) + .and_then(rutis_bridge::session::Error::code) + .unwrap_or("rejected") + .to_owned(); + Self { code, message: error.to_string() } + } +} + +pub type ChangeFn = Arc< + dyn Fn(Option) -> BoxFuture<'static, Result> + Send + Sync, +>; + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Read { + pub id: SourceId, + pub scope: Scope, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Snapshot { + pub document: Document, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UserSnapshot { + pub revision: Revision, + pub document: Document, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReplaceUser { + pub id: SourceId, + pub scope: Scope, + pub expected_revision: Revision, + pub document: Document, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentRead { + pub source: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentSnapshot { + pub document: Document, + pub write_only: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentSet { + pub source: String, + pub member: String, + pub value: Value, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ByInstance { + pub instance: Option, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Declaration { + pub id: SourceId, + pub source: String, + pub schema: Value, + pub scopes: Vec, + pub user_only: Vec, + pub write_only: bool, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Declarations { + pub sources: Vec, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizeProject { + pub cwd: String, +} + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Authorized { + pub root: ProjectId, +} + +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Project { + pub root: ProjectId, + pub cwd: String, +} + +#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorizedProjects { + pub projects: Vec, +} #[derive(Debug, thiserror::Error)] pub enum SettingsError { #[error("{0}")] Invalid(String), - #[error("the settings source is not registered: {0}")] + #[error("{0}")] UnknownSource(String), - #[error("the settings document is invalid: {0}")] + #[error("{0}")] InvalidDocument(String), - #[error("the member {0} is changed only by the user")] + #[error("{0}")] UserOnly(String), #[error("{code}: {message}")] - Rejected { code: String, message: String }, + Refused(ChangeRefused), #[error("the settings revision is stale")] Conflict, - #[error("the settings document is {size} bytes, over the document limit")] - TooLarge { size: u64 }, - #[error("the settings document is in place but its durability is unconfirmed")] - Unsynced, + #[error("{0}")] + TooLarge(String), + #[error("{0}")] + Unsynced(String), + #[error("{0}")] + Failed(String), #[error("the settings service is unloading")] Closed, #[error("the settings call was cancelled")] Cancelled, } +impl SettingsError { + /// The wire `code`; a refused change keeps the callback's own code. + pub fn code(&self) -> &str { + match self { + Self::Invalid(_) => "invalid", + Self::UnknownSource(_) => "unknown_source", + Self::InvalidDocument(_) => "invalid_document", + Self::UserOnly(_) => "user_only", + Self::Refused(refused) => &refused.code, + Self::Conflict => "conflict", + Self::TooLarge(_) => "too_large", + Self::Unsynced(_) => "unsynced", + Self::Failed(_) => "failed", + Self::Closed => "closed", + Self::Cancelled => "cancelled", + } + } +} + +/// The wire error's `{code, message}` shape; derived tags cannot carry the callback's code. +impl serde::Serialize for SettingsError { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeStruct; + let mut out = serializer.serialize_struct("SettingsError", 2)?; + out.serialize_field("code", self.code())?; + out.serialize_field("message", &self.to_string())?; + out.end() + } +} + impl PublicService for Settings {} #[rutis::service(name = "settings")] impl Settings { - pub fn register(&self, request: Register) -> Result { /* ... */ } - pub async fn read(&self, request: Read, cancelled: CancelledFn) -> Result { /* ... */ } - pub async fn change(&self, request: Change, cancelled: CancelledFn) -> Result<(), SettingsError> { /* ... */ } - pub async fn read_user(&self, request: ReadUser, cancelled: CancelledFn) -> Result { /* ... */ } + pub fn register(&self, caller: &Ctx, request: Register) -> Result { /* ... */ } + pub async fn read( + &self, + caller: &Ctx, + request: Read, + cancelled: CancelledFn, + ) -> Result { /* ... */ } + pub async fn change( + &self, + caller: &Ctx, + id: SourceId, + scope: Scope, + change: ChangeFn, + cancelled: CancelledFn, + ) -> Result<(), SettingsError> { /* ... */ } + pub async fn read_user( + &self, + request: Read, + cancelled: CancelledFn, + ) -> Result { /* ... */ } pub async fn replace_user( &self, request: ReplaceUser, cancelled: CancelledFn, ) -> Result { /* ... */ } - pub async fn agent_read(&self, request: ReadUser, cancelled: CancelledFn) -> Result { /* ... */ } + pub async fn agent_read( + &self, + request: AgentRead, + cancelled: CancelledFn, + ) -> Result { /* ... */ } pub async fn agent_set( &self, - request: SetMember, + request: AgentSet, cancelled: CancelledFn, ) -> Result { /* ... */ } pub fn declared_sources(&self, request: ByInstance) -> Declarations { /* ... */ } @@ -323,8 +523,17 @@ impl Settings { // `CancelledFn` is the binding's cancellation argument, not a request field. /// The Rust binding of `register` for a Rust document type: the same operation, with the type as -/// its codec instead of a schema. +/// its codec instead of a schema, and its `USER_ONLY` list as the user-only members. impl Settings { - pub fn register_typed(&self) -> Result { /* ... */ } + pub fn register_typed( + &self, + caller: &Ctx, + ) -> Result { /* ... */ } +} + +/// The Rust document binding gains the user-only rule its source declares. +pub trait BusinessDocument { + // ... `NAMESPACE`, `USER_FILE`, `PROJECT_FILE` as today + const USER_ONLY: &'static [&'static str] = &[]; } ``` diff --git a/docs/design/plugins/SettingsMethods.md b/docs/design/plugins/SettingsMethods.md index 6f3378c0bc..757ed20839 100644 --- a/docs/design/plugins/SettingsMethods.md +++ b/docs/design/plugins/SettingsMethods.md @@ -2,48 +2,57 @@ Scope: process. Issue: [#2017](https://github.com/arcships/dim/issues/2017). -SettingsMethods registers the local client's `settings.*` management methods and calls [Settings](Settings.md)' user operations. This document is the owner's target contract; the client surfaces are in [Settings service](../appserver/settings-service.md) §4.3 and §7. +SettingsMethods registers the local client's `settings.*` management methods and calls [Settings](Settings.md)' user operations. The namespace serves **declared sources only**: a Rust source such as `mcp` is `settings_unknown_source`, and its owner's own namespace is the only way to edit it. ## Use and scope: responsibility split SettingsMethods owns: - The `settings` management namespace: which methods exist, their request and reply data, and the mapping from Settings' errors to the client's error codes. -- The local-only rule: the methods are never served to paired devices or a remote entry. +- The declared-only rule and the source-name resolution: the namespace maps the client's `source` name to the registered declared source's id, and refuses a name whose owner is a Rust document. +- Admission: paired devices are never served the namespace; the authenticated loopback Web entry is served `settings.read` and `settings.update` for its allowlisted sources (`model-log` and `execution`). Callers keep: - The user's draft, its editing flow and what a stale draft means in the client. -- Which source the client edits; the client names sources it knows, and it never learns another owner's document. +- Which declared source the client edits; the client never learns another owner's document, and a Rust source is not reachable here. | Requirement (callers) | Can callers compose it from the operations below without breaking the owner's invariants? | Handling | | --- | --- | --- | -| A local client reads a document to edit it | No: the client reaches management methods only, and the draft base is [Settings](Settings.md) `read_user` | `settings.read` | -| A local client writes the draft it edited | No: the write must carry the draft's base revision, the client's business concurrency control between the user's read and write, and report a stale draft | `settings.update` | -| A client discovers every declared source and its schema | Yes, and no client asks: the CLI reads four sources by name | Not an operation; `settings.sources` is deleted | +| A client reads a declared document to edit it | No: the client reaches management methods only, and the draft base is [Settings](Settings.md) `read_user` | `settings.read` | +| A client writes the draft it edited | No: the write must carry the draft's base revision, the client's business concurrency control between the user's read and write, and report a stale draft | `settings.update` | +| A client lists every declared source and its schema | Yes, and no client asks: the CLI reads five sources by name; the Web pages read their two allowlisted sources by name | Not an operation; `settings.sources` is deleted | | A client lists authorized projects to pass a project scope | Yes, and no client asks: no declared source declares a project file | Not an operation; `settings.projects` is deleted | +| A client edits a Rust-typed source | Yes, through that owner's own namespace (`permission.*`, `collaboration.*`, and so on) | Business | + +Every caller of the namespace: the CLI reads `prompts`, `prompt-suggestion`, `execution`, `model-log` and `workflow`; the Web `DiagnosticsSettings` and `PermissionsSettings` pages read `model-log` and `execution`; the Workflow TypeScript plugin reads the plugin-face `settings` service `projects`, which is not this namespace. ## Caller example -The CLI edits the operator's prompts with the revision it read. The revision is the draft's base, a business value the client holds; the daemon compares it and never exposes the owner's internal version. +The CLI edits the operator's prompts with the revision it read. ```rust #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] struct ReadRequest<'a> { source: &'a str, + scope: Scope, } #[derive(serde::Serialize)] #[serde(rename_all = "camelCase")] struct UpdateRequest<'a> { source: &'a str, + scope: Scope, expected_revision: &'a str, document: &'a JsonObject, } let snapshot: SettingsDraft = client - .typed("settings.read", serde_json::to_value(ReadRequest { source: SOURCE })?) + .typed( + "settings.read", + serde_json::to_value(ReadRequest { source: SOURCE, scope: Scope::User })?, + ) .await?; // The user edits one field; the write is the whole document at the revision read. client @@ -51,6 +60,7 @@ client "settings.update", serde_json::to_value(UpdateRequest { source: SOURCE, + scope: Scope::User, expected_revision: &snapshot.revision, document: &document, })?, @@ -58,13 +68,13 @@ client .await?; ``` -The request is one typed struct, serialized at the client boundary; no request is assembled as an inline JSON literal. +The request is one typed struct, serialized at the client boundary; no request is assembled as an inline JSON literal. The reply keeps `{revision, document}`, the shape today's CLI and Web pages parse. ## Own contract ### Dependencies -- [Settings](Settings.md): `read_user` and `replace_user`. SettingsMethods adds no state and forwards nothing else. +- [Settings](Settings.md): `declared_sources` (no instance) to resolve the client's source name to a declared source id, then `read_user` and `replace_user` with that id. SettingsMethods adds no state of its own beyond the admitted-write task it owns. ### Operations @@ -72,51 +82,70 @@ No service. Two management methods, registered with `managementMethods`: | Method | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `settings.read` | The user's draft base for one document | `{source}` | `{revision, document}` | The call is dropped | invalid params, `settings_unknown_source`, `settings_failed`, reloading | -| `settings.update` | Replace a document with the draft at the revision read | `{source, expectedRevision, document}` | `{revision}` | The call is dropped | invalid params, `settings_unknown_source`, `settings_conflict`, `settings_unsynced`, `settings_failed`, reloading | +| `settings.read` | The user's draft base for one declared document | `{source, scope}` | `{revision, document}` | The call is dropped; nothing changes | invalid params, `settings_unknown_source`, `settings_failed`, `operation_interrupted`, reloading | +| `settings.update` | Replace a declared document with the draft at the revision read | `{source, scope, expectedRevision, document}` | `{revision, document}` | An admitted write commits or ends `settings_unsynced`; a wait dropped before admission changes nothing | invalid params, `settings_unknown_source`, `settings_conflict`, `settings_unsynced`, `settings_failed`, `operation_interrupted`, reloading | -`settings_conflict` means the draft is stale: the client reads again and lets the user decide. `settings_unsynced` means the bytes are in place with unconfirmed durability: read again instead of repeating the write. +Invalid params covers a malformed request, an unknown field, a missing revision, a document that is not an object, and a document the source's schema refuses; for a schema refusal the message is the validator's, and the client shows it as an input error. + +`settings_conflict` means the draft is stale: the client reads again and lets the user decide. `settings_unsynced` means the bytes are in place with unconfirmed durability: read again instead of repeating the write. `operation_interrupted` means the call was cancelled or its part is unloading; the client re-reads before retrying. `reloading` means the daemon is restarting. ### Errors | Kind | What the caller does next | | --- | --- | -| invalid params | Fix the request: an unknown field, a missing revision, or a document that is not an object | -| `settings_unknown_source` | The source is not registered now; report that the feature is off and retry after its owner registers it | +| invalid params | Fix the request or the draft: an unknown field, a missing revision, a document that is not an object, a schema violation (the message is the validator's) | +| `settings_unknown_source` | The source is not registered now, or it is a Rust source this namespace does not serve; report that the feature is off, or use that owner's namespace | | `settings_conflict` | Read again; the user's draft is stale | | `settings_unsynced` | Read again; the write is in place | -| `settings_failed` | Read again before retrying; the store refused or failed without a code the client can act on | +| `settings_failed` | Read again before retrying; the store failed without a code the client can act on | +| `operation_interrupted` | The call was cancelled or its part is unloading; read again before retrying | | reloading | The daemon is restarting; retry after it is back | ### Flows -| Operation | Normal path | Caller cancels | Owner closes or reloads | Settled by | +| Operation | Normal path | Caller cancels | Caller closes or the row unloads | Settled by | | --- | --- | --- | --- | --- | -| `settings.read` | Call [Settings](Settings.md) `read_user`, map the reply | Nothing changes | Pending calls end `reloading` | Settings | -| `settings.update` | Call [Settings](Settings.md) `replace_user`, map the reply | Before Settings writes: nothing changes, `settings_failed` or `reloading` | In-flight calls finish or end `reloading` | Settings | +| `settings.read` | Resolve the declared source id, call [Settings](Settings.md) `read_user`, map the reply | Nothing changes; no reply | Pending calls end `operation_interrupted` | Settings | +| `settings.update` | Resolve the declared source id, admit the write into this part's task, call [Settings](Settings.md) `replace_user`, map the reply | An admitted write still commits or ends `settings_unsynced`; dropping the wait does not undo it | Admitted writes settle before the part closes | Settings owns the write; SettingsMethods holds the admitted task | + +## Supersedes + +- [Settings service](../appserver/settings-service.md) §4.3. +- [Management methods](../appserver/management-methods.md)'s list of four `settings.*` methods. + +## Client-visible changes + +- The management methods `settings.sources` and `settings.projects` are removed. No repository client calls them: the CLI reads five sources by name, the Web `DiagnosticsSettings` and `PermissionsSettings` pages read their two allowlisted sources by name, and no declared source has a project file. An out-of-repo client that listed sources or projects reads the sources it knows by name instead; its `settings.read` and `settings.update` requests and replies keep their shapes, including `scope` and the `{revision, document}` update reply. +- `settings.read` and `settings.update` keep the project scope field; the number is Settings' own process-local project number, which is what the request already carried. +- No error code, field name or notification name changes. ## Exceptions with reasons -- `managementMethods` is a mechanism registration point, not a forwarding facade: the namespace belongs to this part because Rpc reaches Settings through Agents and may not reach a management owner ([ADR 004](../../adr/004-loader-plugin-management.md) D4), and the mapping from Settings' kinds to the client's codes is this part's own contract. +- `managementMethods` is a mechanism registration point, not a forwarding facade: the namespace belongs to this part because Rpc reaches Settings through Agents and may not reach a management owner ([ADR 004](../../adr/004-loader-plugin-management.md) D4), and the declared-only rule and the client's error codes are this part's own contract. +- The client's request and reply shapes stay as today's protocol: existing CLI and Web callers send `{source, scope, expectedRevision, document}` and parse `{revision, document}`, and the redesign changes plugin-facing surfaces, not the client protocol. +- `settings.sources` and `settings.projects` are deleted, not moved: no client calls them (the CLI reads five sources by name, the Web pages two, and no declared source has a project file). ## Rule check +Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). + | Rule | Application | | --- | --- | | §1 parts and Capabilities | One process part, no Timeline facts, no folded state: not a Capability. | | §2 scopes | Process; the methods are client surfaces, not Session state. | -| §3 orthogonality | No state of its own; one dependency, [Settings](Settings.md). | +| §3 orthogonality | No state of its own; one dependency, [Settings](Settings.md), plus the admitted-write task it owns. | | §4 rule 1 | No event. | -| §4 rule 7 | Clients use management methods; they learn no file name, path or lock. | +| §4 rule 7 | Clients use management methods; they learn no file name, path, id or lock. | | §4 rule 8 | No infrastructure change; the existing `managementMethods` mechanism is used. | | §7 objects | Request and reply are data; no object, handle or path crosses. | -| §7 no proxy | Settings answers the document; SettingsMethods maps the errors and owns the namespace. | +| §7 no proxy | Settings answers the document; SettingsMethods owns the namespace, the declared-only rule and the error mapping. | | §7 one face | The management namespace exists once; the service operations stay on [Settings](Settings.md). | | §7 cross-language | Both methods are data. | -| §7 caller complexity | The revision reaches the client because the user's draft depends on it; nothing else of Settings' mechanism does. | -| §7 one change | `settings.sources` and `settings.projects` are deleted with this change; the CLI is the only caller migrated. | +| §7 caller complexity | The revision reaches the client because the user's draft depends on it; the declared-only rule and the error mapping stay here. | +| §7 one change | `settings.sources` and `settings.projects` are deleted with this change; the CLI and the Web pages are migrated in the same change. | | ADR 002 D2 | No wiring plugin: the namespace owner is a process part that depends on Settings, as PermissionRules owns `permission`. | | ADR 002 D4 | Business configuration stays in Settings sources; the methods carry no structural item. | +| ADR 027 | Not applicable: the callers are clients of a process-scope service. | ## Requirements raised to mechanism owners @@ -124,4 +153,4 @@ None. ## Binding appendix -No service and no Rust binding: the two methods are registered with `managementMethods`. The request and reply types are the client's JSON shapes in the operations table. +No service and no Rust binding: the two methods are registered with `managementMethods`. The request and reply types are the client's JSON shapes in the operations table; the CLI's `ReadRequest` and `UpdateRequest` above are the Rust spelling of the same data. diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index 0cf6cd6437..bb60d13479 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -101,7 +101,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `worktreeAssociations` | `store.associateWorktree` | 形状见 §4.8。 | | `toolSourcesView` | `toolSourcesView.get/observe` | 同一 ToolRegistry owner 的独立只读观察面;贡献注册仍由 `toolRegistry` 负责,见 [工具贡献 §7.5](../architecture/rust-agent/tool-contributions.md#75-服务接口)。 | -宿主读取端口的数据面(§4.10)包括 `executionSettingsHost`、`toolchainSourceHost`、`promptSuggestionSettingsHost`。模型选择与列表统一由 `providerService` 提供;调用方和配置见[进程操作](contracts/process-owner-operations.md);其余读取端口沿用现名。 +宿主读取端口的数据面(§4.10)包括 `executionSettings`、`toolchainSourceHost`、`promptSuggestionSettings`;前两者的操作由 [ExecutionSettings](plugins/ExecutionSettings.md) 与 [PromptSuggestionSettings](plugins/PromptSuggestionSettings.md) 定义。模型选择与列表统一由 `providerService` 提供;调用方和配置见[进程操作](contracts/process-owner-operations.md);其余读取端口沿用现名。 ### 3.3 所有者 API,已有数据兄弟 @@ -110,7 +110,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | 名字 | 数据兄弟 | 说明 | | --- | --- | --- | | `agentIndex` | `sessions` | 目录查询走 `sessions` | -| `settingsService` | `settings` | GoalBranch 的取消契约见 §4.1。 | +| `settingsService` | `settings` | 已由 [Settings](plugins/Settings.md) 取代:一个服务标注在所有者类型上,不保留 owner API 行。 | | `modelHost` | `modelHost` | 完整模型请求直接调用所选配置的执行入口;辅助请求使用 `providerService.complete`。 | | `loader` | `rutis/loader` | 插件管理走数据面 | | `sessionStore` | `store`、`sessionFiles`、`timelineStore` | 标题与 worktree 关联直接调 store | @@ -216,7 +216,7 @@ PromptSettings 的三个只读端口按 [prompt overrides §3.1](appserver/promp ### 4.1 `settingsService`:保留调用取消 -迁移前 `GoalBranch` 继续用类型化调用,读取随 branch stop token 取消。设置 owner 在 #1292 的批次内确定如何将调用方取消传递给读取操作,并验证 `settings.read` 的 `SettingsResult` 信封和现有错误语义。Goal 切到同一数据契约的 Rust 绑定时,覆盖分支停止中断设置读取的流程。 +已由 [Settings](plugins/Settings.md) 与 [SettingsMethods](plugins/SettingsMethods.md) 取代:所有者按 source id 读值,调用方的取消随读取结束;GoalBranch 的读取改走该绑定。 ### 4.2 `modelHost`:保留完整模型请求 diff --git a/docs/design/subagent-model-policy.md b/docs/design/subagent-model-policy.md index b933a994f5..e9dcd53fc9 100644 --- a/docs/design/subagent-model-policy.md +++ b/docs/design/subagent-model-policy.md @@ -53,7 +53,7 @@ decision by an LLM. `agent` means the existing request/profile selection behavio | Identify the requesting branch | `CollaborationSession::request` already receives `branch_id`; pass it within Collaboration, without changing an event or tool request | | Read the adopted leader model | `Session::get(branch_id)` while consuming `collaboration/request`, before starting its delivery task | | Resolve an explicit model | The existing `AgentIndex` model-selection host and configured/non-catalog profile paths | -| Persist and edit policy | Native `BusinessDocument`, `SettingsService::read/update`, source CAS and owner management methods, as used by `permission_rules.rs` | +| Persist and edit policy | [CollaborationModelPolicy](../plugins/CollaborationModelPolicy.md): the `collaboration` source, its `policy` value read and the `collaboration.*` methods | | Start/restore and retain members | Existing Agents/Collaboration Session creation, usage holds and cleanup, including idle unloading | Do not use `leader.config().model` or `session.summaries` as the adopted leader model: From fcf1dd550096d267cc37133c425be67a0360952d Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 11:26:05 +0800 Subject: [PATCH 6/8] design(settings): align the contracts with the callee and the review Depend on FileStorage operations that exist in #2080: the host registers roots and hands their paths as values, so Settings and ModelLog take the home directory from the assembly and Settings reads and updates documents by absolute path. The refusal is a Rejected variant whose wire code is rejected and whose callback code is reason; the appendix compiles in a temporary crate. Scope the source-id row binding to read and change, rename the declaration hint to writeOnlyHint, split the sync operations from the cancelled ones, and correct the examples and retained documents the review named. --- docs/design/appserver/prompt-overrides.md | 58 +++----- docs/design/appserver/settings-service.md | 105 +-------------- docs/design/overview.md | 6 +- docs/design/plugins/AgentSettings.md | 2 +- docs/design/plugins/ContextCompaction.md | 2 +- docs/design/plugins/ExecutionSettings.md | 10 +- docs/design/plugins/ModelLog.md | 10 +- docs/design/plugins/PluginManager.md | 4 +- docs/design/plugins/PromptSettings.md | 8 +- .../plugins/PromptSuggestionSettings.md | 2 +- docs/design/plugins/ProviderSettings.md | 6 +- docs/design/plugins/Settings.md | 124 +++++++----------- docs/design/plugins/SettingsMethods.md | 8 +- docs/design/service-faces.md | 13 +- docs/design/subagent-model-policy.md | 2 +- 15 files changed, 116 insertions(+), 244 deletions(-) diff --git a/docs/design/appserver/prompt-overrides.md b/docs/design/appserver/prompt-overrides.md index 8bbacf562f..38839d49be 100644 --- a/docs/design/appserver/prompt-overrides.md +++ b/docs/design/appserver/prompt-overrides.md @@ -36,14 +36,14 @@ adopted. ```text App Server process row: PromptSettings registers Settings source "prompts" - provides three ports from the same document + owns one promptSettings service | - +--------------------------+--------------------------+ - | | | - BasePromptSettingsHost SkillsInstructionsSettingsHost SummaryPromptSettingsHost - | | | - PromptSources part Skills part ProductSummaryStrategy part - (dim/base) (dim/skills/instructions) (summary prompt) + +------------------+------------------+ + | | | + base() skills() summary() + | | | + PromptSources part Skills part ProductSummaryStrategy part + (dim/base) (dim/skills/instructions) (summary prompt) \ | / read once while the Session part applies ``` @@ -80,13 +80,10 @@ are its normal surface; in the file-backed profile it is `prompts.json` under th ## 3. Host ports and precedence -Each owner declares its own port, so a capability depends only on its own text: - -| Owner | Port | Reads | -| --- | --- | --- | -| PromptSources | `BasePromptSettingsHost` | `base` | -| Skills | `SkillsInstructionsSettingsHost` | `skills` | -| ContextCompaction | `SummaryPromptSettingsHost` | `summary` | +Each capability reads only its own text. The owner service is [PromptSettings](../plugins/PromptSettings.md); a +capability outside the App Server depends on the port trait in `dim-agent-capabilities` for its text: +`BasePromptSettings` for PromptSources, `SkillsInstructionsSettings` for Skills and +`SummaryPromptSettings` for ContextCompaction. - The port is optional (`Option>`): an assembly that does not register the name, such as the capability tests or a host without Settings, injects nothing and keeps its built-in text. @@ -105,8 +102,8 @@ Superseded by [PromptSettings](../plugins/PromptSettings.md): one service `promp ## 4. Client entry The settings methods are the primitive: `settings.read` and `settings.update` with -`source: "prompts"`, `scope: "user"`. `settings.sources` publishes the schema, and both methods -are management methods, so only a local connection can edit the texts. +`source: "prompts"`, `scope: "user"`. The client knows the three member names; `settings.sources` +is deleted. Both methods are management methods, so only a local connection can edit the texts. The native client presents each field as plain text rather than JSON: @@ -172,37 +169,18 @@ Rules: [design rules](../../architecture/rust-agent/principles.md) §1 and §4, | Rule | How this design complies | | --- | --- | -| §1 Plugins and capabilities bounded | Each text stays in its owner; the App Server owns only the Settings document and the ports | +| §1 Plugins and capabilities bounded | Each text stays in its owner; the App Server owns the document and the one service, and each capability depends on its own port trait | | §4 rule 4 No business meaning in core | No core type gains a prompt text; the ports are capability-level contracts | | §4 rule 6 Context from consumed events | The text reaches the model through the existing adopted prompt sources; no new context path | -| §4 rule 7 Public events and services | No new event, client method or Timeline fact; the existing Settings methods and three optional process services are used | +| §4 rule 7 Public events and services | No new event, client method or Timeline fact; the existing Settings methods and one optional process service are used | | §4 rule 8 Infrastructure unchanged | No change to Timeline, Dispatcher, rutis or the assembly mechanism | | ADR 002 D1 Scope | The document and ports live at the process scope where the shared configuration is; the texts live in their Session parts | | ADR 002 D4 Configuration | Business configuration stays with its owner; the document is the App Server's source, as `execution` and `prompt-suggestion` are | | ADR 007 D5 Owner registration | A dedicated App Server row registers the source; Settings and the assembly declare none | | ADR 008 D2 No delivery status | This document states the design; the issue tracks delivery | -| ADR 008 D3 Own scope only | The owner documents state their own port; this page states the product setting and the client entry | +| ADR 008 D3 Own scope only | The owner contract states the service and the ports; this page states the product setting and the client entry | ## 7. Binding appendix -```rust -pub trait BasePromptSettings: Send + Sync + 'static { - fn base(&self, cancel: CancellationToken) -> HostFuture<'_, Option>>; -} -pub struct BasePromptSettingsHost(pub Arc); - -pub trait SkillsInstructionsSettings: Send + Sync + 'static { - fn instructions(&self, cancel: CancellationToken) -> HostFuture<'_, Option>>; -} -pub struct SkillsInstructionsSettingsHost(pub Arc); - -pub trait SummaryPromptSettings: Send + Sync + 'static { - fn system_prompt(&self, cancel: CancellationToken) -> HostFuture<'_, Option>>; -} -pub struct SummaryPromptSettingsHost(pub Arc); -``` - -The App Server row registers the `prompts` declaration and provides the three hosts from one -`PromptDocument`; each host reads only its field. Each binding is provided at its Rust type key and -`host_key` for its service name. Its dispatcher calls the same owner method; native -callers invoke that method directly without JSON conversion. +Superseded by the binding appendix of [PromptSettings](../plugins/PromptSettings.md); the three +`*SettingsHost` types are deleted. diff --git a/docs/design/appserver/settings-service.md b/docs/design/appserver/settings-service.md index 3cfe2b2f19..989401b8d4 100644 --- a/docs/design/appserver/settings-service.md +++ b/docs/design/appserver/settings-service.md @@ -198,16 +198,11 @@ plugin unloads. Nothing else is new. Nothing enters the Timeline. ### 4.1 Common shapes -| Shape | JSON | -| --- | --- | -| `Scope` | `"user"` or `{"project": }`. `root` is the project root number Settings assigns in this process (`SettingsScope::Project`). It is not a durable identity and is never persisted | -| `Snapshot` | `{revision: string, document: object}` | -| `Error` | `{code, message}` | -| `Sources` | The `settings.sources` reply (§4.3): `{dialect: string, sources: [{source, schema, scopes, userOnly, writeOnly}]}`. `dialect` is exactly `https://json-schema.org/draft/2020-12/schema`, the draft every `schema` is compiled in (§3.1). `schema` is the registered schema verbatim, `default` members included. `scopes` is `["user"]`, or `["user", "project"]` when the source declares a project file. `userOnly` is the registered pointer list. `writeOnly` hints that the schema root itself or a member reachable through `properties` is marked `writeOnly: true`. A root-level `writeOnly` counts for this hint but is not a hidden member: the redaction (§1.2) removes members reached through `properties` only, so such a source lists `writeOnly: true` and hides nothing. Neither rule scans `items`, `$defs` or `anyOf`, so a client reads `schema` itself for the rest. No item carries a document, a file name or an owner | +Superseded by the Data and binding sections of [Settings](../plugins/Settings.md): `Scope`, `Document`, the declarations, the project table and the error shapes are defined there. ### 4.2 Service `settings` (owner path) -Superseded by [Settings](../plugins/Settings.md): one service on the `Settings` type, one source id per registration, a value read, a change callback, the user draft path and the agent path. §4.1 and §4.4 stay in force. +Superseded by [Settings](../plugins/Settings.md): one service on the `Settings` type, one source id per registration, a value read, a change callback, the user draft path and the agent path. §4.4 stays in force. ### 4.3 Management methods `settings.*` (client path) @@ -245,72 +240,15 @@ Permission does). ### 4.5 Rust binding -Superseded by the binding appendix of [Settings](../plugins/Settings.md). The error variants, events, security boundary and state descriptions of this document stay in force. +Superseded by the binding appendix of [Settings](../plugins/Settings.md). §4.4 events, §7 security, §8.1 and §9 stay in force. ## 5. Flows -### 5.1 Owner reads and updates - -``` - TS owner settings (HostDispatch) SettingsService storage - | read {web, "user"} ---->| decode request | | - | | read_declared ---------->| file / user/web row ---->| - | | | defaults, schema check | - |<-- {revision r1, document} -------------------------| | - | update {web, "user", r1, doc'} ->| update_declared(Owner) | - | | | defaults, schema | - | | | user-only diff vs current| - | | | differs: user_only_field - | | | CAS r1 ------------------>| replace - | | | emit settings.changed {web, "user", r2} - |<-- {revision r2, document} -------------------------| | -``` - -The user-only diff is checked under the same lease (or native transaction) as CAS, against the -document it replaces. - -### 5.2 Client edits a user-only field - -``` - Client Rpc Settings (managementMethods) - | settings.read {web, "user"} ---->| {r2, doc} - | settings.update {web, "user", r2, doc with searchService} -> update_declared(Client) - |<-- {r3, doc} | emit settings.changed {web, "user", r3} - TS owner (its tool asks to change searchService) - | update {web, "user", r3, doc with another searchService} -> user_only_field, nothing written -``` - -### 5.3 Registration - -``` - owner row apply settings (HostDispatch) SettingsService - | register(declaration) ------->| caller = calling row | - | | register_declared -------->| parse (unknown fields rejected) - | | | check name, files, pointers - | | | compile schema; {} with defaults valid - | | | name or file registered? refuse - | | | record; withdrawal = caller's unload - |<-- resolved (or rejected: the row's apply fails) ----------| - owner row unloads -> its sources are withdrawn; their documents stay in the home -``` - -Settings is built whenever there is a product or target home, as before; a plugin that registers -a source needs it. +Superseded by the Flows and Exceptions sections of [Settings](../plugins/Settings.md). The persistence profiles' behavior in §3 stays in force. ## 6. Errors -| Code (service / wire) | When | Retry | -| --- | --- | --- | -| `unknown_source` / `settings_unknown_source` | No source of that name is registered, or (on these paths) it is a Rust source | After its owner registers it | -| `invalid_scope` / invalid params | Project scope for a source without `projectFile`, or a root not authorized | After authorizing the project | -| `invalid_document` / invalid params | Schema violation or a non-object document | No; nothing written | -| `invalid_document` / `settings_failed` | The persisted file or row is invalid (on read) | After the user repairs it | -| `user_only_field` | An owner write changes a user-only field | No; the user changes it through the client | -| `conflict` / `settings_conflict` | Stale `expectedRevision` | Read and retry | -| `unsynced` / `settings_unsynced` | The new content is in place and announced, but could not be synced | Read before retrying | -| `failed` / `settings_failed` | Storage, persistence or worker failure | Read before retrying | -| `closed` / reloading | Settings is unloading | Yes | -| `cancelled` | Call dropped or cancelled | Caller's choice | +Superseded by the Errors table of [Settings](../plugins/Settings.md): `user_only`, `invalid`, `failed` and the other kinds are defined there, with what the caller does next. ## 7. Security @@ -403,38 +341,7 @@ question 2); that is no new requirement on dim runtime or rutis. ## 11. Acceptance (flow tests) -App Server flow tests (`crates/dim-app-server/tests/settings_flow.rs` and a TypeScript row loaded -through C4's path): - -1. A TypeScript test package registers source `example` (user file, project file, schema with a - `default`, one user-only pointer). Its first `read` returns the default document with revision - `missing`. An `update` with that revision stores the document and returns a new revision. A - stale revision fails with `conflict`. A schema violation fails and writes nothing. -2. A client `settings.update` changes the user-only field. The owner's next `update` that changes - it fails with `user_only_field`; one that keeps it succeeds. -3. A Rust listener on `settings_changes("example")` receives `{source, scope, revision}` after - each successful write on both paths, and none after a rejected one. The payload serializes to - the §4.4 JSON shape. -4. Native profile: the user scope persists in row `user/example`; existing v13 rows are unchanged. - Project scope on an unauthorized root fails with `invalid_scope`. -5. `settings.read` of `mcp` returns `settings_unknown_source`. A row registering `mcp`, a second - registration of one source, or a malformed declaration fails the registering row. A source - appears when its owner registers it and is `unknown_source` once the owner unloads, while its - document stays in the home. -6. ~~Credential references through a shared `credentials` store.~~ Withdrawn (§1.2). -7. A paired-device connection is not served `settings.read` or `settings.sources`. -8. An authenticated Web entry connection is answered `unknown_method` for `settings.sources` - and is served the allowlisted `settings.read` for `model-log`. -9. `settings.sources` replies `{dialect, sources: []}` when nothing is registered, lists a - registered declared source with its schema verbatim, its scopes, its user-only pointers and - its `writeOnly` hint, never lists a Rust source, and drops a declared source's entry the - moment its owner unloads, when `settings.read` answers `settings_unknown_source` again. -10. `settings.projects` replies `{projects: []}` before anything is authorized, then lists the - root `session.create` authorized with its canonical cwd, and that root serves - `settings.read` with `{project: root}`; a second authorization of the same cwd adds no item, - a root this process never authorized is invalid params, and a root a client authorized - through `hooks.catalog` for a cwd with no Session is listed too. The list starts empty again - after a daemon restart on the same home. +Superseded by the delivery's flow tests on [#2017](https://github.com/arcships/dim/issues/2017): the owner read/change path, the user draft path, the agent path, the project table and the declared registry are tested there instead of against the deleted `settings.sources`/`settings.projects` methods. ## 12. Implementation status diff --git a/docs/design/overview.md b/docs/design/overview.md index 1ab2c8d9e4..004c640120 100644 --- a/docs/design/overview.md +++ b/docs/design/overview.md @@ -100,7 +100,7 @@ Plugins never add wiring plugins (ADR 002 D2). Each need maps to a mechanism tha | Put content into the model context | Branch input (raw blocks, keyed blocks) or tool results ([session access](contracts/session-access.md#a2-source-input-conventions)) | Goal, Hooks, ShellInput, Scheduler, Workflow | | Act on a write before it is committed | A synchronous Timeline before callback registered by a branch-scoped plugin ([single-tree](../architecture/rust-agent/single-tree.md)): it transforms the draft inside the commit lock, never blocks the write and never waits for external work; the original draft commits on failure ([principles §4 rule 3](../architecture/rust-agent/principles.md)) | None planned | | Client method about a Session | A namespace registered with the Session's `sessionMethods`, which Rpc dispatches through the Session ([A.1](contracts/session-boundary.md#a1-method-contributions)) | Questions, Goal, SessionTitle, Attachments, ShellInput, InputQueue (`session.input.withdraw`) | -| Host management method | A namespace a process plugin registers with `managementMethods`, looked up by Rpc per call | Existing management methods, Settings (business configuration, `settings.read`/`settings.update`/`settings.sources`/`settings.projects`, S8b, implemented), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RemoteGateway | +| Host management method | A namespace a process plugin registers with `managementMethods`, looked up by Rpc per call | Existing management methods, Settings (business configuration, `settings.read`/`settings.update`, S8b, implemented; the two methods serve declared sources), Scheduler, Workflow, ExternalAgent, Modality, PluginManager, RemoteGateway | | Reach other Sessions | Agents' `sessions` service (`launch`, `input`, `history`, `idle`, ...), as Collaboration does ([session access](contracts/session-access.md#a1-the-sessions-service)) | Scheduler, Workflow | | Hand an event to the Sessions that subscribed to it | The process service `eventHub`, which delivers each event through Agents' `sessions` service ([EventHub](plugins/EventHub.md)) | Producers: IM, SaaS and CI notifications, timers, other agents; a Session's `events` tool and clients' `eventhub.*` methods subscribe | @@ -331,7 +331,7 @@ The table in [§3](#3-integration-by-existing-mechanisms) is exhaustive. A new p 6. **Interrupt**: a plugin cancels in-flight work and releases resources before writing terminal facts ([interrupt](../architecture/rust-agent/interrupt.md)). 7. **Admission**: new tools declare a risk category. No new Permission category is added: a risk Permission does not know is unclassified, which ReadOnly denies, WorkspaceWrite asks about and FullAccess allows (`permission.rs`); a tool may still declare a descriptive risk such as `persistent_configuration`. Sessions started by automation use the starter's policy as an upper bound, which Scheduler jobs and Workflow definitions may narrow. Runs started by a management method default to read-only unless declared, capped by host configuration. `workflow` uses the `agent` tool's risk category. 8. **Dependency direction and reload cost**: core parts never depend on optional plugins; an optional plugin's reload or failure affects only its own features (D3). A reload that reaches its real dependents may fail their in-flight turns; this is accepted and documented in each plugin's conflict table, never prevented. -9. **Management plane**: management methods (`account.*`, `provider.*`, `mcp.*`, `skills.*`, `settings.read`/`settings.update`/`settings.sources`/`settings.projects`, and the methods of new process plugins) are registered by process plugins with `managementMethods`; a rutis session's far end reaches that service too ([rutis 0.19 upgrade M8](rutis-0.19-upgrade.md#m8-the-ui-leaf-is-a-plugin-whose-life-is-a-session)). Session methods have no level; `shell.*` is an ordinary Session method. Local RPC serves both kinds, RemoteGateway serves Session methods only, and a rutis session's far end reaches them through the exported `managementMethods` service (trusted local code). There are no identity tiers. `hello`, `daemon.*`, `agent.*` and the existing `session.*` methods stay Rpc built-ins; `daemon.shutdown` is a built-in never served to a paired device (a connection with a `deviceId`). +9. **Management plane**: management methods (`account.*`, `provider.*`, `mcp.*`, `skills.*`, `settings.read`/`settings.update`, and the methods of new process plugins) are registered by process plugins with `managementMethods`; a rutis session's far end reaches that service too ([rutis 0.19 upgrade M8](rutis-0.19-upgrade.md#m8-the-ui-leaf-is-a-plugin-whose-life-is-a-session)). Session methods have no level; `shell.*` is an ordinary Session method. Local RPC serves both kinds, RemoteGateway serves Session methods only, and a rutis session's far end reaches them through the exported `managementMethods` service (trusted local code). There are no identity tiers. `hello`, `daemon.*`, `agent.*` and the existing `session.*` methods stay Rpc built-ins; `daemon.shutdown` is a built-in never served to a paired device (a connection with a `deviceId`). 10. **Remote Session methods**: paired devices may call every Session method, including `session.permission.update` and `shell.*` (compatibility change, [methods A.4](contracts/session-boundary.md#a4-migration-and-compatibility)). 11. **In-flight work**: there is no shared registry. Each owner provides its own query and stop, and the CLI aggregates them. 12. **Withdrawal**: InputQueue owns the withdrawal and conditional queued-input Steer contract ([Session access A.4](contracts/session-access.md#a4-withdrawal)). Every pending-input derivation excludes deleted inputs, which never enter model context (their keyed blocks never take effect). @@ -506,7 +506,7 @@ A **supplement** adds services, methods or configuration. A **change** alters ex | Agents | Supplement | The `sessions` service ([sessions service](appserver/sessions-service.md)); `SessionConfig.interactive`; `launch` with a policy capped by the starter, `LaunchRequest.agent` optional (absent: Agents' default profile; request `model` over the profile's model); creation from another Session's cut ([deletion and fork](appserver/session-deletion-and-fork.md#6-fork)); `session.agent.update` and `session.agent.get` through Agents' Session entry, resolving an exact profile ID for prompt/model adoption and reading back the profile a branch adopted | Scheduler, Workflow, fork, `/agent` | | Collaboration | Change | Member model: the user's [subagent model policy](subagent-model-policy.md) (`agent`: the profile's model, else the default selection; `inherit`; `fixed`); [member permission inheritance and tool-approval routing](subagent-tool-approval.md): new native members sample the requesting branch's current policy; pending member approvals reach that branch as adopted inputs, with leader decision tools under its Approval and Permission and [user review of the original action](cli-commands.md#subagent-tool-approval) (#29, #257); member providers by kind (`collaborationMembers:`, looked up per call) for members that are not dim Sessions, whose asks use the same member-approval route; the `agent` tool keeps its existing risk classification ([ExternalAgent §9.2](plugins/ExternalAgent.md#92-collaboration-member-providers)) | ExternalAgent | | SessionStore | Supplement | Title metadata with revision checks, written only through `setTitle`, with a Session broadcast notice on change (owners of process-level state emit such notices) (S5b, implemented: the `sessionMetadata` service, [title metadata](appserver/session-title-metadata.md)); deletion and cleanup; fork (copies facts before the cut) (S5c, implemented: [deletion and fork](appserver/session-deletion-and-fork.md)); Session files on the resource node, shared on fork and deleted with the last owner (S5a, implemented: the `sessionFiles` service, [session files](appserver/session-files.md)); `session_grants` rows, removed with the Session and never copied to a fork ([ADR 012](../adr/012-session-grants.md)) | SessionTitle, Attachments, fork, SessionGrants | -| Settings | Supplement | S8a (Rust, implemented): one or more named business sources per owner, each holding one document type; no subscription API of its own: a committed write emits the rutis event `settings.changed` `{source, scope, revision}` on `settings/`, for user and project scope, without the body, and a newly authorized project emits `settings.project_authorized`; validation and defaults only at the Settings boundary; additive `user/` rows under the v13 `settings_documents` contract (D4). S8b (with C4, implemented): the language-neutral `settings` service with JSON Schema, defaults, allowed scopes and user-only fields declared on C4 rows; management methods `settings.read`/`settings.update`/`settings.sources`/`settings.projects`; no credential service (§6.4) | Every plugin with business configuration, including user-written Scheduler jobs (source `schedule`) and Workflow definitions (source `workflow`) | +| Settings | Supplement | S8a (Rust, implemented): one or more named business sources per owner, each holding one document type; no subscription API of its own: a committed write emits the rutis event `settings.changed` `{source, scope, revision}` on `settings/`, for user and project scope, without the body, and a newly authorized project emits `settings.project_authorized`; validation and defaults only at the Settings boundary; additive `user/` rows under the v13 `settings_documents` contract (D4). S8b (with C4, implemented): the language-neutral `settings` service with JSON Schema, defaults, allowed scopes and user-only fields declared on C4 rows; management methods `settings.read`/`settings.update` for declared sources; no credential service (§6.4). The target contract is [Settings](plugins/Settings.md) | Every plugin with business configuration, including user-written Scheduler jobs (source `schedule`) and Workflow definitions (source `workflow`) | | Provider | Supplement | Validation and mapping of advertised effort/tier preferences against the captured adopted model configuration; `AuxiliaryModel` service: `complete(model, request)`, one non-streaming call outside any Session, with the model passed by the caller from its own configuration ([design](appserver/auxiliary-model.md)); proposed [Desktop/CLI management supplement](appserver/provider-management.md) for safe connection edits, model lifecycle and client-only preferences; non-conversational connections per Modality category | `/effort`, `/fast`, SessionTitle, Modality | | `pluginFiles` (`PluginFilesPlugin`) | Supplement | Binary read and write and a format version ([trusted plugin storage](../../crates/dim-app-server/README.md#trusted-plugin-storage)); code location unchanged | Scheduler, Workflow, Modality, RemoteGateway, PluginManager, ExternalAgent | | Mcp, Provider, SkillsCatalog, ManagedProviders, OAuth plugins | Change | Register their existing management namespaces with `managementMethods` (wire-compatible); Mcp's `mcp.approve`/`mcp.revoke` are removed, servers run when enabled, and project entries start disabled until the user's local configuration enables them (§6.4 Approval scope) | Rpc migration | diff --git a/docs/design/plugins/AgentSettings.md b/docs/design/plugins/AgentSettings.md index 6620a64f97..8ab7bbb785 100644 --- a/docs/design/plugins/AgentSettings.md +++ b/docs/design/plugins/AgentSettings.md @@ -117,7 +117,7 @@ writable - The tool is registered with the existing `toolRegistry` and `ToolContribution`; it is admitted and executed like every tool. - The read handler calls the setting module's read port. A future write path adds a typed setter and separates the write risk. -Service faces follow the [owner catalog](../../architecture/rust-agent/generated/catalog.md#services): v1 consumes the process `executionSettingsHost` data face with asynchronous `read({})`, and the Session `toolRegistry` data face. The tool's input and result are data; its Rust part is not leaf-ready. +Service faces follow the [owner catalog](../../architecture/rust-agent/generated/catalog.md#services): v1 consumes the process `executionSettings` data face with asynchronous `read({})`, and the Session `toolRegistry` data face. The tool's input and result are data; its Rust part is not leaf-ready. ## 5. Permission diff --git a/docs/design/plugins/ContextCompaction.md b/docs/design/plugins/ContextCompaction.md index fe2dd23d6a..77fb478d06 100644 --- a/docs/design/plugins/ContextCompaction.md +++ b/docs/design/plugins/ContextCompaction.md @@ -1980,7 +1980,7 @@ otherwise — is pinned by `a_length_sentence_needs_one_target_placeholder` in **The product's user override.** The App Server may supply the operator's summary prompt from its `prompts` setting ([prompt overrides](../appserver/prompt-overrides.md)). The port is -`SummaryPromptSettingsHost`, optional and read while the Session's strategy part applies: the +`SummaryPromptSettings` (the port trait in `dim-agent-capabilities`), optional and read while the Session's strategy part applies: the factory `system_prompt` outranks it, a read failure keeps `SYSTEM`, and the value applies to Sessions loaded after the change. The length sentence and the target rule stay factory-only, so a user override changes the prompt and not the size rule. diff --git a/docs/design/plugins/ExecutionSettings.md b/docs/design/plugins/ExecutionSettings.md index 208b476b83..067e75a02b 100644 --- a/docs/design/plugins/ExecutionSettings.md +++ b/docs/design/plugins/ExecutionSettings.md @@ -40,7 +40,7 @@ let switches = execution_settings.read(cancelled.clone()).await.map_err(|error| ### Dependencies - [Settings](Settings.md): `register` for the `execution` source and `read` for its value. -- The Rust port, for consumers outside the App Server: the trait `ExecutionSettingsRead` and the reply type `ExecutionSettings` live in `dim-agent-capabilities` ([`execution_settings`](../../../crates/dim-agent-capabilities/src/execution_settings.rs)). HostPlatform and the `settings` tool depend on the trait; the App Server's `ExecutionSettings` implements it and serves the same read on the wire. +- The Rust port, for consumers outside the App Server: the trait `ExecutionSettingsRead` and the reply type `Switches` live in `dim-agent-capabilities` ([`execution_settings`](../../../crates/dim-agent-capabilities/src/execution_settings.rs)). HostPlatform and the `settings` tool depend on the trait; the App Server's `ExecutionSettings` implements it and serves the same read on the wire. ### Operations @@ -68,7 +68,7 @@ let switches = execution_settings.read(cancelled.clone()).await.map_err(|error| ## Supersedes -- [ADR 011](../../adr/011-execution-settings.md) D1's port name `executionSettingsHost`: the decision is unchanged, the port is `executionSettings` and its Rust binding is `ExecutionSettingsRead`. +- [ADR 011](../../adr/011-execution-settings.md) D1's type `ExecutionSettingsHost` and its service name `executionSettingsHost`: the decision is unchanged. The type is replaced by the owner type `ExecutionSettings`, which implements the port trait `ExecutionSettingsRead`; the wire service is `executionSettings`. - [Service faces](../service-faces.md) §3.2's and §4.10's `executionSettingsHost` entries. ## Rule check @@ -103,6 +103,7 @@ None new. HostPlatform's read at process preparation is unchanged in shape; only ## Binding appendix ```rust +use dim_agent_capabilities::host::{CancelledFn, HostFuture}; use dim_agent_runtime::PublicService; use rutis::host::BoxFuture; @@ -121,6 +122,11 @@ pub enum ExecutionSettingsError { Failed { message: String }, } +// The Rust port, in dim-agent-capabilities; the App Server's ExecutionSettings implements it. +pub trait ExecutionSettingsRead: Send + Sync + 'static { + fn read(&self, cancelled: CancelledFn) -> HostFuture<'_, Result>; +} + impl PublicService for ExecutionSettings {} #[rutis::service(name = "executionSettings")] diff --git a/docs/design/plugins/ModelLog.md b/docs/design/plugins/ModelLog.md index dd1cf81df4..847d478647 100644 --- a/docs/design/plugins/ModelLog.md +++ b/docs/design/plugins/ModelLog.md @@ -28,8 +28,12 @@ Callers keep: The recorder reads the destination while it starts a request. ```rust -let destination = model_log.recording().await.ok().flatten(); -if let Some(directory) = destination.directory { +let destination = model_log + .recording() + .await + .ok() + .and_then(|view| view.directory); +if let Some(directory) = destination { // aimux owns the file under this directory. } ``` @@ -40,7 +44,7 @@ if let Some(directory) = destination.directory { - [Settings](Settings.md): `register` for the `model-log` source and `read` for its value. - The Rust port, for the consumer outside the App Server: the trait `RecordingDestination` lives in `dim-agent-aimux` where the recorder is, and the App Server's `ModelLog` implements it and serves the same read on the wire. -- FileStorage: `root_path` for the home root, once, to build the destination directory. +- The assembly provides the home directory as a host value; the recorder's destination is `/model-log`. FileStorage is not involved. ### Operations diff --git a/docs/design/plugins/PluginManager.md b/docs/design/plugins/PluginManager.md index ce2a57ab21..0cc6b36257 100644 --- a/docs/design/plugins/PluginManager.md +++ b/docs/design/plugins/PluginManager.md @@ -312,8 +312,8 @@ PluginManager adds no text of its own to model context beyond the `plugin` tool. | Command | Does | | --- | --- | | `list`, `install …`, `enable …`, `disable `, `reload `, `update `, `remove ` | The `plugin.*` method of the same name, with the CLI's arguments; a relative path is resolved against the Session's working directory. Same result and errors. | - | `config ` | The declared (JSON Schema) Settings sources the plugin that `` uses registered (R4); Rust typed sources, such as Mcp's, are not served here and are not listed: for each, its user document, revision, schema and user-only fields. A member the schema marks `writeOnly` (a secret, [settings-service §1.2](../appserver/settings-service.md#12-decision-secrets-belong-to-their-owner)) is left out of the document and listed in `writeOnlySet` when it holds a value. A plugin that is not running has registered none. Its client-side counterpart is `settings.sources` ([settings-service §4.3](../appserver/settings-service.md#43-management-methods-settings-client-path)), which lists the declarations only. | - | `config set ` | Replaces one top-level member of a source through Settings: reads the user document, sets `` (`.` when the plugin has several sources) to `` (JSON, else a string) and updates with the revision it read. Settings checks the revision and schema; the write is an owner write, so a user-only field is refused, and a member that is or contains a `writeOnly` member is refused too. The owner reads its source when it needs it, so the value takes effect without a restart. Structural row configuration is not edited here. | + | `config ` | The declared (JSON Schema) Settings sources the plugin that `` uses registered (R4); Rust typed sources, such as Mcp's, are not served here and are not listed. For each, [Settings](../plugins/Settings.md) `declared_sources {instance}` gives its id, schema, scopes, user-only pointers and write-only hint, and `agent_read` gives its user document with every `writeOnly` member left out and listed in `writeOnly`. The revision is not part of this path. A plugin that is not running has registered none. Its client-side counterpart is `settings.read` ([SettingsMethods](../plugins/SettingsMethods.md)), which serves declared sources only. | + | `config set ` | Replaces one top-level member of a source through Settings: `agent_set` with `` (`.` when the plugin has several sources) and `` (JSON, else a string). Settings checks the member and the schema; the agent path refuses a user-only or `writeOnly` member. The owner reads its source when it needs it, so the value takes effect without a restart. Structural row configuration is not edited here. | | `help [command]` | The command list, or one command's usage and details. | The tool's description carries only the one-line command list; `help` gives the details, and a malformed command's error result carries that command's usage. The tool is a tool call: Permission decides each one ([requirement 5](../plugin-management.md), [ADR 003](../../adr/003-approval-scope.md)). Its declared risk is `persistent_configuration`; `list` and `help` are admitted as `read_filesystem` (R3); `config`, whose documents may hold secrets and user content, is admitted at the declared risk, as the sources' own tools are. diff --git a/docs/design/plugins/PromptSettings.md b/docs/design/plugins/PromptSettings.md index ef6cc85a14..2a53c978ae 100644 --- a/docs/design/plugins/PromptSettings.md +++ b/docs/design/plugins/PromptSettings.md @@ -29,7 +29,11 @@ Callers keep: PromptSources reads the base text once, while its Session part applies. ```rust -let base = prompt_settings.base(cancelled.child_token()).await.ok().flatten(); +let base = prompt_settings + .base(cancelled.child_token()) + .await + .ok() + .and_then(|view| view.text); let text = factory.base.or(base).unwrap_or_else(|| BUILT_IN.into()); ``` @@ -69,7 +73,7 @@ A read returns the member as stored after the schema check; an absent member is ## Supersedes -- [Prompt overrides](../appserver/prompt-overrides.md) §3.1: the three services and their bare string replies are replaced by `promptSettings` and `{text}`. The precedence rules above and §4's client entry stay in force. +- [Prompt overrides](../appserver/prompt-overrides.md) §3 and §3.1 (the three ports), §7 (the three-host binding appendix) and §4's `settings.sources` sentence: one `promptSettings` service and `{text}`, with each capability depending on its own port trait. The precedence rules above and the rest of §4 stay in force. ## Rule check diff --git a/docs/design/plugins/PromptSuggestionSettings.md b/docs/design/plugins/PromptSuggestionSettings.md index 6f63b50452..eb6ec7ba78 100644 --- a/docs/design/plugins/PromptSuggestionSettings.md +++ b/docs/design/plugins/PromptSuggestionSettings.md @@ -28,7 +28,7 @@ Callers keep: PromptSuggestion reads the value before it decides. ```rust -let settings = settings_host.read(token.clone()).await?; +let settings = prompt_suggestion_settings.read(token.clone()).await?; if !settings.enabled { return Ok(Decision::Refused("disabled")); } diff --git a/docs/design/plugins/ProviderSettings.md b/docs/design/plugins/ProviderSettings.md index ed370fe68b..96eab4e92c 100644 --- a/docs/design/plugins/ProviderSettings.md +++ b/docs/design/plugins/ProviderSettings.md @@ -29,7 +29,11 @@ Callers keep: Provider reads the value when it builds a request. ```rust -let configured = provider_settings.user_agent().await.ok().flatten(); +let configured = provider_settings + .user_agent() + .await + .ok() + .and_then(|view| view.user_agent); let user_agent = configured.unwrap_or_else(|| dim_user_agent()); ``` diff --git a/docs/design/plugins/Settings.md b/docs/design/plugins/Settings.md index 635f13f42c..33e5984ef2 100644 --- a/docs/design/plugins/Settings.md +++ b/docs/design/plugins/Settings.md @@ -11,8 +11,8 @@ Settings owns: - **Sources.** The registry of named documents: each source's file names, project scope, the members only the user changes, and how its content is checked — a JSON Schema or a Rust document type. A registration belongs to the registering row and ends when that row unloads. - **Documents and revisions.** The user document (a file, or a row in the native store) and the project document (a file under an authorized project); the opaque revision that changes on every committed write; one writer at a time per document. - **Change application.** Running a caller's change against the current document under the owner's exclusion, checking the result, writing it, publishing the fact, and reporting whether durability is confirmed. -- **Authority.** An owner change and an agent change may not alter a user-only member; a user edit may. Members marked `writeOnly` are never returned to the agent, and the agent may not set them. -- **Authorized projects.** The cwd → project table, the directory opened for each authorized project, and the fact announcing a new one. +- **Authority.** An owner change and an agent change may not alter a user-only member; a user edit may. Every member marked `writeOnly` that is reachable through `properties` is withheld from the agent, and the agent may not set it; the rule does not scan `items`, `$defs` or `anyOf`. +- **Authorized projects.** The cwd → project table, the host-registered project root each authorized cwd denotes, and the fact announcing a new one. - **Facts.** `settings/` with `{source, scope, revision}` after a commit, and `settings/projects` with `{root, cwd}` after a new authorization. Callers keep: @@ -88,7 +88,7 @@ The plugin tool reads a plugin's configuration for the agent, and sets one membe let view = settings .agent_read(AgentRead { source: "web".into() }, cancelled.clone()) .await?; -// `view.writeOnly` lists the members withheld from the agent. +// `view.write_only` lists the members withheld from the agent. settings .agent_set( AgentSet { source: "web".into(), member: "/proxyDns".into(), value: true.into() }, @@ -114,9 +114,9 @@ let bytes = storage.read(definitions, cancelled).await?; // FileStorage's operat ### Dependencies -- [FileStorage](https://github.com/arcships/dim/pull/2080): `add_root` for an authorized project, `read` and `update` for a document stored as a file, and `create_directory` for the project's directory under `.dimcode`. Settings passes no path outside an authorized root. +- [FileStorage](https://github.com/arcships/dim/pull/2080): `read` and `update` for a document stored as a file, with an absolute path. Settings holds no root: the assembly gives it the home directory as a host value, and the host registers the project directory as a root when it creates the Session, so an authorized cwd is already addressable and its path is the document's base. Settings passes no path outside those two bases. - The storage engine ([#2018](https://github.com/arcships/dim/issues/2018)) as the native profile's crate-private implementation: it executes this owner's transactions over the `settings_documents` rows. The rows and their request, reply and error shapes are this contract's ([Native-profile row operations](#native-profile-row-operations)); the engine answers no Settings read or write on its public face. -- The caller's row: a source id and the registration are bound to the row that registered them; an id from another row is `invalid`. +- The caller's row: a source id and the registration are bound to the row that registered them. `read` and `change` check the caller's row and answer `invalid` for another row's id; the user path (`read_user`, `replace_user`) and the agent path (`agent_read`, `agent_set`) do not check the caller's row, and the user path is served to [SettingsMethods](SettingsMethods.md) and to a Rust owner's own namespace. ### Operations @@ -129,19 +129,19 @@ let bytes = storage.read(definitions, cancelled).await?; // FileStorage's operat | `replace_user` | Replace a document with the draft the user edited at the revision read | `{id, scope, expectedRevision, document}` | `{revision, document}` | Before the write; an admitted write still commits | `invalid`, `invalid_document`, `conflict`, `too_large`, `unsynced`, `failed`, `closed`, `cancelled` | | `agent_read` | A declared document for the agent, `writeOnly` members withheld | `{source}` | `{document, writeOnly}` | While the document is read | `unknown_source`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled` | | `agent_set` | Set one member of a declared document for the agent | `{source, member, value}` | `{document, writeOnly}` | Before the write | `unknown_source`, `invalid`, `user_only`, `invalid_document`, `too_large`, `unsynced`, `failed`, `closed`, `cancelled` | -| `declared_sources` | The declared sources, by name: all of them, or those a live row registered | `{instance?}` | `{sources: [{id, source, schema, scopes, userOnly, writeOnly}]}` | None; the owner completes the read | None | -| `authorize_project` | Admit a cwd as a project root; the same cwd answers the same number | `{cwd}` | `{root}` | While FileStorage opens the directory | `invalid`, `failed`, `closed`, `cancelled` | +| `declared_sources` | The declared sources, by name: all of them, or those a live row registered | `{instance?}` | `{sources: [{id, source, schema, scopes, userOnly, writeOnlyHint}]}` | None; the owner completes the read | None | +| `authorize_project` | Record a cwd as an authorized project; the same cwd answers the same number | `{cwd}` | `{root}` | None; the table is written before the reply | None | | `authorized_projects` | The projects authorized in this process generation | `{}` | `{projects: [{root, cwd}]}` | None | None | Data: -- `SourceId` is the id `register` assigns; it is bound to the row that registered it, and a caller from another row is `invalid`. `declared_sources` lists only declared sources; a Rust source's id is not listed. +- `SourceId` is the id `register` assigns. `read` and `change` check that the calling row registered it; an id from another row is `invalid` there. The user path does not check the row: `SettingsMethods` reaches a declared source's id after resolving the client's name, and a Rust owner reaches its own id. `declared_sources` lists only declared sources; a Rust source's id is not listed. - `Document` is one JSON object; a missing user document reads as its default document. - `Scope` is `"user"` or `{"project": }`. The number is this process's project number, assigned by `authorize_project`; it is not durable and it is not FileStorage's root id. - `userOnly` lists JSON Pointers to members only the user changes. Each pointer must name a member reachable through the schema's `properties`; otherwise `register` is `invalid`. - `ChangeFn` is `Fn(Option) -> Result`: it is called once, under the document's exclusion, with the current document, and returns the next document or its own refusal. It must only compute; waiting on another owner or on I/O inside the change holds the document for that whole wait. - `Revision` is an opaque value that changes on every committed write. Only the user path carries it, as the draft base the client holds: a business concurrency control between the user's read and write. An owner change carries no revision; the owner's exclusion and any waiting stay inside `change`. -- `writeOnly` lists the JSON Pointers of members withheld from the agent and holding a value. +- `writeOnly` lists the JSON Pointers of members, reachable through `properties`, that are withheld from the agent when they hold a value. `writeOnlyHint` in a declaration is true when the source declares at least one such member; it is a hint, not the pointer list. ### Native-profile row operations @@ -172,8 +172,8 @@ A fact is published after the commit and never carries a document. A failed fact | `invalid` | Fix the input: a declaration whose name or file is taken, whose schema is refused, or whose user-only pointer names no reachable member; a source id from another row; an unknown project; a project scope for a source without a project file; a member pointer that names no member | | `unknown_source` | The declared source is not registered now, or it is a Rust source that the client and agent paths do not serve: retry after its owner registers it, or report that the feature is off | | `invalid_document` | The document as stored, or the one the change produced, fails its check; repair the user's document or fix the change | -| `user_only` | The change or the agent named a member only the user changes; ask the user, or leave the member as it is | -| `rejected` | The change refused with its own `code` and `message`; act on that code | +| `user_only` | The change or the agent named a member only the user changes, including a `writeOnly` member the agent tried to set; ask the user, or leave the member as it is | +| `rejected` | The change refused with its own `reason` and `message`; act on `reason` | | `conflict` | The user's draft is stale; read again and let the user decide | | `too_large` | The document exceeds the document limit; the caller must not treat the value as a document | | `unsynced` | The document is in place but its durability is unconfirmed; read it and do not repeat a change without reading | @@ -187,8 +187,9 @@ A fact is published after the commit and never carries a document. A failed fact | --- | --- | --- | --- | --- | --- | | `change` | Take the document's exclusion, read the current document, call the change, check the result, write it, publish, release | Before the write: the change's future is dropped, the document is unchanged, the exclusion is released, `cancelled` | The row's `apply` future ends; the same release applies | New calls are refused; an in-flight change finishes or ends `closed`; the generation releases its exclusions | Exclusion by Settings; the change's future by the calling row | | `replace_user` | Take the exclusion, read the current revision, refuse a stale base, check and write the document, publish, release | An admitted write still commits or ends `unsynced`; a wait dropped before admission changes nothing | The admitted write completes; the reply may be lost | In-flight calls finish or end `closed` | Exclusion by Settings; the admitted write by Settings | -| `read`, `read_user`, `agent_read`, `declared_sources`, `authorized_projects` | Open the document through its profile or read the registry, check it, return the value | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | File handle or row read by Settings | -| `authorize_project` | Open the directory through FileStorage's `add_root`, append to the project table, publish the fact | Before the directory is opened or the row is appended | The call ends `cancelled`; a later call for the same cwd completes the authorization | The table is generation state: a new generation starts empty and a cwd is authorized again at admission | Directory by FileStorage; the project table by Settings | +| `read`, `read_user`, `agent_read` | Open the document through its profile, check it, return the value | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | File handle or row read by Settings | +| `declared_sources`, `authorized_projects` | Read the registry or the project table and return the value; no cancellation and nothing to release | Not applicable | Not applicable | The generation answers from its own memory | Settings | +| `authorize_project` | Insert the cwd in the project table when absent, publish the fact for a new one, return the number | Not cancellable; the insert is one step | The insert completes; the reply may be lost | The table is generation state: a new generation starts empty and a cwd is authorized again at admission | The project table by Settings; the directory root by the host | | `register` | Check the declaration, insert under the calling row, return the id | Not cancellable; a failed `apply` ends the row | The registration is withdrawn with the row; its documents stay | The new generation starts with no registrations; the documents stay | Registration lifetime by the calling row | ## Exceptions with reasons @@ -196,12 +197,12 @@ A fact is published after the commit and never carries a document. A failed fact - The user path carries a draft revision and the owner path does not: the client's business decides whether a write still applies to the document the user read, while an owner change always applies to the current document; the revision is not a version the owner checks on the owner path. - `unsynced` reports a write that is in place with unconfirmed durability: a read sees it, and a repeated change applies again, so the caller reads before repeating. - On the native profile the first read imports the user file into the row when the row is absent: the import is internal state migration, not an operation, and the file stays where it is. -- The project table is process-generation state: a project number is not durable and does not survive a Settings reload; a caller that needs a project after a reload resolves its cwd again at admission, which re-authorizes it. +- The project table is process-generation state: the number is Settings' own, not FileStorage's root id, and not durable. The host registers the project directory as a FileStorage root when it creates the Session; after a Settings reload the table starts empty and a cwd is authorized again at admission. - A client write is admitted when it starts: a disconnected client does not undo it, so the reply may be lost while the document is written or `unsynced`. ## Supersedes -- [Settings service](../appserver/settings-service.md) §4.2 (the `settings` service) and §4.5 (the Rust binding); §4.3 is [SettingsMethods](SettingsMethods.md)'s. The document's §3 state, §4.1 shapes, §4.4 events, §6 errors' state meanings, §7 security and §11 acceptance stay in force; §4.1's `Scope` is the `Scope` below and §4.4's `project_authorized` payload keeps `{root, cwd}`. +- [Settings service](../appserver/settings-service.md) §4.1 (common shapes: `Snapshot`, `Sources`, `SettingsScope`), §4.2 (the `settings` service), §4.5 (the Rust binding), §5 (the operations' flows), §6 (the error codes) and §11 (acceptance). §4.3 is [SettingsMethods](SettingsMethods.md)'s. The document's §3 state, §4.4 events, §7 security, §8.1, §9 and §10 stay in force; §4.4's `project_authorized` payload keeps `{root, cwd}`, and the new acceptance is the delivery's flow tests. - [Settings service](../appserver/settings-service.md) §8.1's note that Rust owners keep their own methods stays; the methods' shapes are in each owner's contract. - [Resource owner operations](../contracts/resource-owner-operations.md) §Settings. - [Service faces](../service-faces.md) §3.3's `settingsService` row, §3.2's host-port sentence for the three prompt ports, and §4.1's `settingsService` paragraph. @@ -231,7 +232,7 @@ Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d74417 | §7 no proxy | No operation answers another owner's data: a value is requested from the part that owns it, and workflow definition bytes come from FileStorage for the Workflow plugin. | | §7 one face | One service on the `Settings` type; no facade, no wrapper type, no second name. | | §7 cross-language | Every operation's request, reply and errors are data; the Rust binding is the appendix. | -| §7 caller complexity | The revision, exclusion, retry and durability stay inside Settings; the caller handles `conflict`, `user_only`, `rejected` and `unsynced` only. | +| §7 caller complexity | The revision, exclusion, retry and durability stay inside Settings; the caller handles the business outcomes (`conflict`, `user_only`, `rejected`, `unsynced`) and the ordinary failures (`invalid`, `unknown_source`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled`). | | §7 one change | The old `settings`/`settingsService` surfaces and their callers are migrated in one change; PluginManager, SettingsMethods and every source owner appear in the delivery table. | | ADR 002 D1 | Process scope; documents and the project table outlive Sessions. | | ADR 002 D2 | No wiring plugin; the service is on the owner type. | @@ -293,24 +294,24 @@ impl Scope { } } -/// One document's replacement from the change callback: its own `code` and `message`. +/// One document's replacement from the change callback: its own `reason` and `message`. #[derive(Debug, thiserror::Error)] #[error("{code}: {message}")] pub struct ChangeRefused { - pub code: String, + pub reason: String, pub message: String, } -/// A callback's refusal arrives as the wire's own error; its code and message are kept. +/// A callback's refusal arrives as the wire's own error; its code becomes `reason`. impl From for ChangeRefused { fn from(error: rutis::host::CallError) -> Self { - let code = error + let reason = error .raw() .and_then(|raw| raw.downcast_ref::()) .and_then(rutis_bridge::session::Error::code) .unwrap_or("rejected") .to_owned(); - Self { code, message: error.to_string() } + Self { reason, message: error.to_string() } } } @@ -382,7 +383,7 @@ pub struct Declaration { pub schema: Value, pub scopes: Vec, pub user_only: Vec, - pub write_only: bool, + pub write_only_hint: bool, } #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] @@ -403,7 +404,7 @@ pub struct Authorized { pub root: ProjectId, } -#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct Project { pub root: ProjectId, @@ -416,60 +417,31 @@ pub struct AuthorizedProjects { pub projects: Vec, } -#[derive(Debug, thiserror::Error)] +#[derive(Debug, serde::Serialize, thiserror::Error)] +#[serde(tag = "code", rename_all = "snake_case")] pub enum SettingsError { - #[error("{0}")] - Invalid(String), - #[error("{0}")] - UnknownSource(String), - #[error("{0}")] - InvalidDocument(String), - #[error("{0}")] - UserOnly(String), - #[error("{code}: {message}")] - Refused(ChangeRefused), - #[error("the settings revision is stale")] - Conflict, - #[error("{0}")] - TooLarge(String), - #[error("{0}")] - Unsynced(String), - #[error("{0}")] - Failed(String), - #[error("the settings service is unloading")] - Closed, - #[error("the settings call was cancelled")] - Cancelled, -} - -impl SettingsError { - /// The wire `code`; a refused change keeps the callback's own code. - pub fn code(&self) -> &str { - match self { - Self::Invalid(_) => "invalid", - Self::UnknownSource(_) => "unknown_source", - Self::InvalidDocument(_) => "invalid_document", - Self::UserOnly(_) => "user_only", - Self::Refused(refused) => &refused.code, - Self::Conflict => "conflict", - Self::TooLarge(_) => "too_large", - Self::Unsynced(_) => "unsynced", - Self::Failed(_) => "failed", - Self::Closed => "closed", - Self::Cancelled => "cancelled", - } - } -} - -/// The wire error's `{code, message}` shape; derived tags cannot carry the callback's code. -impl serde::Serialize for SettingsError { - fn serialize(&self, serializer: S) -> Result { - use serde::ser::SerializeStruct; - let mut out = serializer.serialize_struct("SettingsError", 2)?; - out.serialize_field("code", self.code())?; - out.serialize_field("message", &self.to_string())?; - out.end() - } + #[error("{message}")] + Invalid { message: String }, + #[error("{message}")] + UnknownSource { message: String }, + #[error("{message}")] + InvalidDocument { message: String }, + #[error("{message}")] + UserOnly { message: String }, + #[error("{reason}: {message}")] + Rejected { reason: String, message: String }, + #[error("{message}")] + Conflict { message: String }, + #[error("{message}")] + TooLarge { message: String }, + #[error("{message}")] + Unsynced { message: String }, + #[error("{message}")] + Failed { message: String }, + #[error("{message}")] + Closed { message: String }, + #[error("{message}")] + Cancelled { message: String }, } impl PublicService for Settings {} diff --git a/docs/design/plugins/SettingsMethods.md b/docs/design/plugins/SettingsMethods.md index 757ed20839..0600f1b5fa 100644 --- a/docs/design/plugins/SettingsMethods.md +++ b/docs/design/plugins/SettingsMethods.md @@ -82,12 +82,12 @@ No service. Two management methods, registered with `managementMethods`: | Method | Intent | Request | Reply | Cancellation | Errors | | --- | --- | --- | --- | --- | --- | -| `settings.read` | The user's draft base for one declared document | `{source, scope}` | `{revision, document}` | The call is dropped; nothing changes | invalid params, `settings_unknown_source`, `settings_failed`, `operation_interrupted`, reloading | -| `settings.update` | Replace a declared document with the draft at the revision read | `{source, scope, expectedRevision, document}` | `{revision, document}` | An admitted write commits or ends `settings_unsynced`; a wait dropped before admission changes nothing | invalid params, `settings_unknown_source`, `settings_conflict`, `settings_unsynced`, `settings_failed`, `operation_interrupted`, reloading | +| `settings.read` | The user's draft base for one declared document | `{source, scope}` | `{revision, document}` | A cancelled call has no reply and changes nothing | invalid params, `settings_unknown_source`, `settings_failed`, `operation_interrupted`, reloading | +| `settings.update` | Replace a declared document with the draft at the revision read | `{source, scope, expectedRevision, document}` | `{revision, document}` | A cancelled wait changes nothing before admission; an admitted write commits or ends `settings_unsynced` | invalid params, `settings_unknown_source`, `settings_conflict`, `settings_unsynced`, `settings_failed`, `operation_interrupted`, reloading | Invalid params covers a malformed request, an unknown field, a missing revision, a document that is not an object, and a document the source's schema refuses; for a schema refusal the message is the validator's, and the client shows it as an input error. -`settings_conflict` means the draft is stale: the client reads again and lets the user decide. `settings_unsynced` means the bytes are in place with unconfirmed durability: read again instead of repeating the write. `operation_interrupted` means the call was cancelled or its part is unloading; the client re-reads before retrying. `reloading` means the daemon is restarting. +`settings_conflict` means the draft is stale: the client reads again and lets the user decide. `settings_unsynced` means the bytes are in place with unconfirmed durability: read again instead of repeating the write. `operation_interrupted` means this part unloaded while the call was pending; a caller-cancelled call has no reply. The client re-reads before retrying. `reloading` means the daemon is restarting. ### Errors @@ -98,7 +98,7 @@ Invalid params covers a malformed request, an unknown field, a missing revision, | `settings_conflict` | Read again; the user's draft is stale | | `settings_unsynced` | Read again; the write is in place | | `settings_failed` | Read again before retrying; the store failed without a code the client can act on | -| `operation_interrupted` | The call was cancelled or its part is unloading; read again before retrying | +| `operation_interrupted` | The part unloaded while the call was pending; read again before retrying | | reloading | The daemon is restarting; retry after it is back | ### Flows diff --git a/docs/design/service-faces.md b/docs/design/service-faces.md index bb60d13479..5bff26432d 100644 --- a/docs/design/service-faces.md +++ b/docs/design/service-faces.md @@ -92,7 +92,7 @@ Rust 产品装配的现状以 [生成的 catalog](../architecture/rust-agent/gen | `wakeups` | `wakeups.create/list/cancel` | 形状按 [Scheduler](plugins/Scheduler.md#102-methods-and-tool) §10.2。 | | `loops` | `loops.start/next/list/stop` | 形状按 [Scheduler](plugins/Scheduler.md#126-interfaces) §12.6;`start`、`next`、`stop` 是迁改,`list` 是读取。投递 pass、恢复与 `settle_delivering` 不在此面。 | | `sessionFiles` | `sessionFiles.put/import/read/register/owns/owned_paths` | 形状按 [Session files](appserver/session-files.md) §9.1,`SessionFiles` 是进程内绑定。 | -| `commandRules` | `commandRules.read` | Session 命令规则读取,按 [命令规则](appserver/permission-command-rules.md#41-language-neutral-adr-002-d5) §4.1。 | +| `commandRules` | 已删除 | 规则由 [PermissionRules](plugins/PermissionRules.md) 的 `permissionRules.rules` 提供。 | | `managedSearch` | `managedSearch.search` | 凭据由实现持有,见 §4.6。 | | `agentConfig` | `agentConfig.get()` | 形状见 §4.8。 | | `sessionLanguage` | `sessionLanguage.get()` | 形状见 §4.8。 | @@ -209,12 +209,9 @@ Proposed target operations: [Session and branch operations](contracts/runtime-ow 每批处理同一个 owner 的相关操作。 -PromptSettings 的三个只读端口按 [prompt overrides §3.1](appserver/prompt-overrides.md#31-data-operations) -提供 `basePromptSettingsHost.base({})`、`skillsInstructionsSettingsHost.instructions({})` 和 -`summaryPromptSettingsHost.systemPrompt({})`,回复为字符串或 `null`。它们共享现有 owner, -原生与跨语言入口调用同一读取方法;配置优先级、读取时机和失败回退保持 owner 契约。 +PromptSettings 的一个服务按 [PromptSettings](plugins/PromptSettings.md) 提供 `promptSettings.base({})`、`promptSettings.summary({})` 和 `promptSettings.skills({})`,回复为 `{text}` 或 none;capability 侧各依赖自己的端口 trait。配置优先级、读取时机和失败回退保持 owner 契约。 -### 4.1 `settingsService`:保留调用取消 +### 4.1 `settingsService`:已被 Settings 取代 已由 [Settings](plugins/Settings.md) 与 [SettingsMethods](plugins/SettingsMethods.md) 取代:所有者按 source id 读值,调用方的取消随读取结束;GoalBranch 的读取改走该绑定。 @@ -355,11 +352,11 @@ eventSubscriptions.list {sessionId} -> reply 这些读取操作持有 owner 的闭包,Rust 绑定直接调用类型化操作;dispatcher 只在跨语言边界解码请求、调用同一个操作并编码回复,不写第二份业务逻辑。Rust 调用不经过 JSON,也不为读取另起桥接任务。每次异步调用持有独立的子取消 token:取消或丢弃调用会取消该次 owner 读取,不取消调用方的父 token。跨语言回复使用 `cancellable_future`,放弃等待会丢弃同一个读取;owner 的生命周期仍约束其工作。 ```text -executionSettingsHost.read({}) -> {sandbox, network} +executionSettings.read({}) -> {sandbox, network} -> error {code: failed, message} toolchainSourceHost.list({}) -> {toolchains: [{bin, root}]} # sync -> error {code: failed, message} -promptSuggestionSettingsHost.read({}) -> {enabled, maxChars} +promptSuggestionSettings.read({}) -> {enabled, maxChars} -> error {code: failed, message} providerService.selectableModels({}) -> {models: [ModelCapabilitySnapshot]} providerService.selectableForModality({}) -> {models: [ModalityModelSnapshot]} diff --git a/docs/design/subagent-model-policy.md b/docs/design/subagent-model-policy.md index e9dcd53fc9..0dbe9812e3 100644 --- a/docs/design/subagent-model-policy.md +++ b/docs/design/subagent-model-policy.md @@ -53,7 +53,7 @@ decision by an LLM. `agent` means the existing request/profile selection behavio | Identify the requesting branch | `CollaborationSession::request` already receives `branch_id`; pass it within Collaboration, without changing an event or tool request | | Read the adopted leader model | `Session::get(branch_id)` while consuming `collaboration/request`, before starting its delivery task | | Resolve an explicit model | The existing `AgentIndex` model-selection host and configured/non-catalog profile paths | -| Persist and edit policy | [CollaborationModelPolicy](../plugins/CollaborationModelPolicy.md): the `collaboration` source, its `policy` value read and the `collaboration.*` methods | +| Persist and edit policy | [CollaborationModelPolicy](plugins/CollaborationModelPolicy.md): the `collaboration` source, its `policy` value read and the `collaboration.*` methods | | Start/restore and retain members | Existing Agents/Collaboration Session creation, usage holds and cleanup, including idle unloading | Do not use `leader.config().model` or `session.summaries` as the adopted leader model: From 8ef2691ce3aff905c1ddeb8805cf453ab6de529a Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 11:44:46 +0800 Subject: [PATCH 7/8] design(settings): align FileStorage calls with #2080 head 7224c0cd4 Settings uses add_root for a project authorization, read and update for a document; ModelLog uses root_path for the home root. The home directory arrives as an assembly value, which is a choice: root_path and stat exist and are not needed here. --- docs/design/plugins/ModelLog.md | 8 ++++---- docs/design/plugins/Settings.md | 9 +++++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/design/plugins/ModelLog.md b/docs/design/plugins/ModelLog.md index 847d478647..7b94f1ebc4 100644 --- a/docs/design/plugins/ModelLog.md +++ b/docs/design/plugins/ModelLog.md @@ -28,13 +28,13 @@ Callers keep: The recorder reads the destination while it starts a request. ```rust -let destination = model_log +let directory = model_log .recording() .await .ok() .and_then(|view| view.directory); -if let Some(directory) = destination { - // aimux owns the file under this directory. +if let Some(directory) = directory { + // aimux owns the file under this directory; it is `/model-log`. } ``` @@ -44,7 +44,7 @@ if let Some(directory) = destination { - [Settings](Settings.md): `register` for the `model-log` source and `read` for its value. - The Rust port, for the consumer outside the App Server: the trait `RecordingDestination` lives in `dim-agent-aimux` where the recorder is, and the App Server's `ModelLog` implements it and serves the same read on the wire. -- The assembly provides the home directory as a host value; the recorder's destination is `/model-log`. FileStorage is not involved. +- [FileStorage](https://github.com/arcships/dim/pull/2080) at its head `7224c0cd4`: `root_path` for the home root. The assembly provides the home root id as a host value, and the recorder's destination is `/model-log`. ### Operations diff --git a/docs/design/plugins/Settings.md b/docs/design/plugins/Settings.md index 33e5984ef2..22b5713bfc 100644 --- a/docs/design/plugins/Settings.md +++ b/docs/design/plugins/Settings.md @@ -114,7 +114,7 @@ let bytes = storage.read(definitions, cancelled).await?; // FileStorage's operat ### Dependencies -- [FileStorage](https://github.com/arcships/dim/pull/2080): `read` and `update` for a document stored as a file, with an absolute path. Settings holds no root: the assembly gives it the home directory as a host value, and the host registers the project directory as a root when it creates the Session, so an authorized cwd is already addressable and its path is the document's base. Settings passes no path outside those two bases. +- [FileStorage](https://github.com/arcships/dim/pull/2080) at its head `7224c0cd4`: `add_root` for a project authorization, and `read` and `update` for a document stored as a file, with an absolute path. The host registers the roots it assembles with and each Session's workspace; a project cwd is made addressable with `add_root` and answers the same id when it is added again. Settings reads the home directory as a host value from the assembly, because the assembly already knows it; FileStorage also exposes `root_path` and `stat`, which Settings does not use — this is a choice, not a missing operation. Settings passes no path outside the home directory and an authorized cwd. - The storage engine ([#2018](https://github.com/arcships/dim/issues/2018)) as the native profile's crate-private implementation: it executes this owner's transactions over the `settings_documents` rows. The rows and their request, reply and error shapes are this contract's ([Native-profile row operations](#native-profile-row-operations)); the engine answers no Settings read or write on its public face. - The caller's row: a source id and the registration are bound to the row that registered them. `read` and `change` check the caller's row and answer `invalid` for another row's id; the user path (`read_user`, `replace_user`) and the agent path (`agent_read`, `agent_set`) do not check the caller's row, and the user path is served to [SettingsMethods](SettingsMethods.md) and to a Rust owner's own namespace. @@ -130,7 +130,7 @@ let bytes = storage.read(definitions, cancelled).await?; // FileStorage's operat | `agent_read` | A declared document for the agent, `writeOnly` members withheld | `{source}` | `{document, writeOnly}` | While the document is read | `unknown_source`, `invalid_document`, `too_large`, `failed`, `closed`, `cancelled` | | `agent_set` | Set one member of a declared document for the agent | `{source, member, value}` | `{document, writeOnly}` | Before the write | `unknown_source`, `invalid`, `user_only`, `invalid_document`, `too_large`, `unsynced`, `failed`, `closed`, `cancelled` | | `declared_sources` | The declared sources, by name: all of them, or those a live row registered | `{instance?}` | `{sources: [{id, source, schema, scopes, userOnly, writeOnlyHint}]}` | None; the owner completes the read | None | -| `authorize_project` | Record a cwd as an authorized project; the same cwd answers the same number | `{cwd}` | `{root}` | None; the table is written before the reply | None | +| `authorize_project` | Admit a cwd as an authorized project; the same cwd answers the same number | `{cwd}` | `{root}` | Before the directory is opened or the entry appended | `invalid`, `closed`, `cancelled` | | `authorized_projects` | The projects authorized in this process generation | `{}` | `{projects: [{root, cwd}]}` | None | None | Data: @@ -189,7 +189,7 @@ A fact is published after the commit and never carries a document. A failed fact | `replace_user` | Take the exclusion, read the current revision, refuse a stale base, check and write the document, publish, release | An admitted write still commits or ends `unsynced`; a wait dropped before admission changes nothing | The admitted write completes; the reply may be lost | In-flight calls finish or end `closed` | Exclusion by Settings; the admitted write by Settings | | `read`, `read_user`, `agent_read` | Open the document through its profile, check it, return the value | Before the reply; nothing changes | The call ends `cancelled` | Pending calls end `closed` | File handle or row read by Settings | | `declared_sources`, `authorized_projects` | Read the registry or the project table and return the value; no cancellation and nothing to release | Not applicable | Not applicable | The generation answers from its own memory | Settings | -| `authorize_project` | Insert the cwd in the project table when absent, publish the fact for a new one, return the number | Not cancellable; the insert is one step | The insert completes; the reply may be lost | The table is generation state: a new generation starts empty and a cwd is authorized again at admission | The project table by Settings; the directory root by the host | +| `authorize_project` | Call `add_root` for the cwd, append the cwd → number entry when absent, publish the fact for a new one, return the number | Before the directory is opened or the entry is appended; a later call for the same cwd completes the authorization | The call ends `cancelled`; the append-only root table keeps the root | The table is generation state: a new generation starts empty and a cwd is authorized again at admission | The project table by Settings; the directory root by FileStorage | | `register` | Check the declaration, insert under the calling row, return the id | Not cancellable; a failed `apply` ends the row | The registration is withdrawn with the row; its documents stay | The new generation starts with no registrations; the documents stay | Registration lifetime by the calling row | ## Exceptions with reasons @@ -197,7 +197,8 @@ A fact is published after the commit and never carries a document. A failed fact - The user path carries a draft revision and the owner path does not: the client's business decides whether a write still applies to the document the user read, while an owner change always applies to the current document; the revision is not a version the owner checks on the owner path. - `unsynced` reports a write that is in place with unconfirmed durability: a read sees it, and a repeated change applies again, so the caller reads before repeating. - On the native profile the first read imports the user file into the row when the row is absent: the import is internal state migration, not an operation, and the file stays where it is. -- The project table is process-generation state: the number is Settings' own, not FileStorage's root id, and not durable. The host registers the project directory as a FileStorage root when it creates the Session; after a Settings reload the table starts empty and a cwd is authorized again at admission. +- The project table is process-generation state: the number is Settings' own, not FileStorage's root id, and not durable. FileStorage's `add_root` makes the cwd addressable and answers a root id that Settings keeps only inside the authorization; after a Settings reload the table starts empty and a cwd is authorized again at admission. +- Settings uses `add_root`, `read` and `update` from FileStorage; it does not use `root_path` or `stat`, which exist in the same contract. The home directory is a host value because the assembly owns it, and a Settings document is read whole, so neither is needed. - A client write is admitted when it starts: a disconnected client does not undo it, so the reply may be lost while the document is written or `unsynced`. ## Supersedes From 0677c7155079284b8a60f682d9ee8da5458c2188 Mon Sep 17 00:00:00 2001 From: scotares Date: Tue, 24 Nov 2026 13:30:51 +0800 Subject: [PATCH 8/8] design(settings): close the inline review findings Settings says it registers each authorized cwd with add_root; the Workflow example passes the offset and length arguments; ChangeRefused names its reason field. PromptSettings keeps the three capability traits and uses the port's optional read in its example. The retained settings-service sections no longer list settings.sources, settings.projects, workflowFiles or SettingsService, and the service-faces Supersedes points at the paragraph it changes. --- docs/design/appserver/settings-service.md | 46 +++++++++---------- .../plugins/CollaborationModelPolicy.md | 2 +- docs/design/plugins/ExecutionSettings.md | 4 +- docs/design/plugins/ModelLog.md | 2 +- docs/design/plugins/PermissionRules.md | 2 +- docs/design/plugins/PromptSettings.md | 11 ++--- .../plugins/PromptSuggestionSettings.md | 2 +- docs/design/plugins/ProviderSettings.md | 2 +- docs/design/plugins/Settings.md | 10 ++-- docs/design/plugins/SettingsMethods.md | 6 +-- 10 files changed, 42 insertions(+), 45 deletions(-) diff --git a/docs/design/appserver/settings-service.md b/docs/design/appserver/settings-service.md index 989401b8d4..125f31e3f3 100644 --- a/docs/design/appserver/settings-service.md +++ b/docs/design/appserver/settings-service.md @@ -17,10 +17,12 @@ each source with Settings when it starts ([ADR 007](../../adr/007-plugin-configu the source name, its files, a JSON Schema (with `default` values) and its user-only fields (§3.1). Settings then offers three things over JSON documents: -- the process service `settings`, which the owner uses: `register`, `read`, `update` (CAS on - the revision) and `projects`; -- the client management methods `settings.read`, `settings.update`, `settings.sources` and - `settings.projects`; +- the process service `settings`, which the owner uses: `register` (with its `userOnly` list), + `read`, `change`, `read_user`, `replace_user`, `agent_read`, `agent_set`, `declared_sources`, + `authorize_project` and `authorized_projects` (the target shapes are in + [Settings](../plugins/Settings.md)); +- the client management methods `settings.read` and `settings.update` for declared sources + ([SettingsMethods](../plugins/SettingsMethods.md)); - the same rutis events as S8a, `settings.changed` and `settings.project_authorized`. Their payloads become serializable. There is no `subscribe(source)`. @@ -38,10 +40,9 @@ way (§4.5). Rust sources keep their owners' management methods. F2's `permissio No new plugin, no Timeline event, no change to Timeline, Dispatcher, rutis or assembly. -The same Settings provider supplies generated `workflowFiles` for definition -directories. It reads the existing project authorization map and the original -process caller’s declared package scope, without exporting FileStorage or raw -root indices. See the [native definition-file contract](../p6-p7-bindings.md#3-workflow-definition-files). +Workflow definition files are not a Settings operation: Workflow composes the project's cwd +from `authorized_projects` with FileStorage's path operations +([#2033](https://github.com/arcships/dim/issues/2033)). ### 1.1 What this does not do @@ -49,8 +50,9 @@ root indices. See the [native definition-file contract](../p6-p7-bindings.md#3-w event bus (issue comment). Settings keeps no watch channel of its own. - No generic client access to Rust sources (`mcp`, `mcp-projects`, `mcp-plugins`, `skills`, `permission`). Their validation is Rust code that Settings cannot run on client JSON. -- Source discovery is `settings.sources` (§4.3): local connections can list the declared - sources and their schemas, never their documents. There is still no settings UI. +- Source discovery is by name: a local client reads and writes the declared sources it knows + through `settings.read`/`settings.update`; no method lists every declaration (`settings.sources` + is deleted in [#2017](https://github.com/arcships/dim/issues/2017)). There is still no settings UI. - No secret store, credential service or field-name rule (§1.2). The one marker is the schema's `writeOnly` annotation. - MCP's inline tokens, `env` and `headers` stay where they are (ADR 004 D4). @@ -95,17 +97,17 @@ depended on a store nobody owned. That service and the `*Ref` rule are withdrawn Process scope +-------------------------------------------------------------------------+ | Settings (existing plugin) | - | SettingsService | + | one service and the source registry | | registered sources, each until its registering plugin unloads: | | BusinessDocument types (Rust owners) | | declared sources: schema, defaults, files, user-only pointers | - | named service `settings` (HostDispatch) <-- owner writes | - | managementMethods `settings` <-- client writes | + | service `settings` <-- owner operations | + | managementMethods `settings.*` <-- client operations | | emits settings.changed on settings/, | | settings.project_authorized on settings/projects | +------^-------------------------------^----------------------------------+ - | register/read/update/projects | settings.read / settings.update - | | settings.sources / settings.projects + | register/read/change/... | settings.read / settings.update + | | (declared sources only) | | TypeScript owner (rutis runtime row) Rpc <-- local client ``` @@ -119,7 +121,7 @@ owner depends on `settings`. Every owner, built-in Rust and TypeScript alike, registers its sources from its own process row's `apply`. Declared sources use `settings.register(declaration)` through their language binding -(§4.2, §4.5); native `BusinessDocument` sources use `SettingsService::register::` (§4.5). Neither the App Server's assembly nor PluginManager +(§4.2, §4.5); native `BusinessDocument` sources use `Settings::register_typed::` (§4.5). Neither the App Server's assembly nor PluginManager declares sources. A registration belongs to the plugin that made it and is withdrawn when that plugin unloads (turned off, removed or reloaded); a reload registers again from the new generation. The stored documents stay in the home whether or not their source is registered: an @@ -307,7 +309,7 @@ F2 left open whether to fold its methods into `settings.read/update`. They stay: | §4 rule 4 (core has no business meaning) | Settings validates against declared schemas and names no owner | | §4 rule 5 (batches) | No Timeline writes | | §4 rule 6 (context) | Nothing enters model context. A tool's view of settings is its owner's business | -| §4 rule 7 (public interfaces only) | Owners use the `settings` service; clients use management methods, and read the declarations through `settings.sources`, never from a plugin package | +| §4 rule 7 (public interfaces only) | Owners use the `settings` service; clients use management methods for the declared sources they know by name, never a plugin package | | §4 rule 8 (infrastructure unchanged) | No change to Timeline, Dispatcher, event envelope, rutis, loader, Agent assembly or Session facade. Existing `HostDispatch`, `ServiceCatalog`, `managementMethods` and rutis events are used as they are | | §4 rule 9 (only needed facts in Timeline) | No event is added; settings are not Timeline facts | | ADR 002 D1 (scope) | Settings is a process plugin; the sources outlive Sessions | @@ -329,12 +331,10 @@ question 2); that is no new requirement on dim runtime or rutis. plugin itself (§3.1), so installing, replacing or removing a plugin does not reload Settings. 4. ~~**Which plugin provides `credentials` in the product.**~~ Withdrawn with the service: each owner handles its own secrets (§1.2). -5. ~~**Source discovery for a settings UI.**~~ Settled 2026-11-05: discovery is - `settings.sources` (§4.3), a management method served to local connections only that lists - each declared source, its schema and its scopes, never a document. The question was whether - a generic `/settings` page would need the declared sources and their schemas (for example a - `settings.sources` method); nothing required it for S8b, so it stayed with the CLI settings - design until now. +5. ~~**Source discovery for a settings UI.**~~ Settled 2026-11-05, then superseded by + [#2017](https://github.com/arcships/dim/issues/2017): `settings.sources` is deleted. A client + reads the declared sources it knows by name; an out-of-repo page that needs the list would + have to be given it again through its owner's namespace. 6. **User-only fields for Rust sources.** No Rust owner writes its source on behalf of a tool today. If one does (Scheduler, Workflow), it needs a user-only declaration on its `BusinessDocument`. That is decided with that owner's design. diff --git a/docs/design/plugins/CollaborationModelPolicy.md b/docs/design/plugins/CollaborationModelPolicy.md index 09b92457f7..35a553e80d 100644 --- a/docs/design/plugins/CollaborationModelPolicy.md +++ b/docs/design/plugins/CollaborationModelPolicy.md @@ -83,7 +83,7 @@ let policy = if startup { ## Rule check -Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). | Rule | Application | | --- | --- | diff --git a/docs/design/plugins/ExecutionSettings.md b/docs/design/plugins/ExecutionSettings.md index 067e75a02b..38ee2e143f 100644 --- a/docs/design/plugins/ExecutionSettings.md +++ b/docs/design/plugins/ExecutionSettings.md @@ -8,7 +8,7 @@ ExecutionSettings owns the `execution` document and the process execution switch ExecutionSettings owns: -- The `execution` source: its file, its schema, and the two switches `sandbox` and `network`, both defaulting to `false` and declared as user-only members. This contract changes their authority: today the source declares no user-only member, so an owner or agent write could change the switches; under this contract such a write is `user_only`, and the delivery lists the change. +- The `execution` source: its file, its schema, and the two switches `sandbox` and `network`, both defaulting to `false` and declared as user-only members. This contract changes their authority: today the source declares no user-only member (`crates/dim-app-server/src/execution_settings.rs`), so an owner or agent write could change the switches; under this contract such a write is `user_only`, and the delivery lists the change. - The value `{sandbox, network}`: the switches in force now, read at each use. Callers keep: @@ -73,7 +73,7 @@ let switches = execution_settings.read(cancelled.clone()).await.map_err(|error| ## Rule check -Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). | Rule | Application | | --- | --- | diff --git a/docs/design/plugins/ModelLog.md b/docs/design/plugins/ModelLog.md index 7b94f1ebc4..104c719b32 100644 --- a/docs/design/plugins/ModelLog.md +++ b/docs/design/plugins/ModelLog.md @@ -74,7 +74,7 @@ if let Some(directory) = directory { ## Rule check -Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). | Rule | Application | | --- | --- | diff --git a/docs/design/plugins/PermissionRules.md b/docs/design/plugins/PermissionRules.md index 30bed4aab0..4677679f8a 100644 --- a/docs/design/plugins/PermissionRules.md +++ b/docs/design/plugins/PermissionRules.md @@ -100,7 +100,7 @@ client ## Rule check -Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). | Rule | Application | | --- | --- | diff --git a/docs/design/plugins/PromptSettings.md b/docs/design/plugins/PromptSettings.md index 2a53c978ae..09bbcd480a 100644 --- a/docs/design/plugins/PromptSettings.md +++ b/docs/design/plugins/PromptSettings.md @@ -29,11 +29,8 @@ Callers keep: PromptSources reads the base text once, while its Session part applies. ```rust -let base = prompt_settings - .base(cancelled.child_token()) - .await - .ok() - .and_then(|view| view.text); +// `prompt_settings` is the BasePromptSettings port; its read answers the text or none. +let base = prompt_settings.base(cancelled.child_token()).await.ok().flatten(); let text = factory.base.or(base).unwrap_or_else(|| BUILT_IN.into()); ``` @@ -77,7 +74,7 @@ A read returns the member as stored after the schema check; an absent member is ## Rule check -Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). | Rule | Application | | --- | --- | @@ -106,7 +103,7 @@ None new. The consumers ([PromptSources](../../architecture/rust-agent/plugins/P ## Binding appendix -The three reads are one service on the owner type; the old `BasePromptSettingsHost`, `SkillsInstructionsSettingsHost` and `SummaryPromptSettingsHost` types and their traits are deleted. +The three reads are one service on the owner type; the old `BasePromptSettingsHost`, `SkillsInstructionsSettingsHost` and `SummaryPromptSettingsHost` wrapper types are deleted, while the traits `BasePromptSettings`, `SkillsInstructionsSettings` and `SummaryPromptSettings` stay in `dim-agent-capabilities` and the owner implements them. ```rust use dim_agent_runtime::PublicService; diff --git a/docs/design/plugins/PromptSuggestionSettings.md b/docs/design/plugins/PromptSuggestionSettings.md index eb6ec7ba78..432ac9906b 100644 --- a/docs/design/plugins/PromptSuggestionSettings.md +++ b/docs/design/plugins/PromptSuggestionSettings.md @@ -72,7 +72,7 @@ The reply carries both members because the schema gives both a default; a docume ## Rule check -Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). | Rule | Application | | --- | --- | diff --git a/docs/design/plugins/ProviderSettings.md b/docs/design/plugins/ProviderSettings.md index 96eab4e92c..dfd529a7ce 100644 --- a/docs/design/plugins/ProviderSettings.md +++ b/docs/design/plugins/ProviderSettings.md @@ -72,7 +72,7 @@ let user_agent = configured.unwrap_or_else(|| dim_user_agent()); ## Rule check -Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). | Rule | Application | | --- | --- | diff --git a/docs/design/plugins/Settings.md b/docs/design/plugins/Settings.md index 22b5713bfc..f235794417 100644 --- a/docs/design/plugins/Settings.md +++ b/docs/design/plugins/Settings.md @@ -12,7 +12,7 @@ Settings owns: - **Documents and revisions.** The user document (a file, or a row in the native store) and the project document (a file under an authorized project); the opaque revision that changes on every committed write; one writer at a time per document. - **Change application.** Running a caller's change against the current document under the owner's exclusion, checking the result, writing it, publishing the fact, and reporting whether durability is confirmed. - **Authority.** An owner change and an agent change may not alter a user-only member; a user edit may. Every member marked `writeOnly` that is reachable through `properties` is withheld from the agent, and the agent may not set it; the rule does not scan `items`, `$defs` or `anyOf`. -- **Authorized projects.** The cwd → project table, the host-registered project root each authorized cwd denotes, and the fact announcing a new one. +- **Authorized projects.** The cwd → project table, the FileStorage root it registers with `add_root` for each authorized cwd, and the fact announcing a new one. - **Facts.** `settings/` with `{source, scope, revision}` after a commit, and `settings/projects` with `{root, cwd}` after a new authorization. Callers keep: @@ -107,7 +107,7 @@ let project = projects .find(|project| project.cwd == cwd) .ok_or(WorkflowError::WorkspaceNotAuthorized)?; let definitions = format!("{}/.dimcode/workflows/{}", project.cwd, name); -let bytes = storage.read(definitions, cancelled).await?; // FileStorage's operation +let bytes = storage.read(definitions, None, None, cancelled).await?; // FileStorage's operation ``` ## Own contract @@ -206,14 +206,14 @@ A fact is published after the commit and never carries a document. A failed fact - [Settings service](../appserver/settings-service.md) §4.1 (common shapes: `Snapshot`, `Sources`, `SettingsScope`), §4.2 (the `settings` service), §4.5 (the Rust binding), §5 (the operations' flows), §6 (the error codes) and §11 (acceptance). §4.3 is [SettingsMethods](SettingsMethods.md)'s. The document's §3 state, §4.4 events, §7 security, §8.1, §9 and §10 stay in force; §4.4's `project_authorized` payload keeps `{root, cwd}`, and the new acceptance is the delivery's flow tests. - [Settings service](../appserver/settings-service.md) §8.1's note that Rust owners keep their own methods stays; the methods' shapes are in each owner's contract. - [Resource owner operations](../contracts/resource-owner-operations.md) §Settings. -- [Service faces](../service-faces.md) §3.3's `settingsService` row, §3.2's host-port sentence for the three prompt ports, and §4.1's `settingsService` paragraph. +- [Service faces](../service-faces.md) §3.3's `settingsService` row, §3.2's host-port sentence (`executionSettings`, `promptSuggestionSettings`), §4's prompt-ports paragraph, and §4.1's `settingsService` paragraph. - [Management methods](../appserver/management-methods.md)'s `settings.read`/`update`/`sources`/`projects` list. - [Prompt overrides](../appserver/prompt-overrides.md) §3.1 (the three prompt ports are one service; see [PromptSettings](PromptSettings.md)). - [Permission command rules](../appserver/permission-command-rules.md) §4.1's `commandRules` service (see [PermissionRules](PermissionRules.md)). ## Rule check -Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). | Rule | Application | | --- | --- | @@ -297,7 +297,7 @@ impl Scope { /// One document's replacement from the change callback: its own `reason` and `message`. #[derive(Debug, thiserror::Error)] -#[error("{code}: {message}")] +#[error("{reason}: {message}")] pub struct ChangeRefused { pub reason: String, pub message: String, diff --git a/docs/design/plugins/SettingsMethods.md b/docs/design/plugins/SettingsMethods.md index 0600f1b5fa..ccbbc93867 100644 --- a/docs/design/plugins/SettingsMethods.md +++ b/docs/design/plugins/SettingsMethods.md @@ -10,7 +10,7 @@ SettingsMethods owns: - The `settings` management namespace: which methods exist, their request and reply data, and the mapping from Settings' errors to the client's error codes. - The declared-only rule and the source-name resolution: the namespace maps the client's `source` name to the registered declared source's id, and refuses a name whose owner is a Rust document. -- Admission: paired devices are never served the namespace; the authenticated loopback Web entry is served `settings.read` and `settings.update` for its allowlisted sources (`model-log` and `execution`). +- Admission: paired devices are never served the namespace; the authenticated loopback Web entry is served `settings.read` and `settings.update` for its allowlisted sources (`WEB_SETTINGS_SOURCES` in `crates/dim-app-server/src/protocol.rs`: `model-log` and `execution`). Callers keep: @@ -25,7 +25,7 @@ Callers keep: | A client lists authorized projects to pass a project scope | Yes, and no client asks: no declared source declares a project file | Not an operation; `settings.projects` is deleted | | A client edits a Rust-typed source | Yes, through that owner's own namespace (`permission.*`, `collaboration.*`, and so on) | Business | -Every caller of the namespace: the CLI reads `prompts`, `prompt-suggestion`, `execution`, `model-log` and `workflow`; the Web `DiagnosticsSettings` and `PermissionsSettings` pages read `model-log` and `execution`; the Workflow TypeScript plugin reads the plugin-face `settings` service `projects`, which is not this namespace. +Every caller of the namespace: the CLI reads `prompts` (`crates/dim-cli/src/prompt_command.rs`, `crates/dim-cli/src/session_host.rs`), `prompt-suggestion` and `execution` (`session_host.rs`), `model-log` (`crates/dim-cli/src/recording.rs`) and `workflow` (`crates/dim-cli/src/management/workflow.rs`); the Web `DiagnosticsSettings` and `PermissionsSettings` pages (`web/src/features/settings/`) read `model-log` and `execution`; the Workflow TypeScript plugin (`runtime/plugins/workflow/catalog.ts`) reads the plugin-face `settings` service, which is not this namespace. ## Caller example @@ -127,7 +127,7 @@ Invalid params covers a malformed request, an unknown field, a missing revision, ## Rule check -Rules: [§7](https://github.com/arcships/dim/blob/2fc4f50b47529e17d51e92b1d7441734771226fc/docs/architecture/rust-agent/principles.md#7-所有者与操作), [ADR 002](../../adr/002-plugin-scope.md). +Rules: [§7](https://github.com/arcships/dim/pull/2029), [ADR 002](../../adr/002-plugin-scope.md). | Rule | Application | | --- | --- |