diff --git a/README.md b/README.md index 24b33af3..6661d108 100644 --- a/README.md +++ b/README.md @@ -1,88 +1,74 @@ # rustscript-agent -A small independent runner for agents written in RustScript (`.rss`). The runner owns only program loading, HTTP policy configuration, host binding, and the VM `Waiting` → resume driver. Provider protocol, prompt state, turn limits, tool-call handling, and final output remain in the RustScript source. +`rustscript-agent` is a standalone agent runtime with **agent policy in RustScript and authority/durability in Rust**. RSS programs own the model loop, provider adaptation, tool routing, approval policy, and compaction decisions; the Rust host owns admission, capabilities, durable state, effect commits, and transport. -## Run +## Core properties + +- **Script-owned behavior:** the bundled coding loop, provider dispatch, Guardian review, and tool registry live under [`rss/`](rss/). +- **Typed host boundary:** named host shapes preserve `Unit`, `Option`, and `Result` semantics instead of inferring variants from JSON nulls. +- **Atomic admission:** each run freezes its session context, provider profile, tool registry, workspace authority, limits, prompt, deadline, and plugin graph before execution. +- **Durable lifecycle:** SQLite-backed sessions, messages, runs, events, approvals, graph pins, and effect receipts support restart repair and replay without reissuing completed work. +- **Reviewed effects:** tool calls pass through prepare, Guardian or user review, native execution, and durable commit; managed workspace mutations use private trees and explicit publication. +- **Fail-closed authority:** HTTP, filesystem, process, credential, workspace, and plugin-control capabilities are bounded and deny by default unless the native host grants them. + +## Quick start + +Start the gateway with the immutable bundled coding entry: ```bash -cargo run --release -- \ - --script examples/http_get.rss \ - --allow-host api.example.com +RUSTSCRIPT_AGENT_SOURCE=bundled:coding \ +RUSTSCRIPT_AGENT_ALLOW_ANONYMOUS=1 \ +cargo run --release --bin rustscript-agent-gateway ``` -The HTTP host is deny-by-default. Every destination must be explicitly allowlisted (hosts **and** ports; see [Configuration](docs/configuration.md)). The runner enables the RustScript `http-client` feature and does not provide an upstream agent or model adapter. - -## Library API +Anonymous mode is for local evaluation. Production deployments should configure bearer authentication, persistent state, provider credentials, and network allowlists; see [Configuration](docs/configuration.md) and [Deployment](docs/deployment.md). -```rust -use rustscript_agent::{AgentConfig, AgentRunner}; +The request path is compact: -let runner = AgentRunner::from_file( - "agent.rss", - AgentConfig::for_hosts(["api.example.com"]), -)?; -let result = runner.run()?; +```text +HTTP / Telegram + -> Rust admission snapshot and durable run + -> RSS provider + agent + Guardian policy + -> Rust capability/effect boundary + -> durable messages, events, receipts, and publications ``` -The current scope is intentionally synchronous at the Rust API boundary: a pending HTTP host operation is driven internally through the VM's blocking wait/resume path. A future gateway can expose the same VM lifecycle asynchronously without moving agent behavior into Rust. +## Documentation -## Hermes-compatible gateway +- [Architecture](docs/architecture.md) — RSS/native ownership, typed boundaries, lifecycle, effects, replay, and capability fences +- [HTTP API](docs/api.md) — implemented route families and lifecycle semantics +- [Configuration](docs/configuration.md) — canonical environment, embedding, capability, and provider settings +- [Deployment](docs/deployment.md) — source builds, state, operations, shutdown, backup, systemd, and containers +- [Development](docs/development.md) — repository layout, focused tests, CI, RSS corpus, and fixture conventions +- [Status](docs/status.md) — detailed capability and maturity matrix, including explicit exclusions -The gateway is part of this independent repository. It uses the RustScript `pd-vm` crate for RSS execution and does not depend on the `pd-edge` gateway runtime. +## Build and test + +The repository uses Rust 1.99 in CI and pins RustScript Core at `11c9ee908a29365bd02573311f56e9308eb7dbe6`. ```bash -RUSTSCRIPT_AGENT_SOURCE=bundled:coding \ -RUSTSCRIPT_AGENT_ALLOW_HOSTS=api.example.com \ -RUSTSCRIPT_AGENT_ALLOW_PORTS=443 \ -RUSTSCRIPT_AGENT_BEARER_TOKEN='' \ -RUSTSCRIPT_AGENT_STATE_DB=/var/lib/rustscript-agent/state.db \ -cargo run --release --bin rustscript-agent-gateway +cargo +1.99.1 build --locked +cargo +1.99.1 test --locked --all-features --test docs_contract_tests +cargo +1.99.1 test --locked --all-features --all-targets +cargo +1.99.1 fmt --all -- --check +``` + +For focused local coding-agent coverage: + +```bash +cargo test --test coding_agent_e2e_tests +cargo test --test coding_agent_edge_e2e_tests ``` -A present `config.yaml` `agent.source` is the authoritative agent source; a -present-but-invalid config source fails closed with no environment fallback. -Only when the config is missing does the gateway fall back to -`RUSTSCRIPT_AGENT_SOURCE`, then the deprecated `RUSTSCRIPT_AGENT_SCRIPT`, then -the bundled coding entry. A valid source is `bundled:coding`, or `file:` plus -an absolute path. Full environment-variable reference: -[docs/configuration.md](docs/configuration.md). -Deployment, systemd/container examples, shutdown and backup: [docs/deployment.md](docs/deployment.md). - -## Status - -This repository is **not v1-complete**. The table describes code in this -source checkout; it does not claim a published release, live-provider -availability, or final composed-candidate acceptance. Blocked or excluded -items are explicit, and no placeholder route is advertised. - -| Area | Status | -| --- | --- | -| Single-run runner (`rustscript-agent --script … --allow-host …`) | Implemented | -| Gateway HTTP API: sessions, runs, SSE events, stop, jobs CRUD, subagent interrupt | Implemented (see [plans/2026-07-30_rustscript-agent-gateway-api.md](plans/2026-07-30_rustscript-agent-gateway-api.md)) | -| Durable SQLite state: sessions/messages/runs/events/jobs/approvals/compactions, restart recovery | Implemented | -| Gateway entry selection | A present `config.yaml` `agent.source` is authoritative; a missing config falls back to `RUSTSCRIPT_AGENT_SOURCE`, then the deprecated `RUSTSCRIPT_AGENT_SCRIPT`, then bundled `bundled:coding`. | -| Legacy chat completion path (`/api/sessions/{id}/chat`) | Legacy-constructor-only; production gateway selection via `RUSTSCRIPT_AGENT_SOURCE`, legacy `RUSTSCRIPT_AGENT_SCRIPT`, or bundled `bundled:coding` returns `501 agent_source_not_configured`. Normal coded-agent runs use `POST /v1/runs`. | -| OpenAI Chat Completions (`openai`, `openai_chat`, or default) | Current source has buffered and streaming requests through the opaque native credential transport; this is source status, not live-provider validation. | -| Codex Responses (`openai-codex` / `codex-responses`) | Access-only source path is present. Full refresh/lifecycle support is not claimed here. | -| Generic custom Responses adapter (explicit adapter selection) | Not implemented; returns typed `not_implemented` and sends no request. | -| Anthropic Messages | Not implemented; remains a typed `not_implemented` stub. | -| API hardening (A7): bounded per-peer-IP/per-account rate limiting, client-disconnect policy | Implemented (disabled by default; see [docs/configuration.md](docs/configuration.md)) | -| Observability (A9): bounded metrics registry, `GET /metrics`, structured terminal tracing | Implemented (see [docs/deployment.md](docs/deployment.md)) | -| RSS coding loop + durable compaction policies (A5) | The gateway's bundled coding entry runs through the agent worker; compaction policies remain implemented and tested (`rss/agent/compact.rss`). | -| RSS coding tools + workspace-confined loop | Implemented for the library worker: `read_file`, `search_files`, `write_file`, `patch`, `terminal`, `process` run serially through `rss/tools/dispatch.rss`. Local E2E: `cargo test --test coding_agent_e2e_tests` and `cargo test --test coding_agent_edge_e2e_tests`. See [docs/configuration.md](docs/configuration.md). Parallel tools remain excluded (A6). | -| Approval execution chain (A4) | Implemented for tool dispatch: durable approval records, `ask` policy for write/process, HTTP and Telegram approve/reject, one typed terminal result. A general-purpose harness layer beyond tool approval remains excluded. | -| Parallel tools and subagents (A6) | Not implemented (excluded from the current milestone scope) | -| Scheduled / durable job execution | **Not implemented (explicitly excluded)**. Job CRUD, pause/resume, and latest-output routes exist, but there is no scheduler; `POST /api/jobs/{id}/run` is intentionally absent and answers `404`. | -| Telegram gateway (A8) | **Implemented**: native Bot API transport (https/rustls), deny-by-default account/chat/user allowlists, durable delivery cursors (at-least-once), bounded 429/5xx/401 retries, fail-closed first-boot drain, bounded shutdown drain. See [docs/deployment.md](docs/deployment.md). | - -The bounded `config.yaml` / `auth.yaml` loaders and production -`config::load_snapshot` bridge exist. Package-level end-to-end config/auth/provider -acceptance, final composed-candidate acceptance, and remote delivery remain -open. - -Current lifecycle/reliability behavior is covered by the integration -suites in `tests/` (admission, bounded delivery, terminal-commit retries, -restart recovery, storage stalls, coding-agent E2E). CI runs them with -`cargo test --locked --all-features --all-targets`. The main coding -workflow E2E is `cargo test --test coding_agent_e2e_tests`. Cancellation -and output-limit edges are `cargo test --test coding_agent_edge_e2e_tests`. +## Current maturity + +The gateway, durable run lifecycle, serial coding tools, approvals, managed effects, plugin graph pinning, and Telegram transport are implemented in the current source tree. The project remains pre-v1: provider coverage is uneven, scheduled execution and parallel tools/subagents are excluded, and final remote-provider acceptance remains open. See the [status matrix](docs/status.md). + +## Related projects + +- [RustScript Core](https://github.com/rustscript-lang/rustscript) — language, compiler, VM, and host SDK +- [RustScript specification](https://github.com/rustscript-lang/spec) — language specification +- [pd-edge](https://github.com/rustscript-lang/pd-edge) — RustScript edge runtime and ABI +- [pd-controller](https://github.com/rustscript-lang/pd-controller) — control plane for RustScript edge deployments +- [RustScript Playground](https://github.com/rustscript-lang/playground) — browser playground +- [RustScript website and documentation](https://github.com/rustscript-lang/website) diff --git a/docs/api.md b/docs/api.md new file mode 100644 index 00000000..f4385dd1 --- /dev/null +++ b/docs/api.md @@ -0,0 +1,86 @@ +# HTTP API + +The production router is defined in [`src/gateway/api_server.rs`](../src/gateway/api_server.rs). This reference lists only routes registered there; request and response details remain governed by the typed handlers and tests. + +## Common behavior + +- The configured request-body limit applies to the complete router. +- When bearer authentication is configured, send `Authorization: Bearer ***` on every route. Optional rate limiting runs first per peer IP and then per verified account. +- Anonymous mode can expose ordinary routes, but managed-workspace maintenance, run-effect queries, and plugin control still require configured authentication. Plugin control additionally requires trusted host-side control configuration. +- Handler-generated errors use `{"error":{"code":"...","message":"..."}}`, with route-specific status codes. Framework rejections, including JSON extractor failures and router-wide body-limit rejections, may use Axum's native response format until they are normalized. +- Mutating session/job handlers and run admission commit durable state before publishing it in memory. + +See [Configuration](configuration.md) for authentication, body, rate, and lifecycle bounds. + +## Health and discovery + +| Method | Path | Semantics | +| --- | --- | --- | +| `GET` | `/health/detailed` | Liveness plus active-run and pending-terminal gauges; includes bounded source metadata when available. | +| `GET` | `/metrics` | Prometheus text from the bounded in-memory registry; no storage query. | +| `GET` | `/v1/models` | Returns the configured model/provider identity. | + +## Sessions + +| Method | Path | Semantics | +| --- | --- | --- | +| `GET`, `POST` | `/api/sessions` | List or create sessions. Listing supports bounded pagination and source/search filters. | +| `GET`, `PATCH`, `DELETE` | `/api/sessions/{session_id}` | Read, update title/end reason, or delete a session. | +| `GET` | `/api/sessions/{session_id}/messages` | Return the session's canonical message history. | +| `POST` | `/v1/sessions/{session_id}/workspace` | Bind a validated workspace; rejected while the session has an active run. | +| `POST` | `/v1/sessions/{session_id}/compact` | Run the durable compaction lifecycle for the session. | +| `POST` | `/api/sessions/{session_id}/chat` | Legacy synchronous chat path. Source-selected production gateway constructors leave it unconfigured and return `501 agent_source_not_configured`; normal coded-agent execution uses `POST /v1/runs`. | + +## Runs, events, effects, and approvals + +| Method | Path | Semantics | +| --- | --- | --- | +| `POST` | `/v1/runs` | Atomically admit a run and return `202`. Optional `Idempotency-Key` replay returns the original run; reuse with different canonical input returns a conflict. | +| `GET` | `/v1/runs/{run_id}/events` | SSE replay followed by live events. `after_seq` resumes after a cursor; a cursor older than retained history returns `409 event_cursor_too_old`. | +| `POST` | `/v1/runs/{run_id}/stop` | Request cooperative cancellation. The durable run stays `running` until one terminal transition commits. | +| `GET` | `/v1/runs/{run_id}/effects` | Authenticated, read-only, cursor-paginated managed-effect summaries. It accepts `after_effect_id` and a bounded `limit`. | +| `GET` | `/v1/runs/{run_id}/approvals` | List pending approvals for an active run; requires bearer authentication. | +| `POST` | `/v1/runs/{run_id}/approvals/{approval_id}` | Resolve one pending approval with `{"decision":"approved"}` or `{"decision":"denied"}`. Resolution is owner-bound and one-time. | + +Run admission freezes provider/tool/workspace/graph state before returning. A fresh admission starts one worker; an idempotent replay does not start another. Events and messages are durable before SSE broadcast. Delivery is at-least-once, so clients should deduplicate by durable event identity and resume by sequence. + +## Managed workspaces + +These routes require persistent managed-workspace configuration and authenticated native authority. The path workspace ID must equal the typed body workspace ID. + +| Method | Path | Semantics | +| --- | --- | --- | +| `POST` | `/v1/workspaces/{workspace_id}/checkpoints` | Freeze a checkpoint; returns `201`, or `202` when submission succeeded but the final receipt is unknown. | +| `POST` | `/v1/workspaces/{workspace_id}/restore` | Restore a checkpoint and atomically admit a new run; returns `202` and starts the restored worker. | +| `POST` | `/v1/workspaces/{workspace_id}/branches` | Create a branch from authorized managed state; returns `201`. | +| `POST` | `/v1/workspaces/{workspace_id}/publish` | Publish a managed branch; returns `200`, or `202` for a submitted-unknown outcome. | + +The typed request/receipt families and failure mapping are implemented in [`src/gateway/workspaces.rs`](../src/gateway/workspaces.rs). + +## Plugin graphs + +Plugin routes require a verified bearer plus trusted host-side `InstallAuthorization`; request JSON cannot supply install authority. + +| Method | Path | Semantics | +| --- | --- | --- | +| `POST` | `/v1/plugins/install` | Validate and install an immutable plugin package capture. | +| `POST` | `/v1/plugin-graphs/resolve` | Resolve installed packages into a closed graph lock. | +| `POST` | `/v1/plugin-graphs/{graph_id}/prepare` | Compile and validate the stored graph without activating it. | +| `GET` | `/v1/plugin-graphs/{graph_id}` | Read the stored graph/control view. | +| `POST` | `/v1/plugin-activations` | Activate a prepared graph through the generationed control store. | +| `POST` | `/v1/plugin-activations/{activation_id}/rollback` | Roll back through activation history with conflict checks. | + +Handlers and authorization are in [`src/gateway/plugins.rs`](../src/gateway/plugins.rs); durable locks, refs, activation generations, history, retention, and revocation are in [`src/plugins/control_store.rs`](../src/plugins/control_store.rs). + +## Jobs and subagent compatibility + +| Method | Path | Semantics | +| --- | --- | --- | +| `GET`, `POST` | `/api/jobs` | List or create durable job records. | +| `GET`, `PATCH`, `DELETE` | `/api/jobs/{job_id}` | Read, update, or delete a job record. | +| `GET` | `/api/jobs/{job_id}/output/latest` | Return the stored latest output, if any. | +| `POST` | `/api/jobs/{job_id}/pause` | Set the job record disabled. | +| `POST` | `/api/jobs/{job_id}/resume` | Set the job record enabled. | +| `POST` | `/api/subagents/{subagent_id}/interrupt` | Route an interrupt to the run handle with that ID. | + +Job CRUD does not schedule or execute jobs. There is no `/api/jobs/{job_id}/run` route. Parallel tool dispatch and subagent fan-out are not implemented; see [Status](status.md). diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 00000000..d3dfe44f --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,107 @@ +# Architecture + +`rustscript-agent` splits control policy from host authority: RustScript (`.rss`) decides what the agent should do, while Rust decides what the process is permitted to do and when state becomes durable. + +## Responsibility split + +| RustScript owns | Rust owns | +| --- | --- | +| Agent loop, provider selection and protocol adaptation | HTTP/Telegram ingress, request normalization, authentication, and rate limits | +| Prompt/message shaping, turn limits, compaction policy, and tool dispatch | Atomic admission, deadlines, cancellation, capacity, and run sequencing | +| Guardian review policy and `allow` / `deny` / `needs_user` decisions | Capability issuance, user-approval handoff, filesystem/process confinement, and secret custody | +| Declarative storage commands and plugin manifests | SQLite worker, durable-before-visible publication, graph capture/pinning, effect journal, and restart repair | + +The owning implementations are the bundled [`rss/agent`](../rss/agent/), [`rss/llm`](../rss/llm/), [`rss/tools`](../rss/tools/), and [`rss/storage`](../rss/storage/) modules on the policy side, and [`AgentService`](../src/service.rs), the [gateway](../src/gateway/), [capabilities](../src/capabilities/), [effects](../src/effects/), and [plugins](../src/plugins/) on the native side. The storage SQL is expressed in RSS, but Rust controls the worker, transaction boundary, sequencing, and in-memory publication. + +## Typed host boundary + +The public host catalog uses descriptor-owned named structs rather than untyped maps for closed shapes. [`src/runtime/host_types.rs`](../src/runtime/host_types.rs) declares fixed provider, capability, process, approval, tool, and plugin-state envelopes. Open provider/plugin JSON crosses as bounded serialized text and is audited in [`src/runtime/host_compose.rs`](../src/runtime/host_compose.rs). + +The boundary preserves three distinct concepts: + +- `Unit` represents an operation with no value. +- `Option` uses the core's explicit tagged carrier; `None`, `Some(())`, and nested options remain distinct. +- `Result` is validated as its declared carrier and is not reconstructed from a null or an ad hoc `{ok: ...}` map. + +[`src/runtime/host_shapes.rs`](../src/runtime/host_shapes.rs) converts only schema-owned legacy nullable leaves and delegates final validation to the VM. Ambiguous nulls, duplicate wrapping, invalid resource handles, and undeclared dynamic returns fail closed. Typed-boundary regressions are exercised by [`tests/native_callback_result_composite_rss_tests.rs`](../tests/native_callback_result_composite_rss_tests.rs), [`tests/rss_tools_contract_tests.rs`](../tests/rss_tools_contract_tests.rs), and the host-catalog audits in [`src/runtime/host_compose.rs`](../src/runtime/host_compose.rs). + +## Admission snapshot and run lifecycle + +`POST /v1/runs` enters [`AgentService::admit_external_with_workspace_selector`](../src/service.rs). Admission uses one capacity permit and one absolute cancellation deadline across every preparation attempt. Slow prompt, workspace, storage, and plugin preparation runs outside the global commit gate. The commit phase then revalidates the relevant inputs and atomically publishes the durable admission plus its in-memory handle. + +The frozen admission context includes: + +- session history and parent run; +- model and provider profile; +- tool registry and run limits; +- canonical workspace binding and native workspace authority; +- coding prompt and project guidance; +- active or checkpoint-selected plugin graph, package refs, and callable capture; +- deadline, cancellation token, and idempotency identity. + +A rejected admission leaves no partial session, message, run, event, pin, or live permit. The implementation and contention/deadline regressions live in [`src/service.rs`](../src/service.rs), [`tests/run_lifecycle_tests.rs`](../tests/run_lifecycle_tests.rs), and [`tests/provider_durable_replay_loop_tests.rs`](../tests/provider_durable_replay_loop_tests.rs). + +After admission, the worker drives the exported RSS `run(context)` stream. Rust commits `run.started`, provider/tool lifecycle events, and exactly one terminal transition. Stop, deadline, disconnect, and gateway halt request typed cancellation; a run remains durably `running` until the terminal commit succeeds. Live SSE delivery follows durable state and is at-least-once. + +## Durable session, run, and event state + +With `RUSTSCRIPT_AGENT_STATE_DB`, [`GatewayPersistence`](../src/gateway/store.rs) serializes SQLite commands through the compiled [`rss/storage/main.rss`](../rss/storage/main.rss) program. Durable state covers sessions, messages, runs, events, jobs, approvals, compactions, idempotency receipts, plugin locks/activations/refs, plugin state, and managed-effect records. + +Writes are durable before they become visible in the in-memory store or live event stream. Event IDs and message IDs are stable for provider turns and tool calls, while per-run sequence numbers define replay order. Terminal commits retry within bounded limits; an uncommitted terminal remains observable as `terminal_pending` instead of being reported as complete. + +The store migrates and repairs interrupted rows before rebuilding memory. Loading is cursor-paginated with row and byte bounds rather than a single unbounded query. See [`src/gateway/store.rs`](../src/gateway/store.rs), [`rss/storage/load.rss`](../rss/storage/load.rss), and [`tests/storage_tests.rs`](../tests/storage_tests.rs). + +## Effect prepare, review, commit, and rollback + +Tool execution has a native lifecycle rather than a direct guest-to-OS call: + +1. **Prepare:** validate the frozen registry identity, owner, risk, arguments, deadline, cancellation, graph pin, and workspace head; issue an opaque execution token or return an existing durable replay. +2. **Review:** apply configured read/write/process policy. Guardian evaluates a bounded action preview. A decision may allow, deny, or request a user decision. +3. **Execute:** a token-scoped host performs the confined filesystem/process/artifact operation. RSS never receives raw native authority. +4. **Commit:** persist canonical tool events, the result message, effect receipt, and any managed tree publication before broadcasting them. +5. **Rollback or fence:** abandon uncommitted private state when absence is proven. An indeterminate commit keeps the owner/fence for reconciliation rather than guessing that the effect failed. + +The generic token lifecycle is in [`src/capabilities/lifecycle.rs`](../src/capabilities/lifecycle.rs). Managed tree preparation and native authority are in [`src/effects/broker.rs`](../src/effects/broker.rs); durable event/result composition is in [`src/service/managed_effects.rs`](../src/service/managed_effects.rs). Managed rollback covers private workspace state. Process or other effects outside the tree are explicitly recorded as not reverted; no general rollback of external systems is claimed. + +## Guardian and user handoff + +[`rss/agent/guardian.rss`](../rss/agent/guardian.rss) owns the review decision schema and fail-closed policy. Its valid outcomes are: + +- `allow`: execute under the already prepared native scope; +- `deny`: persist refusal and do not execute; +- `needs_user`: publish one durable pending approval for the original run and suspend that call. + +The HTTP approval routes and Telegram buttons resolve only the pending durable row. Resolution does not mint a broader grant, and replay cannot reuse a one-time decision for another call. Malformed or unavailable Guardian output fails closed. The handoff is covered by [`tests/guardian_sandbox_policy_tests.rs`](../tests/guardian_sandbox_policy_tests.rs) and [`tests/provider_durable_replay_loop_tests.rs`](../tests/provider_durable_replay_loop_tests.rs). + +## Plugin graph pinning + +Plugin administration installs immutable package captures, resolves a closed graph, prepares it, and moves a generationed activation pointer. A new run does not execute from caller-provided `graph_id` data: native admission reads the active/checkpoint graph, validates its lock and package refs, captures the callable, and commits the graph ID, activation generation, and ref with the run. + +A replay returns the original pin without consulting a newer activation. Existing runs therefore retain their admitted graph across a hot cut; revocation and missing artifacts fail closed. The control metadata is in [`src/plugins/control_store.rs`](../src/plugins/control_store.rs), and the admission/recovery invariant is implemented in [`src/plugins/pin.rs`](../src/plugins/pin.rs) and tested by [`tests/tools_pin_production_ab.rs`](../tests/tools_pin_production_ab.rs). + +## Restart and replay + +Restart processing distinguishes completed work from work whose outcome is unknown: + +- completed provider steps replay their durable response without another provider call; +- retry-safe pending provider requests may retry the same logical turn; +- unsafe or effectful pending provider requests become typed interruptions; +- committed tool results replay without running the tool or incrementing metrics again; +- open capability tokens and owned children are interrupted and cleaned up; +- interrupted runs receive one terminal repair, and pending compactions are failed; +- managed branches derive writer ownership from bounded durable history and remain unresolved if the proof is incomplete. + +See [`src/durable_provider.rs`](../src/durable_provider.rs), the recovery paths in [`src/service.rs`](../src/service.rs), [`src/gateway/store.rs`](../src/gateway/store.rs), and managed restart derivation in [`src/effects/broker.rs`](../src/effects/broker.rs). Restart and lost-ack scenarios are covered by [`tests/provider_durable_replay_loop_tests.rs`](../tests/provider_durable_replay_loop_tests.rs), [`tests/effect_commit_recovery_tests.rs`](../tests/effect_commit_recovery_tests.rs), and [`tests/plugin_store_recovery_tests.rs`](../tests/plugin_store_recovery_tests.rs). + +## Capability boundaries + +Authority is native, scoped, and revocable: + +- HTTP is deny-by-default for schemes, hosts, ports, redirects, sizes, timeouts, and private addresses. +- File tools resolve beneath the admitted canonical workspace; managed mode writes private object trees instead of the source directory. +- Process tools execute `argv` directly, bind child handles to one run/token generation, meter output, and clean up owned children on cancellation or shutdown. +- Provider credentials remain opaque native resources; sanitized metadata can cross into RSS, raw secrets cannot. +- Plugin management requires both verified bearer ingress and a trusted host-side install authorization. +- Checkpoint, restore, branch, publish, and effect-query operations require native workspace authority and persistent state. + +The concrete limits are canonical in [Configuration](configuration.md). Security boundaries are also exercised by [`tests/capability_tests.rs`](../tests/capability_tests.rs), [`tests/effect_workspace_tests.rs`](../tests/effect_workspace_tests.rs), [`tests/native_auth_contract_tests.rs`](../tests/native_auth_contract_tests.rs), and [`tests/plugin_admin_api_tests.rs`](../tests/plugin_admin_api_tests.rs). diff --git a/docs/deployment.md b/docs/deployment.md index 0dd3da76..a4588d9b 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -46,7 +46,7 @@ before deploying: ```bash # The lockfile records the exact git source for pd-vm and pd-host-function: grep -A3 'name = "pd-vm"' Cargo.lock -# source = "git+https://github.com/rustscript-lang/rustscript.git?rev=fc8b0c8…#fc8b0c8…" +# source = "git+https://github.com/rustscript-lang/rustscript.git?rev=11c9ee908a29365bd02573311f56e9308eb7dbe6#11c9ee908a29365bd02573311f56e9308eb7dbe6" # The resolved dependency graph shows the same source: cargo tree --locked -p rustscript-vm ``` diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 00000000..cc3e623a --- /dev/null +++ b/docs/development.md @@ -0,0 +1,126 @@ +# Development + +## Repository layout + +| Path | Purpose | +| --- | --- | +| [`src/service.rs`](../src/service.rs) and [`src/service/`](../src/service/) | Atomic admission, run lifecycle, approvals, compaction, managed completion, and plugin administration. | +| [`src/gateway/`](../src/gateway/) | Axum API, Telegram adapter, workspace/plugin/effect routes, and RSS-backed persistence worker. | +| [`src/runtime/`](../src/runtime/) | RSS compilation/execution, closed bundles, typed host catalog, adapters, cancellation, and delivery. | +| [`src/capabilities/`](../src/capabilities/) | Token lifecycle and confined filesystem, process, and artifact capabilities. | +| [`src/effects/`](../src/effects/) | Managed workspace object store, effect journal, checkpoints, publications, authority, and restart fences. | +| [`src/plugins/`](../src/plugins/) | Manifest/schema validation, immutable packages, graph resolution/preparation, activation state, and run pins. | +| [`rss/`](../rss/) | Bundled agent, provider, auth, tool, configuration, and storage policy. | +| [`tests/`](../tests/) | Integration roots, shared support, fixtures, and consolidated case modules. | +| [`schemas/`](../schemas/) | Plugin manifest/lock/state contracts and canonical generated snapshots. | +| [`docs/`](.) | Product, architecture, API, configuration, deployment, development, and maturity references. | + +## Toolchain and scratch space + +CI selects Rust `1.99`; this checkout is verified with `1.99.1`. Keep Cargo locked to the manifest/lockfile pin. + +Integration fixtures require runner-owned scratch directories outside the checkout. CI creates one root and exports all three supported aliases: + +```bash +export RUSTSCRIPT_AGENT_TEST_TMP=/absolute/private/scratch +export RUSTSCRIPT_AGENT_TEST_TMPDIR="$RUSTSCRIPT_AGENT_TEST_TMP" +export TEST_TMPDIR="$RUSTSCRIPT_AGENT_TEST_TMP" +``` + +Tests create unique private children below that root. They must not write generated state into the repository. + +## Focused tests + +Run the narrow owner first and confirm the filter executes at least one test: + +```bash +# Documentation/configuration/deployment drift and links +cargo +1.99.1 test --locked --all-features --test docs_contract_tests + +# Every bundled RSS source +cargo +1.99.1 test --locked --all-features --test rss_corpus_compile_tests + +# Router and gateway contracts +cargo +1.99.1 test --locked --all-features --test gateway_contract_tests + +# Coding loop and cancellation/output edges +cargo +1.99.1 test --locked --all-features --test coding_agent_e2e_tests +cargo +1.99.1 test --locked --all-features --test coding_agent_edge_e2e_tests + +# Managed effect commit/recovery and plugin pinning +cargo +1.99.1 test --locked --all-features --test effect_commit_recovery_tests +cargo +1.99.1 test --locked --all-features --test tools_pin_production_ab +``` + +For an individual case, keep the integration target explicit: + +```bash +cargo +1.99.1 test --locked --all-features \ + --test docs_contract_tests relative_markdown_links_resolve -- --exact +``` + +## Full CI gates + +The canonical workflow is [`.github/workflows/ci.yml`](../.github/workflows/ci.yml): + +```bash +cargo +1.99.1 fmt --all -- --check +cargo +1.99.1 clippy --locked --all-features --all-targets -- -D warnings +cargo +1.99.1 test --locked --all-features --all-targets +git diff --check +``` + +CI also requires the tracked and untracked working tree to remain clean after the gates. + +## Bundled RSS corpus + +[`tests/rss_corpus_compile_tests.rs`](../tests/rss_corpus_compile_tests.rs) discovers sources programmatically instead of freezing a count. At this revision it finds **88** bundled sources: **87** under `rss/` and **1** under `examples/`. + +With `config-fixture`, all 88 compile through their real host catalogs. Without it, only the exact historical fixture entries `rss/auth/oauth_flow.rss`, `rss/auth/store_entry.rss`, and `rss/auth/config_entry.rss` are reported as unavailable; every other discovered source compiles against the production agent catalog. Production modules, libraries without a run export, and new files are all included automatically. + +Recheck the inventory before editing a count: + +```bash +python3 -c 'from pathlib import Path; print(sum(1 for d in ("rss", "examples") for _ in Path(d).rglob("*.rss")))' +``` + +## Consolidated integration roots + +Cargo treats each top-level `tests/*.rs` file as a separate integration binary. The current tree has **63** such roots. Related cases are consolidated below those roots with `#[path = "..."] mod ...;`; for example: + +- [`tests/docs_contract_tests.rs`](../tests/docs_contract_tests.rs) owns documentation, domain, and contract cases from `tests/cases/`; +- [`tests/gateway_contract_tests.rs`](../tests/gateway_contract_tests.rs) owns gateway/API case modules; +- [`tests/effect_commit_recovery_tests.rs`](../tests/effect_commit_recovery_tests.rs) owns the effect recovery matrices; +- larger reusable fixtures live in [`tests/support/`](../tests/support/) rather than becoming independent Cargo targets. + +At this revision, `tests/cases/` contains **86** Rust case modules. Recheck both inventories programmatically before documenting a changed count: + +```bash +python3 -c 'from pathlib import Path; print("roots", len(list(Path("tests").glob("*.rs")))); print("cases", len(list(Path("tests/cases").glob("*.rs"))))' +``` + +When adding a case, attach it to the narrowest existing root. Add a new top-level root only when it needs a distinct feature gate, binary environment, or isolation boundary. + +## Fixture timing conventions + +Compilation, process startup, and the behavior under test have different clocks: + +- Start a **setup/readiness budget** before cold compilation or gateway startup. Shared gateway bounds live in [`tests/support/gateway_ready.rs`](../tests/support/gateway_ready.rs). +- Start the operation's own deadline only after its readiness marker or required setup has completed. Do not make a short authority/deadline assertion pay for unrelated cold compilation. +- Use one absolute deadline per phase and pass it through nested waits; do not reset the clock on every poll. +- On timeout, report whether the child exited, readiness was missing, or the operation exceeded its own bound. Preserve those as separate failures. +- Timing-sensitive targets should run alone at their normal within-target concurrency when qualifying them; cross-target pressure is a separate stress run. + +Exact-child fixtures should use an owned marker containing the exact test name, parent PID, and nonce, then invoke the current test executable with `--exact`. Require the child exit code, `running 1 test`, the named test result, and the final libtest summary before accepting the result. [`tests/plugin_store_recovery_tests.rs`](../tests/plugin_store_recovery_tests.rs) contains this pattern. + +## Child ownership and cleanup + +A fixture that spawns a process owns cleanup on success, error, panic, and timeout: + +- [`tests/support/owned_child.rs`](../tests/support/owned_child.rs) kills and waits for synchronous children and can isolate a Linux process group. +- [`tests/support/owned_async_child.rs`](../tests/support/owned_async_child.rs) enables Tokio `kill_on_drop`, then synchronously reaps as a last resort. +- Drain stdout and stderr concurrently with bounded capture so a full pipe cannot deadlock the child or consume unbounded memory. +- On observer failure, request cancellation or release test gates first, then kill/reap and join owned workers before propagating the assertion. +- Never leave a background child, process group, paused gate, or immutable test tree for a later case to clean up. + +These conventions are part of fixture correctness: a passing assertion with an unreaped child or a reset deadline does not qualify the lifecycle being tested. diff --git a/docs/status.md b/docs/status.md new file mode 100644 index 00000000..db69d7d8 --- /dev/null +++ b/docs/status.md @@ -0,0 +1,68 @@ +# Status and maturity + +This matrix describes the current source checkout. It does not claim a published release, live-provider availability, or final composed-candidate acceptance. The project is pre-v1, and absent routes or adapters are listed explicitly. + +## Runtime and gateway + +| Area | Status | +| --- | --- | +| Single-run runner (`rustscript-agent --script … --allow-host …`) | Implemented for synchronous script execution. HTTP remains deny-by-default; the runner exposes host allowlisting but no port flag. | +| Gateway sessions, messages, run admission, SSE events, stop, compaction, and subagent interrupt compatibility | Implemented. The current router is summarized in [API](api.md). | +| Durable SQLite sessions/messages/runs/events/jobs/approvals/compactions/idempotency | Implemented with RSS storage commands, bounded loading, migrations, and restart recovery. In-memory mode remains available and loses state on restart. | +| Atomic admission snapshot | Implemented: one permit/deadline spans preparation; relevant state is revalidated before durable commit and in-memory publication. | +| Terminal reliability | Implemented with durable-before-live publication, bounded terminal retries, observable `terminal_pending`, and restart repair. External event delivery remains at-least-once. | +| API hardening | Implemented: body bounds, optional bounded per-IP/per-account rate limiting, constant-time bearer comparison, and configurable last-subscriber disconnect policy. Rate limiting is disabled by default. | +| Observability | Implemented: bounded metrics registry, `GET /metrics` protected when bearer authentication is configured and exposed in supported anonymous mode, detailed health, and terminal tracing events. The binaries currently install no tracing subscriber, so stderr remains the packaged log surface. | +| Telegram gateway | Implemented: native rustls Bot API transport, deny-by-default account/chat/user allowlists, durable delivery cursors, bounded retries, first-boot drain, approvals, and bounded shutdown drain. | +| TLS listener | Not implemented. The gateway serves HTTP; terminate TLS at a reverse proxy. | +| Graceful signals | `SIGINT` is handled. `SIGTERM` is not caught; the documented systemd unit uses `KillSignal=SIGINT`. | + +## Agent policy and providers + +| Area | Status | +| --- | --- | +| Bundled RSS coding loop | Implemented through `rss/agent/main.rss`, with frozen coding prompt, provider turns, serial tool continuation, and durable compaction policy. | +| Gateway entry selection | A present `config.yaml` `agent.source` is authoritative. A missing config falls back to `RUSTSCRIPT_AGENT_SOURCE`, then deprecated `RUSTSCRIPT_AGENT_SCRIPT`, then `bundled:coding`; invalid present config fails closed. | +| Legacy chat completion path (`/api/sessions/{id}/chat`) | Legacy-constructor-only; production gateway selection via `RUSTSCRIPT_AGENT_SOURCE`, legacy `RUSTSCRIPT_AGENT_SCRIPT`, or bundled `bundled:coding` returns `501 agent_source_not_configured`. Normal coded-agent runs use `POST /v1/runs`. | +| `config::load_snapshot` bridge | Implemented in the production auth host and fixture host. Bounded config/auth loading, sanitized public config, opaque credential IDs, and native secret custody are present. | +| OpenAI Chat Completions (`openai`, `openai_chat`, or default) | Buffered and streaming source paths exist through opaque native credential transport. This is source status, not live-provider validation. | +| Codex Responses (`openai-codex` / `codex-responses`) | Access-only source path is present. Full refresh/lifecycle support is not claimed. | +| Generic custom Responses adapter | Not implemented; explicit selection returns typed `not_implemented` and sends no request. | +| Anthropic Messages | Not implemented; the adapter remains a typed `not_implemented` stub. | +| Package-level end-to-end config/auth/provider acceptance | Open. Final composed-candidate acceptance and remote delivery remain open. | + +## Tools, approvals, and authority + +| Area | Status | +| --- | --- | +| Built-in coding tools | Implemented for `read_file`, `search_files`, `write_file`, `patch`, `terminal`, and `process`, dispatched serially through RSS. | +| Filesystem/process confinement | Implemented with canonical workspace roots, token-scoped capability owners, direct `argv` execution, output bounds, cancellation, and owned-child cleanup. This is application confinement, not an OS sandbox. | +| Guardian review | Implemented in RSS with validated `allow`, `deny`, and `needs_user` outcomes and fail-closed malformed/unavailable handling. | +| Human approvals | Implemented with durable pending rows, HTTP and Telegram resolution, owner checks, expiry, one-time decisions, and one terminal tool result. | +| Managed workspace effects | Implemented for synchronous filesystem/process tool flows using private immutable trees, prepared receipts, durable commit/readback, conflict handling, and explicit publication. External process effects are recorded as outside-tree and are not rolled back. | +| Checkpoint, restore, branch, publish, and effect queries | Implemented behind authenticated native workspace authority and persistent state. Submitted-unknown outcomes remain fenced for reconciliation. | +| Parallel tool calls | Not implemented; rejected as `unsupported_parallel`. | +| Parallel subagents/fan-out | Not implemented and excluded from the current milestone. The interrupt compatibility route only cancels a run handle by ID. | +| General-purpose harness beyond the implemented tool approval/pinned-tool paths | Excluded from the current product claim. | + +## Plugin graphs and state + +| Area | Status | +| --- | --- | +| Plugin package install and graph resolution | Implemented for trusted host-controlled source roots, bounded manifests/schemas, immutable captures, publisher authorization, and closed graph locks. | +| Prepare, activate, inspect, and rollback routes | Implemented behind bearer verification plus host-side plugin-control authorization. A bearer alone does not grant install authority. | +| Admission graph pin | Implemented: the native admission transaction captures graph ID, activation generation, package refs, callable, registry identity, workspace, and durable ref. Caller JSON cannot mint the execution binding. | +| Hot activation | Implemented for new admissions. Existing runs retain their original graph; replay uses the original pin instead of the current activation. | +| Revocation and missing artifacts | Fail closed with typed graph/pin/artifact errors. Historical builtin captures can remain retained without becoming executable defaults. | +| Plugin state roots and migrations | Implemented for declared supported state/topology paths with revisioned roots, writer fences, checkpoints, and bounded collection. Unsupported topology/state combinations are rejected. | + +## Jobs, release, and exclusions + +| Area | Status | +| --- | --- | +| Job records | CRUD, pause/resume, and latest-output routes are implemented. | +| Scheduled/durable job execution | **Not implemented.** There is no scheduler and no `POST /api/jobs/{id}/run` route. | +| Published package/release | No release claim. The crate is `0.1.0` and depends on unreleased `pd-vm`/`pd-host-function` at pinned Core revision `11c9ee908a29365bd02573311f56e9308eb7dbe6`; deployments are source builds of pinned commits. | +| Full CI | Configured for format, clippy with warnings denied, and `cargo test --locked --all-features --all-targets` on Rust 1.99. See [Development](development.md). | + +The detailed configuration surface is canonical in [Configuration](configuration.md), operational constraints in [Deployment](deployment.md), and ownership/replay invariants in [Architecture](architecture.md). diff --git a/tests/cases/docs_consistency_tests.rs b/tests/cases/docs_consistency_tests.rs index 915a3916..1e758c21 100644 --- a/tests/cases/docs_consistency_tests.rs +++ b/tests/cases/docs_consistency_tests.rs @@ -177,7 +177,14 @@ fn every_agent_gateway_config_field_is_documented() { #[test] fn readme_links_the_canonical_docs() { let readme = read_relative("README.md"); - for target in ["docs/configuration.md", "docs/deployment.md"] { + for target in [ + "docs/api.md", + "docs/architecture.md", + "docs/configuration.md", + "docs/development.md", + "docs/deployment.md", + "docs/status.md", + ] { assert!( readme.contains(&format!("]({target})")), "README.md must link {target}" @@ -187,7 +194,15 @@ fn readme_links_the_canonical_docs() { #[test] fn relative_markdown_links_resolve() { - let files = ["README.md", "docs/configuration.md", "docs/deployment.md"]; + let files = [ + "README.md", + "docs/api.md", + "docs/architecture.md", + "docs/configuration.md", + "docs/development.md", + "docs/deployment.md", + "docs/status.md", + ]; let mut checked = 0; for file in files { let text = read_relative(file); @@ -264,11 +279,18 @@ fn inline_code_closed(line: &str) -> bool { fn inline_code_spans_in_docs_are_closed() { // An unclosed opening backtick makes the code span extend until the next // backtick in the document, rendering whole paragraphs as inline code on - // GitHub. Every inline-code span in the two docs must be paired on its + // GitHub. Every inline-code span in the canonical docs must be paired on its // line (tables and bullets are single lines); fenced code blocks and // their contents are skipped. let mut checked = 0; - for file in ["docs/configuration.md", "docs/deployment.md"] { + for file in [ + "docs/api.md", + "docs/architecture.md", + "docs/configuration.md", + "docs/development.md", + "docs/deployment.md", + "docs/status.md", + ] { let text = read_relative(file); let mut in_fence = false; for (index, line) in text.lines().enumerate() { @@ -295,13 +317,13 @@ fn inline_code_spans_in_docs_are_closed() { #[test] fn authorization_bearer_placeholder_is_a_closed_inline_code_span() { - // The `Authorization: Bearer ` placeholder must appear exactly as - // a closed inline-code span (backtick immediately before and after the - // placeholder) in both docs, matching the middleware's `Bearer ` strip + // The bearer placeholder must appear exactly as a closed inline-code span + // (backtick immediately before and after the placeholder) in all three + // docs, matching the middleware's `Bearer ` strip // plus constant-time compare. Every mention of the token in the docs // must be that closed span. let token = "Authorization: Bearer ***"; - for file in ["docs/configuration.md", "docs/deployment.md"] { + for file in ["docs/api.md", "docs/configuration.md", "docs/deployment.md"] { let text = read_relative(file); let closed_span = format!("`{token}`"); assert!( diff --git a/tests/cases/documentation_consistency_tests.rs b/tests/cases/documentation_consistency_tests.rs index b6ded6ce..a3207ed5 100644 --- a/tests/cases/documentation_consistency_tests.rs +++ b/tests/cases/documentation_consistency_tests.rs @@ -298,7 +298,7 @@ fn auth_storage_documentation_matches_secret_and_unix_file_contract() { } #[test] -fn readme_source_and_protocol_status_matches_current_rss_paths() { +fn status_source_and_protocol_matrix_matches_current_rss_paths() { let gateway = read_relative("src/bin/rustscript-agent-gateway.rs"); assert!(gateway.contains("source_env_value(\"RUSTSCRIPT_AGENT_SOURCE\"")); assert!(gateway.contains("source_env_value(\"RUSTSCRIPT_AGENT_SCRIPT\"")); @@ -323,7 +323,7 @@ fn readme_source_and_protocol_status_matches_current_rss_paths() { let anthropic = read_relative("rss/llm/anthropic_messages.rss"); assert!(anthropic.contains("\"not_implemented\"")); - let readme = read_relative("README.md"); + let status = read_relative("docs/status.md"); for required in [ "RUSTSCRIPT_AGENT_SOURCE", "RUSTSCRIPT_AGENT_SCRIPT", @@ -338,29 +338,29 @@ fn readme_source_and_protocol_status_matches_current_rss_paths() { "not_implemented", ] { assert!( - readme.contains(required), - "README.md must state the current source/protocol boundary (`{required}`)" + status.contains(required), + "docs/status.md must state the current source/protocol boundary (`{required}`)" ); } assert!( - !readme.contains("blocked by core (A3)"), - "README.md must not retain the obsolete blanket A3-blocked status" + !status.contains("blocked by core (A3)"), + "docs/status.md must not retain the obsolete blanket A3-blocked status" ); assert!( - !readme.contains("gateway binary still runs `RUSTSCRIPT_AGENT_SCRIPT`"), - "README.md must not claim the legacy script variable is authoritative" + !status.contains("gateway binary still runs `RUSTSCRIPT_AGENT_SCRIPT`"), + "docs/status.md must not claim the legacy script variable is authoritative" ); } #[test] fn legacy_chat_documentation_matches_source_selected_gateway_behavior() { - let readme = read_relative("README.md"); - let row = readme + let status = read_relative("docs/status.md"); + let row = status .lines() .find(|line| { line.starts_with("| Legacy chat completion path (`/api/sessions/{id}/chat`) |") }) - .expect("README.md must retain the legacy chat status row"); + .expect("docs/status.md must retain the legacy chat status row"); let normalized_row = row.to_ascii_lowercase(); for required in [ "legacy-constructor-only", @@ -373,12 +373,12 @@ fn legacy_chat_documentation_matches_source_selected_gateway_behavior() { ] { assert!( normalized_row.contains(required), - "README.md legacy chat row must state `{required}`" + "docs/status.md legacy chat row must state `{required}`" ); } assert!( !normalized_row.contains("runs the currently selected gateway agent source"), - "README.md must not claim source-selected production chat is available" + "docs/status.md must not claim source-selected production chat is available" ); let gateway = read_relative("src/gateway/mod.rs"); @@ -430,11 +430,11 @@ fn legacy_chat_documentation_matches_source_selected_gateway_behavior() { } #[test] -fn readme_distinguishes_config_bridge_from_composed_package_acceptance() { +fn status_distinguishes_config_bridge_from_composed_package_acceptance() { let auth_host = read_relative("src/auth/host.rs"); assert!(auth_host.contains("\"config::load_snapshot\"")); - let readme = read_relative("README.md"); - let normalized_readme = readme.split_whitespace().collect::>().join(" "); + let status = read_relative("docs/status.md"); + let normalized_status = status.split_whitespace().collect::>().join(" "); for required in [ "config::load_snapshot", "Package-level end-to-end config/auth/provider acceptance", @@ -442,8 +442,8 @@ fn readme_distinguishes_config_bridge_from_composed_package_acceptance() { "remote delivery remain open", ] { assert!( - normalized_readme.contains(required), - "README.md must separate the current bridge from later acceptance (`{required}`)" + normalized_status.contains(required), + "docs/status.md must separate the current bridge from later acceptance (`{required}`)" ); } }