# Documentation for agents URL: https://docs.mars.glass/agents Markdown: https://docs.mars.glass/agents.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Choose narrow context, verified contracts, and read-only documentation tools. ## Discovery formats [#discovery-formats] * `/llms.txt`: canonical page index with descriptions. * `/llms-full.txt`: complete generated documentation text. * Per-page `.md` URLs: narrow, copyable Markdown context. * `/skill.md`: practical documentation-use instructions. * `/openapi.json`: the exact registry HTTP contract. * `/coverage.json`: source inventory, artifact hashes, and coverage boundaries. * `/api/mcp`: read-only documentation discovery, search, and retrieval. The documentation MCP server does not publish entries, execute arbitrary URLs, access credentials, or administer registries. Use the registry API only with the user's actual authorization and operator-provided configuration. ## Work from authority [#work-from-authority] Select the relevant guide, inspect its linked contract, and verify feature status. Prefer schema and source-derived reference over legacy claims. Treat `draft` sharding and `gated` anchoring pages as explicit boundaries. Crate and wire versions are separate. ## Avoid false success [#avoid-false-success] Do not invent a public registry URL, CLI binary, token, signature, chain receipt, benchmark, or ceremony result. Preserve uncertainty after timeouts and partial federation responses. A valid docs build does not certify a backend deployment or cryptographic implementation. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `docs/api/openapi.v1.json` * `mars-server/src/contracts.rs` * `mars-server/src/auth/principal.rs` # MARS documentation URL: https://docs.mars.glass/ Markdown: https://docs.mars.glass/index.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Discover, publish, and verify agent registry records. MARS is the Multi-Agentic Registry Service: a signed registry for agents, tools, skills, workflows, models, datasets, services, organizations, identity roots, and MAP plugins. ## Start with a real registry [#start-with-a-real-registry] * [Query your first entries](/protocol/quickstart): a read-only HTTP workflow. * [Understand the entry contract](/protocol/entry-format): 14 entry types, canonical hashes, and publisher signatures. * [Publish an entry](/protocol/publishing): identity, authorization, signing, and idempotency. * [Operate a registry](/operators/production): PostgreSQL, trust configuration, readiness, and recovery. ## Find the contract [#find-the-contract] [HTTP reference](/api-reference) covers every operation in the checked-in OpenAPI contract. [Artifacts](/reference/artifacts) provides the exact OpenAPI file, 64 JSON schemas, and publisher-signing vectors. [Rust libraries](/libraries) maps all three workspace crates and their public modules. ## Read with an agent [#read-with-an-agent] Use [llms.txt](/llms.txt) to select pages, [llms-full.txt](/llms-full.txt) for the complete corpus, or [the agent guide](/agents) for Markdown exports, skill instructions, and the read-only documentation MCP endpoint. Protocol wire version **1.0.0** and Rust workspace version **0.1.0** are different version axes. Current reference storage is PostgreSQL. MARS-S sharding is a prototype, and Sigil anchoring has a separate governed activation boundary. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `Cargo.toml` * `mars-protocol/src/lib.rs` * `docs/adr/0001-production-registry-and-contract-authority.md` # Attestation and report APIs URL: https://docs.mars.glass/api/attestations Markdown: https://docs.mars.glass/api/attestations.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Read signed evidence and submit authorized claims. ## Endpoints [#endpoints] [Read attestations](/api-reference/get_attestations), [create an attestation](/api-reference/create_attestation), and [report an entry](/api-reference/create_report) use separate contracts. Protected submissions require capability and idempotency. ## Verify evidence [#verify-evidence] Inspect issuer, subject, signed content, temporal bounds, and revocation. Counts do not establish independent issuers. Reports describe an allegation and must not be represented as an adjudicated outcome. See [attestation concepts](/protocol/attestations) for the trust boundary. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` # Discovery endpoints URL: https://docs.mars.glass/api/discover Markdown: https://docs.mars.glass/api/discover.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Structured, MARS-QL, and bounded federated discovery. ## Local discovery [#local-discovery] [Structured discovery](/api-reference/discover) accepts a canonical `entryType`, AND-combined conditions, bounded limit, and optional cursor. [MARS-QL discovery](/api-reference/discover_marsql) accepts a query string. Both return complete records. ## Federated discovery [#federated-discovery] [Client federated discovery](/api-reference/discover_federated) requires an authenticated principal with `federated_discovery`. The separate signed peer discovery route verifies a federation envelope. Do not confuse the two authentication modes. ## Result completeness [#result-completeness] Inspect federation metadata for partial or failed peers. An individual page is bounded; follow valid query-bound cursors to continue. A discovery result is not a verification endorsement. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` # Entries and versions URL: https://docs.mars.glass/api/entries Markdown: https://docs.mars.glass/api/entries.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Read complete records and perform signed lifecycle mutations. Public routes resolve current entries, enumerate versions, and retrieve historical records. Mutation routes create, update, and revoke entries; each has an exact generated contract. ## Reads [#reads] * [Resolve an entry](/api-reference/get_entry) * [List versions](/api-reference/list_entry_versions) * [Read a version](/api-reference/get_entry_version) URL-encode the full DID and version separately. Do not concatenate raw user input into paths. ## Mutations [#mutations] [Create](/api-reference/create_entry), [update](/api-reference/update_entry), and [revoke](/api-reference/delete_entry) require their respective scoped capability and idempotency key. Create/update also require a valid publisher signature; see [publishing](/protocol/publishing). Revocation does not erase immutable history. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` # Errors and retry behavior URL: https://docs.mars.glass/api/errors Markdown: https://docs.mars.glass/api/errors.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Treat contract failures, authorization, and uncertain delivery separately. The [OpenAPI operation pages](/api-reference) include response statuses and `ErrorResponse`. Preserve the server's machine-readable error and message; do not convert every failure into an empty result. ## Client handling [#client-handling] | Failure class | Client response | | --------------------------- | ---------------------------------------------------------------------------------- | | Invalid payload or query | Correct the contract violation before retrying. | | Missing/expired session | Re-authenticate; do not reuse an invalid token indefinitely. | | Missing capability or trust | Request appropriate operator provisioning; signing again does not grant authority. | | Idempotency conflict | Inspect the original request; never mutate payload under the same key. | | Stale transfer or cursor | Read current state and begin a new deliberate operation/query. | | Uncertain network delivery | Retry the identical mutation with its original idempotency key. | Avoid retry storms. Use bounded backoff where a retry is appropriate and respect server limits. A rejected protected mutation is not a successful registry write. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` # WebSocket events URL: https://docs.mars.glass/api/events Markdown: https://docs.mars.glass/api/events.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Real subscription behavior and its current limitations. Connect to `/v1/ws` with the registry's WebSocket origin. The wire contract uses `SubscriptionMessage` and `MarsEvent`. ```json { "action": "subscribe", "filters": { "entryTypes": ["AgentDefinition"], "events": ["entry.created", "entry.updated"] } } ``` ## Event kinds [#event-kinds] `entry.created`, `entry.updated`, `entry.revoked`, `entry.transferred`, `entry.attested`, `entry.reported`, `bond.slashed`, and `federation.sync` are the eight declared event types. A declared type does not prove an external economic or chain action occurred. ## Current limitations [#current-limitations] Nonempty entry type, event type, and DID filters combine with AND. Empty filters match everything. The namespace field is accepted but is not currently enforced by the server filter. Sending `unsubscribe` clears filters, which makes subsequent events match all; **close the socket to stop delivery**. The server tracks a durable event ID internally but exposes no resumable client cursor. On reconnect, reconcile current registry state and deduplicate by event ID; do not promise exactly-once client delivery. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` * `mars-server/src/api/websocket.rs` * `mars-protocol/src/events.rs` # Federation API URL: https://docs.mars.glass/api/federation Markdown: https://docs.mars.glass/api/federation.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Signed peer traffic and operator control. ## Peer protocol [#peer-protocol] [Sync](/api-reference/federation_sync) and [peer discovery](/api-reference/federation_discover) accept signed federation envelopes. Peers must be selected and pinned by the operator. Message kind, recipient, nonce, lifetime, agreements, and scopes are validated. ## Registry discovery and administration [#registry-discovery-and-administration] [Peer listings](/api-reference/list_federation_peers) and [the registries alias](/api-reference/list_registries_alias) expose discovery information. [Update self](/api-reference/update_federation_peer) is protected. [Peer status](/api-reference/federation_peer_status) requires admin capability. ## Disabled by default [#disabled-by-default] Do not point a client at arbitrary peer URLs or assume federation is enabled. See [operator configuration](/operators/federation). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` # Lineage endpoint URL: https://docs.mars.glass/api/lineage Markdown: https://docs.mars.glass/api/lineage.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Retrieve lineage associated with a registered entry. Use [GET entry lineage](/api-reference/get_entry_lineage) after resolving the entry. The generated `EntryLineageResponse` schema describes the return shape. ## Interpretation [#interpretation] The entry may omit lineage. Returned records still need identity and signature verification. Do not treat chain length or root presence as a current authorization grant. ## Related query [#related-query] [Lineage filters](/marsql/lineage-traversal) select stored root and generation metadata. They do not provide recursive SQL traversal. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` # HTTP API overview URL: https://docs.mars.glass/api/overview Markdown: https://docs.mars.glass/api/overview.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json 35 operations generated from the canonical OpenAPI contract. ## Complete contract [#complete-contract] The [generated API reference](/api-reference) documents all 35 operations in the checked-in `openapi.v1.json`. Request bodies, parameters, response schemas, security schemes, and error statuses come directly from that artifact. Download [OpenAPI](/openapi.json) for client generation. The explorer is read-only: no public registry endpoint is assumed and request execution is disabled. Configure your own generated client with an operator-supplied registry URL. ## Authentication boundaries [#authentication-boundaries] Public registry reads and local discovery require no session. Protected registry mutations require a scoped MARS capability and `Idempotency-Key`. SIWS challenges/verification bootstrap a session; signed federation endpoints authenticate peer envelopes. Deep health and peer diagnostics require operator capability. ## Client conventions [#client-conventions] Use JSON content types, URL-encode DIDs as path segments, retain exact schema field casing, apply request timeouts, and distinguish an empty result from a transport or server error. Do not log bearer tokens or signing secrets. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` Session logout is an authentication operation, not a registry mutation: its contract does not require an Idempotency-Key. Follow each generated operation definition. # Rust libraries URL: https://docs.mars.glass/libraries Markdown: https://docs.mars.glass/libraries.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json All three workspace crates and their public module boundaries. ## Library map [#library-map] * [mars-protocol](/libraries/mars-protocol): Wire contracts, publisher signing, hashing, lifecycle, query AST, federation, and event types. * [mars-server](/libraries/mars-server): Registry HTTP server, authorization, durable storage, query planning, federation, and anchor outbox. * [mars-shard](/libraries/mars-shard): MARS-S prototype affinity, topology, shadow copies, resolution, and cross-shard coordination. These pages document source contracts and status. They do not certify package registry availability, a backend deployment, or a test run. The [coverage manifest](/coverage.json) records exact source hashes and module coverage. # Inspect anchor intents URL: https://docs.mars.glass/cli/anchor Markdown: https://docs.mars.glass/cli/anchor.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Current tools and HTTP workflows; no fictional client CLI. This URL is preserved from the earlier CLI guide. The current workspace does not ship a general `mars` client executable. ## Supported workflow [#supported-workflow] Read anchor status through the generated HTTP contract. Only an authorized operator should retry or abandon durable intents. Local state does not prove external finality. [Open the complete guide](/operators/anchoring). ## Verification boundary [#verification-boundary] Run only against a registry/database you are authorized to access. The documentation app is not a registry and its MCP endpoint serves documentation only. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/Cargo.toml` * `mars-server/src/api/mod.rs` # Discover with HTTP URL: https://docs.mars.glass/cli/discover Markdown: https://docs.mars.glass/cli/discover.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Current tools and HTTP workflows; no fictional client CLI. This URL is preserved from the earlier CLI guide. The current workspace does not ship a general `mars` client executable. ## Supported workflow [#supported-workflow] Start with the complete Python quickstart. Local discovery is public and returns bounded complete records. Empty results and transport failures are distinct outcomes. [Open the complete guide](/protocol/quickstart). ## Verification boundary [#verification-boundary] Run only against a registry/database you are authorized to access. The documentation app is not a registry and its MCP endpoint serves documentation only. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/Cargo.toml` * `mars-server/src/api/mod.rs` # Federation operations URL: https://docs.mars.glass/cli/federate Markdown: https://docs.mars.glass/cli/federate.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Current tools and HTTP workflows; no fictional client CLI. This URL is preserved from the earlier CLI guide. The current workspace does not ship a general `mars` client executable. ## Supported workflow [#supported-workflow] Operators configure selected peers, pins, agreements, and signing. A client cannot enable safe federation by issuing an invented `mars federate` command. Signed peer envelopes and session-authenticated client discovery are different protocols. [Open the complete guide](/operators/federation). ## Verification boundary [#verification-boundary] Run only against a registry/database you are authorized to access. The documentation app is not a registry and its MCP endpoint serves documentation only. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/Cargo.toml` * `mars-server/src/api/mod.rs` # Run a MARS-QL query URL: https://docs.mars.glass/cli/marsql Markdown: https://docs.mars.glass/cli/marsql.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Current tools and HTTP workflows; no fictional client CLI. This URL is preserved from the earlier CLI guide. The current workspace does not ship a general `mars` client executable. ## Supported workflow [#supported-workflow] POST a JSON object with a `query` string to `/v1/discover/marsql`. Use a canonical entry type, bounded limit, supported fields, and a returned opaque cursor when continuing results. [Open the complete guide](/marsql/overview). ## Verification boundary [#verification-boundary] Run only against a registry/database you are authorized to access. The documentation app is not a registry and its MCP endpoint serves documentation only. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/Cargo.toml` * `mars-server/src/api/mod.rs` # Server and operator tools URL: https://docs.mars.glass/cli/overview Markdown: https://docs.mars.glass/cli/overview.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json The three binaries actually provided by the MARS workspace. There is no general `mars` client CLI in this release. The preserved CLI documentation routes now describe HTTP workflows and the three actual workspace binaries. | Binary | Purpose | Feature requirement | | ---------------- | --------------------------------------------------------- | ----------------------------------------------------------------- | | `mars-server` | Run the HTTP/WebSocket registry and metrics listener | Default features include `postgres,sigil`; production adds `prod` | | `mars-contracts` | Generate or check canonical JSON Schema/OpenAPI artifacts | `contracts` | | `mars-ledger` | Verify private-audit and public-event ledger chains | `postgres` | ## Commands [#commands] ```bash mars-server --help mars-contracts check mars-ledger verify ``` `mars-contracts generate` rewrites canonical repository artifacts. Use `check` for drift verification. `mars-ledger` reads the database selected by `DATABASE_URL` or `--database-url`. See [server configuration](/operators/production) and [recovery](/operators/recovery). For discovery, resolution, events, and publication, use HTTP/WebSocket clients against an operator-supplied registry URL. No Homebrew package or public hosted endpoint is implied. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/Cargo.toml` * `mars-server/src/main.rs` * `mars-server/src/bin/mars-contracts.rs` * `mars-server/src/bin/mars-ledger.rs` # Resolve with HTTP URL: https://docs.mars.glass/cli/resolve Markdown: https://docs.mars.glass/cli/resolve.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Current tools and HTTP workflows; no fictional client CLI. This URL is preserved from the earlier CLI guide. The current workspace does not ship a general `mars` client executable. ## Supported workflow [#supported-workflow] URL-encode the complete DID as one path segment. Retrieve versions and lineage through their dedicated routes. Inspect lifecycle and signature evidence before trusting a resolved record. [Open the complete guide](/api-reference/get_entry). ## Verification boundary [#verification-boundary] Run only against a registry/database you are authorized to access. The documentation app is not a registry and its MCP endpoint serves documentation only. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/Cargo.toml` * `mars-server/src/api/mod.rs` # Subscribe over WebSocket URL: https://docs.mars.glass/cli/subscribe Markdown: https://docs.mars.glass/cli/subscribe.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Current tools and HTTP workflows; no fictional client CLI. This URL is preserved from the earlier CLI guide. The current workspace does not ship a general `mars` client executable. ## Supported workflow [#supported-workflow] Connect to `/v1/ws` and send a `SubscriptionMessage`. Close the socket to stop delivery: the current unsubscribe behavior clears filters and therefore matches all subsequent events. There is no exposed resumable client cursor. [Open the complete guide](/api/events). ## Verification boundary [#verification-boundary] Run only against a registry/database you are authorized to access. The documentation app is not a registry and its MCP endpoint serves documentation only. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/Cargo.toml` * `mars-server/src/api/mod.rs` # Verify contracts and ledgers URL: https://docs.mars.glass/cli/verify Markdown: https://docs.mars.glass/cli/verify.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Current tools and HTTP workflows; no fictional client CLI. This URL is preserved from the earlier CLI guide. The current workspace does not ship a general `mars` client executable. ## Supported workflow [#supported-workflow] Use `mars-contracts check` for generated artifact drift and `mars-ledger verify` for database chain verification. Publisher signature verification is a separate protocol-library operation using the controlled public key and canonical signing bytes. [Open the complete guide](/operators/recovery). ## Verification boundary [#verification-boundary] Run only against a registry/database you are authorized to access. The documentation app is not a registry and its MCP endpoint serves documentation only. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/Cargo.toml` * `mars-server/src/api/mod.rs` # Attestation filters URL: https://docs.mars.glass/marsql/attestation-joins Markdown: https://docs.mars.glass/marsql/attestation-joins.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Filter attestation counts without inventing joins or trust scores. ## Count filter [#count-filter] ```sql DISCOVER AgentDefinition WHERE attestation_count >= 1 LIMIT 20 ``` `attestation_count` counts attached records. It does not deduplicate issuers or measure credibility. Retrieve and verify individual attestations before making a trust decision. ## No SQL join [#no-sql-join] This preserved legacy URL describes filtering, not an implemented join operator. MARS-QL has no `JOIN`, aggregation, or multi-table SQL interface. Use `GET /v1/attestations/{did}` for the attestation collection associated with a selected entry. ## Evidence checks [#evidence-checks] Check issuer authorization, subject, signed content, expiry, and revocation. A useful application can maintain its own policy evaluation; the registry count alone is insufficient. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/search.rs` * `mars-protocol/src/marsql/parser.rs` * `mars-protocol/src/api.rs` # Query cookbook URL: https://docs.mars.glass/marsql/cookbook Markdown: https://docs.mars.glass/marsql/cookbook.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Practical bounded queries using implemented operators. ## Browse all types [#browse-all-types] ```sql DISCOVER * ORDER BY name ASC LIMIT 10 ``` ## Find a tagged agent [#find-a-tagged-agent] ```sql DISCOVER AgentDefinition WHERE tags CONTAINS "research" LIMIT 20 ``` ## Require several tags [#require-several-tags] ```sql DISCOVER ToolDefinition WHERE tags CONTAINS_ALL ("http", "read-only") LIMIT 10 ``` ## Inspect first-generation records [#inspect-first-generation-records] ```sql DISCOVER AgentDefinition WHERE lineage_reference.generation = 1 LIMIT 20 ``` ## Continue a result page [#continue-a-result-page] Append `OFFSET` with the exact quoted cursor returned for the same query, ordering, and limit. Cursors are opaque and expire. Restart from the first page if the server rejects a cursor rather than guessing a numeric offset. Each query selects recorded attributes. Verify signatures, endpoints, and claims independently before execution. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-protocol/src/marsql/parser.rs` * `mars-server/src/search.rs` # Grammar and supported fields URL: https://docs.mars.glass/marsql/grammar Markdown: https://docs.mars.glass/marsql/grammar.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Syntax implemented by the checked-in parser and query planner. ## Query grammar [#query-grammar] ```text query = "DISCOVER" entry_type [ "WHERE" conditions ] [ "ORDER BY" ordering ] [ "LIMIT" integer ] [ "OFFSET" cursor ] ; conditions = condition { "AND" condition } ; ``` Use exact canonical [entry type names](/protocol/entry-format). Strings are double-quoted; numbers and booleans are typed literals. Conditions support `=`, `!=`, `>`, `>=`, `<`, `<=`, `CONTAINS`, `CONTAINS_ALL`, `CONTAINS_ANY`, and `IN`. Membership lists use parentheses. ```sql DISCOVER * WHERE tags CONTAINS_ANY ("research", "tools") ORDER BY name ASC LIMIT 10 ``` ## Field validation [#field-validation] The parser can recognize a dotted field path without the server accepting it. `search::validate_field_path` defines supported canonical and payload paths; the [search source reference](/libraries/mars-server/search) is the exact authority. Arbitrary SQL and database column expressions are rejected. ## Unsupported language [#unsupported-language] There are no joins, CTEs, grouping, aggregation, or `OR`. Shard/region/cluster extensions belong to the feature-gated prototype parser and must not be assumed on a normal server. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-protocol/src/marsql/parser.rs` * `mars-protocol/src/marsql/ast.rs` * `mars-server/src/search.rs` # Lineage filters URL: https://docs.mars.glass/marsql/lineage-traversal Markdown: https://docs.mars.glass/marsql/lineage-traversal.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Filter recorded lineage, then resolve the evidence explicitly. ## Filter a generation [#filter-a-generation] ```sql DISCOVER AgentDefinition WHERE lineage_reference.generation = 1 LIMIT 20 ``` The query filters complete records by their stored lineage metadata. `lineage_reference.human_root_did` selects the recorded root DID. A missing optional lineage reference is not fabricated by the query engine. ## Resolve the chain [#resolve-the-chain] For a selected entry, call `GET /v1/entries/{did}/lineage` using a URL-encoded DID. Inspect the returned chain and verify the relevant identity evidence. This is a separate operation from discovery. ## Boundaries [#boundaries] Despite this legacy route's name, MARS-QL does not run recursive traversal or SQL joins. Generation and root metadata can narrow candidates; they do not prove current delegation authority or a verified human ceremony. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/search.rs` * `mars-protocol/src/entry.rs` * `mars-server/src/api/rest.rs` # MARS-QL URL: https://docs.mars.glass/marsql/overview Markdown: https://docs.mars.glass/marsql/overview.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json A bounded query language over complete registry records. MARS-QL queries begin with `DISCOVER`, followed by a canonical entry type or `*`. ```sql DISCOVER AgentDefinition WHERE tags CONTAINS "research" LIMIT 20 ``` Send the string as `{ "query": "..." }` to `POST /v1/discover/marsql`. The response contains complete matching entries and pagination metadata. `POST /v1/discover` is the structured JSON alternative. ## Supported operations [#supported-operations] Conditions combine with `AND`. Comparison operators, membership operations, allowlisted field paths, ordering, bounded limits, and opaque keyset cursors are supported. SQL joins, `OR`, aggregation, and CTEs are not part of the language. ## Pagination [#pagination] `OFFSET` means an opaque, expiring HMAC-authenticated cursor; it is not a numeric row offset. Reuse the server's returned cursor with the same query and sort. Treat expiry or query mismatch as a restart of the query. Do not manufacture or edit cursor contents. ## Limits [#limits] The protocol caps query text at 8192 bytes, conditions at 32, and dotted field depth at 16. Server planning validates types, fields, limits, and cursor scope before accessing the store. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-protocol/src/marsql/parser.rs` * `mars-protocol/src/marsql/ast.rs` * `mars-server/src/search.rs` # Abandon anchor URL: https://docs.mars.glass/api-reference/abandon_anchor Markdown: https://docs.mars.glass/api-reference/abandon_anchor.md Status: gated Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `abandon_anchor` · **HTTP:** `POST /v1/admin/anchors/{intent_id}/abandon` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. External anchor activation is gated. Local status or intent mutation does not prove a finalized Sigil transaction. Exact operation definition ```json { "operationId": "abandon_anchor", "parameters": [ { "description": "Durable anchor intent identifier", "in": "path", "name": "intent_id", "required": true, "schema": { "type": "string" } }, { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AnchorControlResponse" } } }, "description": "Intent abandoned" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Admin capability missing" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Intent not found" }, "409": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Intent state or idempotency conflict" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "trust" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Accept transfer offer URL: https://docs.mars.glass/api-reference/accept_transfer_offer Markdown: https://docs.mars.glass/api-reference/accept_transfer_offer.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `accept_transfer_offer` · **HTTP:** `POST /v1/transfers/offers/{offer_id}/accept` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "accept_transfer_offer", "parameters": [ { "description": "Transfer offer identifier", "in": "path", "name": "offer_id", "required": true, "schema": { "type": "string" } }, { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TransferAcceptRequest" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsEntry" } } }, "description": "Recipient-signed transferred entry" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Recipient or capability mismatch" }, "409": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Offer expired or entry changed" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Create attestation URL: https://docs.mars.glass/api-reference/create_attestation Markdown: https://docs.mars.glass/api-reference/create_attestation.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Verifies and separately stores a canonical OAS Verifiable Credential. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `create_attestation` · **HTTP:** `POST /v1/attestations` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "description": "Verifies and separately stores a canonical OAS Verifiable Credential.", "operationId": "create_attestation", "parameters": [ { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AttestationRequest" } } }, "required": true }, "responses": { "201": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/VerifiableAttestationRecord" } } }, "description": "Stored verified attestation" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Issuer or capability mismatch" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Write rate limit exceeded" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "trust" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Create entry URL: https://docs.mars.glass/api-reference/create_entry Markdown: https://docs.mars.glass/api-reference/create_entry.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `create_entry` · **HTTP:** `POST /v1/entries` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "create_entry", "parameters": [ { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsEntry" } } }, "required": true }, "responses": { "201": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsEntry" } } }, "description": "Entry created" }, "400": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry validation failed" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "SIWS session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session publisher mismatch" }, "409": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry already exists" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Write rate limit exceeded" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Create report URL: https://docs.mars.glass/api-reference/create_report Markdown: https://docs.mars.glass/api-reference/create_report.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Records a report whose reporter is derived from Principal. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `create_report` · **HTTP:** `POST /v1/report` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "description": "Records a report whose reporter is derived from Principal.", "operationId": "create_report", "parameters": [ { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ReportRequest" } } }, "required": true }, "responses": { "201": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ReportResponse" } } }, "description": "Report accepted" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Report capability missing" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Write rate limit exceeded" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "trust" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Decline transfer offer URL: https://docs.mars.glass/api-reference/decline_transfer_offer Markdown: https://docs.mars.glass/api-reference/decline_transfer_offer.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `decline_transfer_offer` · **HTTP:** `POST /v1/transfers/offers/{offer_id}/decline` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "decline_transfer_offer", "parameters": [ { "description": "Transfer offer identifier", "in": "path", "name": "offer_id", "required": true, "schema": { "type": "string" } }, { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TransferDeclineRequest" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TransferOffer" } } }, "description": "Declined transfer offer" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Recipient or capability mismatch" }, "409": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Offer expired or already decided" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Deep health URL: https://docs.mars.glass/api-reference/deep_health Markdown: https://docs.mars.glass/api-reference/deep_health.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `deep_health` · **HTTP:** `GET /v1/health/deep` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "deep_health", "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/DeepHealthResponse" } } }, "description": "Operator subsystem health; inspect the body status" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Operator session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Admin capability required" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "operations" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Delete entry URL: https://docs.mars.glass/api-reference/delete_entry Markdown: https://docs.mars.glass/api-reference/delete_entry.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `delete_entry` · **HTTP:** `DELETE /v1/entries/{did}` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "delete_entry", "parameters": [ { "description": "OAS DID of the entry", "in": "path", "name": "did", "required": true, "schema": { "type": "string" } }, { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "responses": { "204": { "description": "Entry revoked" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "SIWS session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session publisher mismatch" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Write rate limit exceeded" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Discover URL: https://docs.mars.glass/api-reference/discover Markdown: https://docs.mars.glass/api-reference/discover.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `discover` · **HTTP:** `POST /v1/discover` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "discover", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/DiscoverRequest" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsQueryResult" } } }, "description": "Discovery results" }, "400": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Invalid discovery request" }, "413": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Query body exceeds the explicit admission limit" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Query rate limit exceeded" } }, "tags": [ "discovery" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Discover federated URL: https://docs.mars.glass/api-reference/discover_federated Markdown: https://docs.mars.glass/api-reference/discover_federated.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `discover_federated` · **HTTP:** `POST /v1/discover/federated` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "discover_federated", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsQuery" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/FederatedDiscoveryResult" } } }, "description": "Deterministically merged local and signed peer results with bounded partial metadata" }, "400": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Invalid query or federated cursor" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Federated discovery capability required" }, "413": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Query body exceeds the explicit admission limit" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Query rate limit exceeded" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "discovery" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Discover marsql URL: https://docs.mars.glass/api-reference/discover_marsql Markdown: https://docs.mars.glass/api-reference/discover_marsql.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `discover_marsql` · **HTTP:** `POST /v1/discover/marsql` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "discover_marsql", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsQlRequest" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsQueryResult" } } }, "description": "MARS-QL DISCOVER results" }, "400": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Invalid MARS-QL DISCOVER expression" }, "413": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Query body exceeds the explicit admission limit" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Query rate limit exceeded" } }, "tags": [ "discovery" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Federation discover URL: https://docs.mars.glass/api-reference/federation_discover Markdown: https://docs.mars.glass/api-reference/federation_discover.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Serves a typed MARS-QL query only after signed-envelope verification, replay protection, and active agreement authorization. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `federation_discover` · **HTTP:** `POST /v1/federation/discover` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. This endpoint authenticates a signed federation envelope against configured peers and keys. It is not an unsigned public mutation merely because the OpenAPI bearer security list is absent. Exact operation definition ```json { "description": "Serves a typed MARS-QL query only after signed-envelope verification, replay protection, and active agreement authorization.", "operationId": "federation_discover", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SignedFederationEnvelope_FederatedDiscoveryRequest" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SignedFederationEnvelope_FederatedDiscoveryResponse" } } }, "description": "Signed peer discovery response" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Envelope signature, timestamp, nonce, or controller invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Peer or agreement not authorized" }, "413": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Signed federation body exceeds the explicit admission limit" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Federation rate limit exceeded" } }, "tags": [ "federation" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Federation peer status URL: https://docs.mars.glass/api-reference/federation_peer_status Markdown: https://docs.mars.glass/api-reference/federation_peer_status.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `federation_peer_status` · **HTTP:** `GET /v1/admin/federation/peers` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "federation_peer_status", "responses": { "200": { "content": { "application/json": { "schema": { "items": { "$ref": "#/components/schemas/FederationPeerStatus" }, "type": "array" } } }, "description": "Protected durable peer cursor, breaker, lag, and quarantine status" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Operator session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Admin capability required" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "federation" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Federation sync URL: https://docs.mars.glass/api-reference/federation_sync Markdown: https://docs.mars.glass/api-reference/federation_sync.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Returns local changes only after OAS service identity, JCS Ed25519 envelope, durable nonce, and active agreement verification. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `federation_sync` · **HTTP:** `POST /v1/federation/sync` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. This endpoint authenticates a signed federation envelope against configured peers and keys. It is not an unsigned public mutation merely because the OpenAPI bearer security list is absent. Exact operation definition ```json { "description": "Returns local changes only after OAS service identity, JCS Ed25519 envelope, durable nonce, and active agreement verification.", "operationId": "federation_sync", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SignedFederationEnvelope_SyncRequest" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SignedFederationEnvelope_SyncResponse" } } }, "description": "Signed federation synchronization batch" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Envelope signature, timestamp, nonce, or controller invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Unknown peer, agreement, or capability" }, "413": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Signed federation body exceeds the explicit admission limit" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Write rate limit exceeded" } }, "tags": [ "federation" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Get anchors URL: https://docs.mars.glass/api-reference/get_anchors Markdown: https://docs.mars.glass/api-reference/get_anchors.md Status: gated Source: MARS source inventory at https://docs.mars.glass/coverage.json Returns a stable keyset page of durable provider-neutral anchor intents, immutable receipts, and the current registry projection. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `get_anchors` · **HTTP:** `GET /v1/anchors/{did}` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. External anchor activation is gated. Local status or intent mutation does not prove a finalized Sigil transaction. Exact operation definition ```json { "description": "Returns a stable keyset page of durable provider-neutral anchor intents, immutable receipts, and the current registry projection.", "operationId": "get_anchors", "parameters": [ { "description": "OAS DID of the entry", "in": "path", "name": "did", "required": true, "schema": { "type": "string" } }, { "description": "Maximum number of anchor records to return. The server clamps this to\nits configured maximum page size.", "in": "query", "name": "limit", "required": false, "schema": { "format": "int64", "minimum": 1, "type": "integer" } }, { "description": "Opaque URL-safe cursor returned by the preceding page.\n\nThe cursor identifies the last-seen `(sequence, createdAt, intentId)`\ntuple. Clients must echo it unchanged and must not construct cursors.", "in": "query", "name": "cursor", "required": false, "schema": { "maxLength": 2048, "minLength": 1, "pattern": "^[A-Za-z0-9_-]+$", "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AnchorListResponse" } } }, "description": "Persisted anchor status in ascending sequence, creation-time, and intent-ID order" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "tags": [ "trust" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Get attestations URL: https://docs.mars.glass/api-reference/get_attestations Markdown: https://docs.mars.glass/api-reference/get_attestations.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `get_attestations` · **HTTP:** `GET /v1/attestations/{did}` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "get_attestations", "parameters": [ { "description": "OAS DID of the entry", "in": "path", "name": "did", "required": true, "schema": { "type": "string" } }, { "description": "Include credentials whose expiration date has passed.", "in": "query", "name": "includeExpired", "required": false, "schema": { "type": "boolean" } }, { "description": "Include credentials revoked in the local registry.", "in": "query", "name": "includeRevoked", "required": false, "schema": { "type": "boolean" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "items": { "$ref": "#/components/schemas/VerifiableAttestationRecord" }, "type": "array" } } }, "description": "Verified attestations; expired and revoked omitted by default" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "tags": [ "trust" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Get bond URL: https://docs.mars.glass/api-reference/get_bond Markdown: https://docs.mars.glass/api-reference/get_bond.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `get_bond` · **HTTP:** `GET /v1/bonds/{bond_id}` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "get_bond", "parameters": [ { "description": "Bond identifier", "in": "path", "name": "bond_id", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Bond" } } }, "description": "Bond record" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Bond not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "tags": [ "trust" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Get entry URL: https://docs.mars.glass/api-reference/get_entry Markdown: https://docs.mars.glass/api-reference/get_entry.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `get_entry` · **HTTP:** `GET /v1/entries/{did}` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "get_entry", "parameters": [ { "description": "OAS DID of the entry", "in": "path", "name": "did", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsEntry" } } }, "description": "Latest entry" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Get entry lineage URL: https://docs.mars.glass/api-reference/get_entry_lineage Markdown: https://docs.mars.glass/api-reference/get_entry_lineage.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `get_entry_lineage` · **HTTP:** `GET /v1/entries/{did}/lineage` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "get_entry_lineage", "parameters": [ { "description": "OAS DID of the entry", "in": "path", "name": "did", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/EntryLineageResponse" } } }, "description": "Canonical lineage summary; lineage is null when absent" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Get entry version URL: https://docs.mars.glass/api-reference/get_entry_version Markdown: https://docs.mars.glass/api-reference/get_entry_version.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `get_entry_version` · **HTTP:** `GET /v1/entries/{did}/versions/{version}` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "get_entry_version", "parameters": [ { "description": "OAS DID of the entry", "in": "path", "name": "did", "required": true, "schema": { "type": "string" } }, { "description": "Semantic version", "in": "path", "name": "version", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsEntry" } } }, "description": "Specific entry version" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry version not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Get transfer offer URL: https://docs.mars.glass/api-reference/get_transfer_offer Markdown: https://docs.mars.glass/api-reference/get_transfer_offer.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `get_transfer_offer` · **HTTP:** `GET /v1/transfers/offers/{offer_id}` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "get_transfer_offer", "parameters": [ { "description": "Transfer offer identifier", "in": "path", "name": "offer_id", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TransferOffer" } } }, "description": "Transfer offer" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Offer not found" } }, "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Health URL: https://docs.mars.glass/api-reference/health Markdown: https://docs.mars.glass/api-reference/health.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `health` · **HTTP:** `GET /v1/health` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "health", "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HealthResponse" } } }, "description": "Shallow service health" } }, "tags": [ "operations" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # API reference URL: https://docs.mars.glass/api-reference Markdown: https://docs.mars.glass/api-reference.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json All 35 operations from the canonical MARS v1 OpenAPI document. The explorer includes request parameters, expandable schemas, response definitions, and client code examples. Configure an operator-supplied registry endpoint in your own client. Playground execution is disabled; this documentation server is not a registry. ## Operations [#operations] | Operation | Method and path | | ----------------------------------------------------------------- | ---------------------------------------------- | | [abandon\_anchor](/api-reference/abandon_anchor) | `POST /v1/admin/anchors/{intent_id}/abandon` | | [retry\_anchor](/api-reference/retry_anchor) | `POST /v1/admin/anchors/{intent_id}/retry` | | [provision\_bond](/api-reference/provision_bond) | `POST /v1/admin/bonds` | | [federation\_peer\_status](/api-reference/federation_peer_status) | `GET /v1/admin/federation/peers` | | [get\_anchors](/api-reference/get_anchors) | `GET /v1/anchors/{did}` | | [create\_attestation](/api-reference/create_attestation) | `POST /v1/attestations` | | [get\_attestations](/api-reference/get_attestations) | `GET /v1/attestations/{did}` | | [logout](/api-reference/logout) | `POST /v1/auth/logout` | | [session](/api-reference/session) | `GET /v1/auth/session` | | [siws\_challenge](/api-reference/siws_challenge) | `POST /v1/auth/siws/challenge` | | [siws\_verify](/api-reference/siws_verify) | `POST /v1/auth/siws/verify` | | [get\_bond](/api-reference/get_bond) | `GET /v1/bonds/{bond_id}` | | [discover](/api-reference/discover) | `POST /v1/discover` | | [discover\_federated](/api-reference/discover_federated) | `POST /v1/discover/federated` | | [discover\_marsql](/api-reference/discover_marsql) | `POST /v1/discover/marsql` | | [create\_entry](/api-reference/create_entry) | `POST /v1/entries` | | [delete\_entry](/api-reference/delete_entry) | `DELETE /v1/entries/{did}` | | [get\_entry](/api-reference/get_entry) | `GET /v1/entries/{did}` | | [update\_entry](/api-reference/update_entry) | `PUT /v1/entries/{did}` | | [get\_entry\_lineage](/api-reference/get_entry_lineage) | `GET /v1/entries/{did}/lineage` | | [list\_entry\_versions](/api-reference/list_entry_versions) | `GET /v1/entries/{did}/versions` | | [get\_entry\_version](/api-reference/get_entry_version) | `GET /v1/entries/{did}/versions/{version}` | | [federation\_discover](/api-reference/federation_discover) | `POST /v1/federation/discover` | | [list\_federation\_peers](/api-reference/list_federation_peers) | `GET /v1/federation/peers` | | [update\_federation\_peer](/api-reference/update_federation_peer) | `PUT /v1/federation/peers/self` | | [federation\_sync](/api-reference/federation_sync) | `POST /v1/federation/sync` | | [health](/api-reference/health) | `GET /v1/health` | | [deep\_health](/api-reference/deep_health) | `GET /v1/health/deep` | | [list\_registries\_alias](/api-reference/list_registries_alias) | `GET /v1/registries` | | [create\_report](/api-reference/create_report) | `POST /v1/report` | | [get\_transfer\_offer](/api-reference/get_transfer_offer) | `GET /v1/transfers/offers/{offer_id}` | | [accept\_transfer\_offer](/api-reference/accept_transfer_offer) | `POST /v1/transfers/offers/{offer_id}/accept` | | [decline\_transfer\_offer](/api-reference/decline_transfer_offer) | `POST /v1/transfers/offers/{offer_id}/decline` | | [transfer\_entry](/api-reference/transfer_entry) | `POST /v1/transfers/{did}/offers` | | [websocket](/api-reference/websocket) | `GET /v1/ws` | [Download the complete OpenAPI contract](/openapi.json). # List entry versions URL: https://docs.mars.glass/api-reference/list_entry_versions Markdown: https://docs.mars.glass/api-reference/list_entry_versions.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `list_entry_versions` · **HTTP:** `GET /v1/entries/{did}/versions` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "list_entry_versions", "parameters": [ { "description": "OAS DID of the entry", "in": "path", "name": "did", "required": true, "schema": { "type": "string" } }, { "description": "Maximum number of versions to return. The server clamps this to its\nconfigured maximum page size.", "in": "query", "name": "limit", "required": false, "schema": { "format": "int64", "minimum": 1, "type": "integer" } }, { "description": "Registry sequence of the last version returned by the preceding page.\n\nClients must treat the value as opaque and echo it unchanged.", "in": "query", "name": "cursor", "required": false, "schema": { "pattern": "^[1-9][0-9]*$", "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/EntryVersionsResponse" } } }, "description": "Bounded version page in stable newest-first sequence order" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # List federation peers URL: https://docs.mars.glass/api-reference/list_federation_peers Markdown: https://docs.mars.glass/api-reference/list_federation_peers.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `list_federation_peers` · **HTTP:** `GET /v1/federation/peers` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "list_federation_peers", "responses": { "200": { "content": { "application/json": { "schema": { "items": { "$ref": "#/components/schemas/FederationPeer" }, "type": "array" } } }, "description": "Canonical federation peer list" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "tags": [ "federation" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # List registries alias URL: https://docs.mars.glass/api-reference/list_registries_alias Markdown: https://docs.mars.glass/api-reference/list_registries_alias.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Compatibility alias with the exact response body of GET /v1/federation/peers. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `list_registries_alias` · **HTTP:** `GET /v1/registries` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "description": "Compatibility alias with the exact response body of GET /v1/federation/peers.", "operationId": "list_registries_alias", "responses": { "200": { "content": { "application/json": { "schema": { "items": { "$ref": "#/components/schemas/FederationPeer" }, "type": "array" } } }, "description": "Federation peer list" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Read rate limit exceeded" } }, "tags": [ "federation" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Logout URL: https://docs.mars.glass/api-reference/logout Markdown: https://docs.mars.glass/api-reference/logout.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `logout` · **HTTP:** `POST /v1/auth/logout` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "logout", "responses": { "204": { "description": "Session revoked idempotently" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "auth" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Provision bond URL: https://docs.mars.glass/api-reference/provision_bond Markdown: https://docs.mars.glass/api-reference/provision_bond.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `provision_bond` · **HTTP:** `POST /v1/admin/bonds` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "provision_bond", "parameters": [ { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BondProvisionRequest" } } }, "required": true }, "responses": { "201": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Bond" } } }, "description": "Registry-local bond provisioned" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Admin capability missing" }, "409": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Idempotency conflict" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "trust" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Retry anchor URL: https://docs.mars.glass/api-reference/retry_anchor Markdown: https://docs.mars.glass/api-reference/retry_anchor.md Status: gated Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `retry_anchor` · **HTTP:** `POST /v1/admin/anchors/{intent_id}/retry` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. External anchor activation is gated. Local status or intent mutation does not prove a finalized Sigil transaction. Exact operation definition ```json { "operationId": "retry_anchor", "parameters": [ { "description": "Durable anchor intent identifier", "in": "path", "name": "intent_id", "required": true, "schema": { "type": "string" } }, { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/AnchorControlResponse" } } }, "description": "Intent requeued" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Admin capability missing" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Intent not found" }, "409": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Intent state or idempotency conflict" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "trust" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Session URL: https://docs.mars.glass/api-reference/session Markdown: https://docs.mars.glass/api-reference/session.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `session` · **HTTP:** `GET /v1/auth/session` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "session", "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SiwsSessionResponse" } } }, "description": "Current SIWS identity" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing, expired, or unknown" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "auth" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Siws challenge URL: https://docs.mars.glass/api-reference/siws_challenge Markdown: https://docs.mars.glass/api-reference/siws_challenge.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `siws_challenge` · **HTTP:** `POST /v1/auth/siws/challenge` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "siws_challenge", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SiwsChallengeRequest" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SiwsChallengeResponse" } } }, "description": "Single-use SIWS challenge" }, "400": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Invalid challenge request" } }, "tags": [ "auth" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Siws verify URL: https://docs.mars.glass/api-reference/siws_verify Markdown: https://docs.mars.glass/api-reference/siws_verify.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `siws_verify` · **HTTP:** `POST /v1/auth/siws/verify` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "siws_verify", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SiwsVerifyRequest" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SiwsVerifyResponse" } } }, "description": "Verified identity and opaque MARS session" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "SIWS verification failed" }, "502": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "GAL lookup failed" } }, "tags": [ "auth" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Transfer entry URL: https://docs.mars.glass/api-reference/transfer_entry Markdown: https://docs.mars.glass/api-reference/transfer_entry.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Creates a signed, expiring offer without changing entry ownership. {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `transfer_entry` · **HTTP:** `POST /v1/transfers/{did}/offers` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "description": "Creates a signed, expiring offer without changing entry ownership.", "operationId": "transfer_entry", "parameters": [ { "description": "OAS DID of the entry", "in": "path", "name": "did", "required": true, "schema": { "type": "string" } }, { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TransferOfferRequest" } } }, "required": true }, "responses": { "201": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TransferOffer" } } }, "description": "Transfer offer created" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Current owner or capability mismatch" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "409": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Live offer or sequence conflict" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Write rate limit exceeded" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Update entry URL: https://docs.mars.glass/api-reference/update_entry Markdown: https://docs.mars.glass/api-reference/update_entry.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `update_entry` · **HTTP:** `PUT /v1/entries/{did}` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "update_entry", "parameters": [ { "description": "OAS DID of the entry", "in": "path", "name": "did", "required": true, "schema": { "type": "string" } }, { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsEntry" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/MarsEntry" } } }, "description": "Entry updated" }, "400": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry validation failed" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "SIWS session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session publisher mismatch" }, "404": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Entry not found" }, "409": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Sequence or lifecycle conflict" }, "429": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Write rate limit exceeded" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "entries" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Update federation peer URL: https://docs.mars.glass/api-reference/update_federation_peer Markdown: https://docs.mars.glass/api-reference/update_federation_peer.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `update_federation_peer` · **HTTP:** `PUT /v1/federation/peers/self` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "update_federation_peer", "parameters": [ { "description": "Required route-scoped idempotency key", "in": "header", "name": "Idempotency-Key", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/FederationPeerUpdateRequest" } } }, "required": true }, "responses": { "200": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/FederationPeer" } } }, "description": "Principal-bound peer metadata" }, "401": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Session missing or invalid" }, "403": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } }, "description": "Federation capability missing" } }, "security": [ { "siwsSession": [] }, { "siwsCookie": [] } ], "tags": [ "federation" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Websocket URL: https://docs.mars.glass/api-reference/websocket Markdown: https://docs.mars.glass/api-reference/websocket.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} ## Contract and client context [#contract-and-client-context] **Operation:** `websocket` · **HTTP:** `GET /v1/ws` Use an operator-supplied registry base URL. Request execution is disabled in this documentation explorer. Generated request snippets are templates, not signed or authorized submissions. Exact operation definition ```json { "operationId": "websocket", "responses": { "101": { "description": "WebSocket protocol upgrade" } }, "tags": [ "operations" ] } ``` Resolve schema references against [the complete OpenAPI document](/openapi.json). [Standalone schemas and hashes](/reference/artifacts) are generated from the same checked-in source. # Anchor intents and activation URL: https://docs.mars.glass/operators/anchoring Markdown: https://docs.mars.glass/operators/anchoring.md Status: gated Source: MARS source inventory at https://docs.mars.glass/coverage.json A durable adapter boundary with governed external activation. ## Implementation boundary [#implementation-boundary] The server has a provider-neutral `AnchorPort`, a Sigil adapter, and durable intent/outbox/receipt state. Current entry lifecycle `active` is distinct from anchor confirmation. A registry write does not prove that a live Sigil transaction was admitted or finalized. ## Safe staged rollout [#safe-staged-rollout] Keep shadow/private-canary work within the operator's approved configuration and activation gates. MARS-S and production anchor authority must not be inferred from type definitions, a compiled adapter, or a status badge. Public docs do not grant activation authority. ## Inspect and recover [#inspect-and-recover] [Read anchors](/api-reference/get_anchors) for an entry. The generated contract distinguishes outbox and receipt state. Admin [retry](/api-reference/retry_anchor) and [abandon](/api-reference/abandon_anchor) operate on intent IDs and require capability plus idempotency. Before retrying an uncertain external action, reconcile receipts and chain state. Abandoning a local intent does not undo an already finalized external transaction. Preserve immutable audit evidence. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/anchor/mod.rs` * `mars-server/src/anchor/sigil.rs` * `mars-server/src/anchor/config.rs` * `mars-protocol/src/anchoring.rs` * `mars-server/src/production.rs` # Authentication and capabilities URL: https://docs.mars.glass/operators/authentication Markdown: https://docs.mars.glass/operators/authentication.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json SIWS sessions, scoped authority, and operator trust. ## Session model [#session-model] The always-compiled auth domain uses MARS principals, capability sets, challenge/session stores, and registered adapters. SIWS is the concrete credential adapter in this release. OpenAgent and Arsenal names are reserved extension identifiers, not working login providers. A valid session is presented as `Authorization: Bearer ...` or the `mars_session` cookie. The bearer header takes precedence. Browser cookies are Secure, HttpOnly, and SameSite=Lax. Do not copy tokens into URLs or logs. ## Capability map [#capability-map] | Action | Capability | | ----------------------------------------------------- | ------------------------------------------------------------ | | Create, update, revoke | `publish_entry`, `update_entry`, `revoke_entry` respectively | | Offer / accept or decline transfer | `transfer_out` / `transfer_accept` | | Attest / report | `attest` / `report` | | Client federated discovery | `federated_discovery` | | Peer self-update | `federation_sync` | | Bonds, anchor recovery, deep health, peer diagnostics | `admin` | Mutation middleware also enforces idempotency and scope. Possession of a signed entry is not sufficient to obtain these capabilities. ## Provisioning [#provisioning] Configure allowed authentication profiles, audience/origin policy, session/challenge durations, and trusted roots with the operator. Validate through the session endpoint. Production startup constructs supported live adapters and rejects invalid credentials/configuration before binding. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/auth/principal.rs` * `mars-server/src/auth/handlers.rs` * `mars-server/src/auth/adapters/siws.rs` * `mars-server/src/middleware/auth.rs` * `mars-server/src/api/mod.rs` # Operate federation URL: https://docs.mars.glass/operators/federation Markdown: https://docs.mars.glass/operators/federation.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Configure peers, signing, agreements, and bounded synchronization. ## Before enabling [#before-enabling] Federation starts disabled. Select peers explicitly, pin their verification keys, configure local signing identity and protected key source, and define agreements/scopes. Invalid signing or trust configuration fails startup before HTTP serving. ## Observe convergence [#observe-convergence] Monitor peer status, breaker state, last successful exchange, lag, and partial discovery metadata. Transport errors must remain visible. Bounded sync/discovery is not a promise that every registry has all records. ## Authentication [#authentication] Peer envelopes bind sender, recipient, nonce, kind, and time. Local client federated discovery uses session capability. Peer administrative updates use `federation_sync`; operator diagnostics use `admin`. Keep these interfaces separate. ## Conflict rules [#conflict-rules] Verify signatures first. Prefer matching locally confirmed anchor evidence, then greater sequence, then lexically smaller canonical digest. Never promote an unsigned or merely claimed anchored record. See [federation API](/api/federation) for exact wire operations. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/config.rs` * `mars-server/src/federation/envelope.rs` * `mars-server/src/federation/worker.rs` * `mars-server/src/federation/policy.rs` # Run a durable registry URL: https://docs.mars.glass/operators/production Markdown: https://docs.mars.glass/operators/production.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Production configuration, storage, readiness, and trust. ## Configure explicitly [#configure-explicitly] `mars-server` accepts `--config`/`MARS_CONFIG`, `--listen-addr`/`MARS_LISTEN_ADDR`, `--database-url`/`DATABASE_URL`, `--allow-memory-store`/`MARS_ALLOW_MEMORY_STORE`, and `--metrics-addr`/`MARS_METRICS_ADDR`. Configuration files use the typed TOML configuration shape. Set `MARS_ENV=production` deliberately. The production validation layer checks storage, live adapter/trust configuration, protected credentials, and enabled federation/anchor dependencies. Defaults suitable for development are not a production configuration. ## PostgreSQL [#postgresql] Use the `postgres` feature and a durable database. Startup connects/migrates the store, verifies immutable audit/event chains, and checks anchor outbox state. Memory storage is an explicit development-only opt-in and loses state on restart. Preserve authentication durability alongside entry durability. ## Search cursor keys [#search-cursor-keys] `MARS_SEARCH_CURSOR_HMAC_KEY` must be valid unpadded base64url secret material meeting the configured size requirements. Provision it through protected secret storage. Rotation must retain the supported previous-key window while existing cursors expire. See [typed search configuration](/libraries/mars-server/config) for exact options and validation. ## Readiness and observability [#readiness-and-observability] `GET /v1/health` is public. `GET /v1/health/deep` requires admin capability and checks dependencies. Prometheus metrics bind separately (default `0.0.0.0:9090`); restrict that listener to your observability network. Configure logs to exclude session tokens and signing material. ## Release features [#release-features] Production builds combine `postgres`, `sigil`, and `prod`. `prod` rejects mock/test anchor combinations. These are source build contracts; the documentation build does not certify a backend release. [Recovery](/operators/recovery) covers ledger verification and backups. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/main.rs` * `mars-server/src/production.rs` * `mars-server/src/config.rs` * `mars-server/Cargo.toml` * `mars-server/src/store/migrations.rs` # Backup and recovery URL: https://docs.mars.glass/operators/recovery Markdown: https://docs.mars.glass/operators/recovery.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Verify durable ledgers and recover without inventing success. ## Back up the whole state [#back-up-the-whole-state] Use PostgreSQL-consistent backups that include registry entries, immutable history/audit/event records, session/challenge state, transfer offers, and anchor outbox. Preserve protected configuration and signing material through the operator's secret-management process; never bundle secrets into documentation artifacts. ## Verify ledgers [#verify-ledgers] The real `mars-ledger` binary requires the `postgres` feature. With `DATABASE_URL` supplied securely: ```bash mars-ledger verify ``` It verifies complete private-audit and public-event hash chains and returns JSON containing `status`, record counts, and head hashes. A connection or chain verification failure is an error, not an empty healthy chain. `--max-connections` defaults to 4. ## Restore procedure [#restore-procedure] Restore into an isolated environment, verify the chains, inspect migration compatibility and outbox state, and validate readiness before accepting traffic. Reconcile uncertain external anchor intents with their recorded receipts before retrying. Operator [retry/abandon endpoints](/operators/anchoring) require explicit admin authority and idempotency. This page documents the recovery interface; no database restore or backend certification was performed by building this website. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/bin/mars-ledger.rs` * `mars-server/src/store/postgres.rs` * `mars-server/src/main.rs` # Registry architecture URL: https://docs.mars.glass/protocol/architecture Markdown: https://docs.mars.glass/protocol/architecture.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Durable PostgreSQL storage and clearly bounded integrations. ## Request path [#request-path] HTTP requests enter the Axum router. Public reads use bounded validation and query planning. Protected mutations resolve an opaque session into a MARS principal, enforce a scoped capability and idempotency, validate publisher-controlled data, and commit through the store abstraction. ## Persistence [#persistence] The production reference store is PostgreSQL. Entries, sessions, challenges, immutable audit/public-event ledgers, transfer offers, and anchor outbox state use durable storage. Startup verifies the ledger chains. The in-memory store is an explicit development option that loses state on restart. ## External trust [#external-trust] Publisher and peer keys are operator-pinned. SIWS is the concrete session adapter in this release. Federation selects configured peers and verifies signed envelopes. Anchor adapters are provider-neutral, with Sigil integration subject to configuration and governed activation. ## Design boundaries [#design-boundaries] MARS-S describes a proposed global-anchor/regional-shard topology; it is not the current PostgreSQL deployment. Weave is not the current durable entry store. Capacity and latency targets in design documents are not measured production performance. See [libraries](/libraries), [operators](/operators/production), and [sharding status](/sharding/overview). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/main.rs` * `mars-server/src/production.rs` * `mars-server/src/store/postgres.rs` * `SHARDING_SPECIFICATION.md` # Attestations and reports URL: https://docs.mars.glass/protocol/attestations Markdown: https://docs.mars.glass/protocol/attestations.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Signed claims, issuer policy, and registry reports. ## Attestations [#attestations] An attestation is a claim about a subject, with issuer, time, signature, and possible revocation semantics. The registry's `POST /v1/attestations` endpoint is protected by `attest` capability and idempotency. Read attestations through `GET /v1/attestations/{did}`. Verify issuer authority, subject binding, time bounds, and revocation before relying on a claim. The count of attestation records is not the count of independent issuers, and neither is automatically a reputation score. ## Reports [#reports] `POST /v1/report` requires `report` capability and `Idempotency-Key`. A report record expresses a reported condition. It must not be treated as a confirmed finding or proof that slashing occurred. ## Query and evidence [#query-and-evidence] Use [attestation filters](/marsql/attestation-joins) to select records and the [exact API](/api-reference/create_attestation) to inspect request/response schema. Preserve original evidence rather than replacing verification with an aggregate badge. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-protocol/src/api.rs` * `mars-server/src/api/rest.rs` * `mars-server/src/search.rs` # Registry-local bonds URL: https://docs.mars.glass/protocol/bonds Markdown: https://docs.mars.glass/protocol/bonds.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Bond metadata, validation, and the external settlement boundary. ## What is implemented [#what-is-implemented] The registry stores bond records and validates optional `bondReference` metadata. Operators provision bonds through the admin API. Bond requirements depend on entry type and operator policy; root entries can be exempt. `BondAmount` is a fixed-point domain type. Follow the generated [bond schemas](/reference/artifacts); do not encode amounts as display strings such as `5 MINTS` in arbitrary fields. Publisher-owned `bondReference` is included in the signing payload. ## What a bond record does not prove [#what-a-bond-record-does-not-prove] The current bond port is registry-local. It does not provide a live Mints escrow adapter or establish an on-chain wallet debit, automatic slash, or timed refund. Types for slashing and distribution describe the contract, not a verified external settlement. ## Operator workflow [#operator-workflow] Use [provision bond](/api-reference/provision_bond) with admin capability and idempotency, then [read bond](/api-reference/get_bond). Keep policy enforcement and any separately operated economic settlement explicit. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/bond.rs` * `mars-protocol/src/bonds.rs` * `mars-server/src/api/rest.rs` # Entry format and signatures URL: https://docs.mars.glass/protocol/entry-format Markdown: https://docs.mars.glass/protocol/entry-format.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json The exact wire shape, 14 entry kinds, hashes, and signing profile. ## Required wire fields [#required-wire-fields] The canonical `MarsEntry` requires `marsVersion`, `entryDid`, `entryType`, `name`, `version`, `publisherDid`, `publishedAt`, `itemSchemaUri`, `itemData`, `itemDataHash`, and structured `signature`. Download the [entry schema](/schemas/v1/mars-entry.schema.json) and [signing vectors](/test-vectors/publisher-signing-profile-v1.json). ## Entry types [#entry-types] The wire names are case-sensitive PascalCase: | Family | Types | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | Artifacts | `AgentDefinition`, `ToolDefinition`, `SkillDefinition`, `WorkflowDefinition`, `ModelDefinition`, `DatasetDefinition`, `ServiceDefinition` | | Organization and roots | `OrganizationDefinition`, `HumanRootRecord`, `MultiHumanRootRecord` | | MAP | `MapPlugin`, `MapPluginRelease`, `MapIntegrationSchema`, `MapPluginCollection` | The `EntryType` enum is authoritative. An older descriptive sentence inside the downloadable contract still says 10; the actual enum contains 14. Crate version is 0.1.0; `marsVersion` is `1.0.0`. ## Hash the payload [#hash-the-payload] `compute_item_data_hash` serializes `itemData` with RFC 8785 JSON Canonicalization Scheme and computes SHA-256, encoded as `sha256:` plus lowercase hexadecimal. Hash the canonical payload, not the complete entry or the original JSON text formatting. ## Sign the entry [#sign-the-entry] `MARS-PUBLISHER-SIGNING-V1` removes only these **top-level** fields before JCS serialization: ```text signature, sequence, updatedAt, lifecycleStatus, verifiableAttestations, shardAssignment, anchorProjection, anchorState, anchorTxHash, anchorBlockHeight, anchorProof ``` Every unlisted field remains signed, including `publisherDid`, `bondReference`, and nested fields with the same names. Use `canonical_signing_bytes`, then `sign_entry`. The signature object uses `algorithm: "Ed25519"`, a DID key URL in `keyId`, and a strict unpadded base64url value encoding 64 signature bytes. Legacy signatures made before the erratum must be re-signed; there is no dual-verification fallback. The vector contains public test-only key material, never a production key. ## Structural limits [#structural-limits] Names: 256 characters; descriptions: 4096; tags: 50, each at most 64 characters; canonical `itemData`: 1 MiB. Optional lineage, relationships, bond reference, and service endpoints must satisfy their own schemas. Passing JSON Schema does not replace runtime signature, ownership, capability, or trust checks. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-protocol/src/entry.rs` * `mars-protocol/src/hash.rs` * `mars-protocol/src/signature.rs` * `docs/adr/0002-publisher-signing-profile-v1-erratum.md` # Federation and trust URL: https://docs.mars.glass/protocol/federation Markdown: https://docs.mars.glass/protocol/federation.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Selected peers, signed envelopes, and bounded convergence. ## Explicit peer selection [#explicit-peer-selection] Federation is disabled by default. Operators select peers, pin their keys, configure federation agreements and scopes, and provision a signing identity. Federation is not an unauthenticated network-wide broadcast. ## Signed peer messages [#signed-peer-messages] Sync and federated discovery use `SignedFederationEnvelope` with message kind, sender/recipient, nonce, time bounds, and signed payload. These routes use peer-envelope verification rather than an ordinary bearer session. Lack of an OpenAPI bearer security entry does not mean that unsigned peer messages are accepted. ## Conflict resolution [#conflict-resolution] Incoming signatures must verify before conflict resolution. Among valid candidates, the policy prefers a matching locally confirmed anchor, then higher sequence, then lexically lower canonical digest. An unconfirmed external claim is not a confirmed local anchor. ## Partial results [#partial-results] Federated discovery is bounded and returns metadata about participating or failing peers. A partial response is not a complete network snapshot. Monitor lag, circuit breakers, peer status, and agreement validity; see [federation operations](/operators/federation). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/federation/envelope.rs` * `mars-server/src/federation/service.rs` * `mars-server/src/federation/policy.rs` * `mars-server/src/federation/discovery.rs` # Identity and publishers URL: https://docs.mars.glass/protocol/identities Markdown: https://docs.mars.glass/protocol/identities.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json DIDs, publisher control, and optional human-root lineage. ## Identity fields [#identity-fields] `entryDid` identifies the registered entity. `publisherDid` identifies its publisher. `signature.keyId` selects a verification key controlled by that publisher. Entry kind, DID kind, payload, and key binding are validated separately. `HumanRootRecord` and `MultiHumanRootRecord` are the canonical wire names for HMR/MHR entries. A record's existence does not establish a verified human ceremony. Verification depends on the identity proof, issuer, and configured trust policy. ## Key resolution [#key-resolution] Operator pins are resolved before registry-stored keys. Production trust policy requires publisher pins and disables implicit self-signed bootstrap by default. A valid mathematical signature from an untrusted key is insufficient for authorized publication. ## Lineage and authorization [#lineage-and-authorization] Lineage is optional entry metadata and is not the same as session capabilities. SIWS turns supported credential proofs into a MARS principal; HTTP middleware authorizes that principal using MARS capabilities. See [OpenAgentID documentation](https://docs.openagent.id) for the identity protocol and [authentication](/operators/authentication) for the registry boundary. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-protocol/src/entry.rs` * `mars-server/src/validation/resolver.rs` * `mars-server/src/config.rs` * `mars-server/src/auth/principal.rs` # What is MARS? URL: https://docs.mars.glass/protocol/introduction Markdown: https://docs.mars.glass/protocol/introduction.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json The registry contract and its implementation boundaries. MARS stores complete, signed records and provides bounded discovery, version history, lineage, attestations, lifecycle operations, federation, and event notifications. ## What an entry proves [#what-an-entry-proves] A valid entry binds its publisher to canonical payload bytes. Registry presence alone does not prove that a human ceremony occurred, a tool is safe, an endpoint is available, a model meets a benchmark, or an external chain finalized the record. Those claims require the relevant independent evidence. ## Current implementation [#current-implementation] `mars-protocol` defines the wire and cryptographic contracts. `mars-server` implements the HTTP server, authorization, storage, search, and federation. PostgreSQL is the durable reference store. `mars-shard` contains the feature-gated MARS-S prototype. ## Choose a path [#choose-a-path] Start with [HTTP discovery](/protocol/quickstart), then use the [entry format](/protocol/entry-format) and [publishing workflow](/protocol/publishing). Operators should begin with [production configuration](/operators/production). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `Cargo.toml` * `mars-protocol/src/lib.rs` * `mars-server/src/lib.rs` # Versions, revocation, and transfers URL: https://docs.mars.glass/protocol/lifecycle Markdown: https://docs.mars.glass/protocol/lifecycle.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Registry lifecycle and explicit ownership handoff. ## Versions and history [#versions-and-history] Read the current entry with `GET /v1/entries/{did}`. Enumerate versions with `GET /v1/entries/{did}/versions`, then retrieve a specific version with the version route. Updates use `PUT /v1/entries/{did}` with a newly signed payload, a scoped `update_entry` capability, and `Idempotency-Key`. Revocation uses the protected `DELETE` route. It is a lifecycle mutation; do not treat it as erasing immutable audit history. Consumers must inspect lifecycle status when choosing usable entries. ## Transfer is an explicit agreement [#transfer-is-an-explicit-agreement] 1. The current authorized owner creates a signed, expiring offer through `POST /v1/transfers/{did}/offers`. 2. The recipient reads the offer, checks its bound entry sequence and expiry, and explicitly accepts or declines it. 3. Acceptance validates the recipient and current state before ownership changes. There is no supported unilateral `/v1/transfer/{did}` command. Offer, accept, and decline use distinct wire contracts and capabilities. [Transfer API](/api-reference/transfer_entry) exposes each exact payload. ## Race and retry handling [#race-and-retry-handling] A concurrent update can invalidate a sequence-bound offer. Fetch current state and make a new deliberate offer instead of blindly retrying stale approval. Preserve idempotency keys for retries of the same operation. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` * `mars-protocol/src/lifecycle.rs` * `mars-protocol/src/api.rs` # Lineage and relationships URL: https://docs.mars.glass/protocol/lineage Markdown: https://docs.mars.glass/protocol/lineage.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Read parentage without confusing it with authorization. ## Two separate structures [#two-separate-structures] `lineageReference` carries the identity lineage to a root, including generation metadata. `relationships` carries typed artifact relationships. Neither is a grant of permission to execute a tool or mutate a registry. ## Resolve the lineage [#resolve-the-lineage] Use `GET /v1/entries/{did}/lineage` with the entry DID URL-encoded as one path segment. The [generated response](/api-reference/get_entry_lineage) defines the complete return shape. Missing parents, roots, or evidence must not be converted into a positive verification result. ## Query lineage fields [#query-lineage-fields] MARS-QL supports the server's allowlisted lineage fields, including `lineage_reference.human_root_did` and `lineage_reference.generation`. These are record filters, not recursive SQL traversal. [Lineage query examples](/marsql/lineage-traversal) show the supported surface. ## Verify separately [#verify-separately] Check root provenance, signatures, issuer policy, and revocation before using lineage to make a trust decision. Registry data may include optional or incomplete lineage. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-protocol/src/entry.rs` * `mars-protocol/src/relationships.rs` * `mars-server/src/search.rs` * `mars-server/src/api/rest.rs` # Publish a signed entry URL: https://docs.mars.glass/protocol/publishing Markdown: https://docs.mars.glass/protocol/publishing.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Prepare an authorized, idempotent registry mutation. ## Prerequisites [#prerequisites] An operator must supply the registry URL, supported authentication audience/profile, publisher trust configuration, and a principal with `publish_entry`. A publisher also needs its controlled Ed25519 key and a valid entry DID/payload schema. A session token and a publisher signature serve different purposes. ## Prepare the entry [#prepare-the-entry] 1. Build the required [wire fields](/protocol/entry-format) using a canonical `EntryType`. 2. Validate the payload against `itemSchemaUri`, then call `compute_item_data_hash` for `itemDataHash`. 3. Compute `canonical_signing_bytes` and sign with the controlled publisher key. The key controller must match the publisher. 4. Validate the completed typed entry and save it as `signed-entry.json`. Do not use the public fixture key or submit an empty signature. The [test vectors](/test-vectors/publisher-signing-profile-v1.json) let you compare canonical bytes and signatures before connecting a real signer. See the [protocol library](/libraries/mars-protocol) for source-level APIs. ## Authenticate [#authenticate] Request a [SIWS challenge](/api-reference/siws_challenge) using the operator's configured audience. Have your supported wallet sign the **returned challenge**, preserving its nonce, audience, origin, root, chain, and expiry. Submit that challenge and signed response to [verify](/api-reference/siws_verify). Never invent a wallet signature or silently replace the challenge fields. Inspect [session](/api-reference/session) to confirm principal and granted capabilities. SIWS availability depends on enabled configuration; reserved OpenAgent/Arsenal profile names are not implemented adapters. ## Submit once, retry safely [#submit-once-retry-safely] With `MARS_REGISTRY_URL`, `MARS_SESSION_TOKEN`, and `MARS_IDEMPOTENCY_KEY` set by your authenticated client, run: ```bash curl --fail-with-body --silent --show-error "$MARS_REGISTRY_URL/v1/entries" -H "Authorization: Bearer $MARS_SESSION_TOKEN" -H "Idempotency-Key: $MARS_IDEMPOTENCY_KEY" -H 'Content-Type: application/json' --data-binary @signed-entry.json ``` Reuse the same key for the same mutation and payload after an uncertain network result. A new logical mutation gets a new key. Do not change the payload while reusing a key. Check the returned record and resolve it again; a registry commit is not proof of live chain anchoring. ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` * `mars-protocol/src/signature.rs` * `mars-server/src/auth/handlers.rs` * `mars-server/src/middleware/auth.rs` # Query your first registry URL: https://docs.mars.glass/protocol/quickstart Markdown: https://docs.mars.glass/protocol/quickstart.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json A complete read-only discovery and resolution workflow. You need Python 3 and a registry base URL supplied by its operator. These examples do not assume a public hosted endpoint. ## Discover and resolve [#discover-and-resolve] Set `MARS_REGISTRY_URL` to your registry's HTTPS origin. The program checks health, discovers at most five complete records, and resolves the first result when one exists. An empty registry is a valid result. ```python title="discover.py" import json import os from urllib.parse import quote from urllib.request import Request, urlopen base = os.environ["MARS_REGISTRY_URL"].rstrip("/") def request(path, payload=None): data = None if payload is None else json.dumps(payload).encode() headers = {"Accept": "application/json"} if data is not None: headers["Content-Type"] = "application/json" with urlopen(Request(base + path, data=data, headers=headers), timeout=15) as response: return json.load(response) print("health:", request("/v1/health")) result = request("/v1/discover/marsql", {"query": "DISCOVER * LIMIT 5"}) print(json.dumps(result, indent=2)) entries = result.get("entries", []) if entries: did = quote(entries[0]["entryDid"], safe="") print("resolved:", request("/v1/entries/" + did)) else: print("No matching entries in this registry.") ``` ```bash python3 discover.py ``` ## What to inspect [#what-to-inspect] Check each record's `entryType`, `publisherDid`, `itemSchemaUri`, `itemDataHash`, and `signature`. Discovery returns complete records; verification is a separate client responsibility. Read [signatures](/protocol/entry-format) before trusting a record. ## Handle failures [#handle-failures] A transport or health failure is different from zero matches. The example propagates HTTP errors instead of converting failures to empty results. For pagination, reuse the returned opaque cursor with the same query and ordering; see [MARS-QL](/marsql/overview). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. * `mars-server/src/api/mod.rs` * `mars-server/src/contracts.rs` * `docs/api/openapi.v1.json` * `mars-protocol/src/marsql/ast.rs` # Contract downloads URL: https://docs.mars.glass/reference/artifacts Markdown: https://docs.mars.glass/reference/artifacts.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Exact OpenAPI, 64 schemas, signing vectors, and source provenance. The following files are copied byte-for-byte from the checked-in source. They are not a second hand-maintained model. ## Canonical artifacts [#canonical-artifacts] | File | SHA-256 | | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | [docs/api/openapi.v1.json](/openapi.json) | `b9d5ec5aa63ba8a5038f3d683f98dff6052d93fcdc4164d6120a9f75322e7cd0` | | [docs/api/openapi.v1.json](/openapi/v1.json) | `b9d5ec5aa63ba8a5038f3d683f98dff6052d93fcdc4164d6120a9f75322e7cd0` | | [schemas/v1/anchor-control-response.schema.json](/schemas/v1/anchor-control-response.schema.json) | `66c61394879bd75c13bf8f436cfe350c1ddd9163a51b7f0990fb8390b1829f72` | | [schemas/v1/anchor-list-query.schema.json](/schemas/v1/anchor-list-query.schema.json) | `b099d5faa890700a01937b44e883752654a373d127d4b8b4102ae81c89fc5197` | | [schemas/v1/anchor-list-response.schema.json](/schemas/v1/anchor-list-response.schema.json) | `c9c7443a290bdfae80f5959f6610c44a1cac097bb8508471c14153f924ab13d6` | | [schemas/v1/anchor-operation.schema.json](/schemas/v1/anchor-operation.schema.json) | `e777e13521a860fb0183c59e3a5e34a745da0a81e39a55c921b807df151a1063` | | [schemas/v1/anchor-outbox-state.schema.json](/schemas/v1/anchor-outbox-state.schema.json) | `b8c21c6c9981d88c96d2551b963cde856dfcd92c2c56463d5cb5b669a98300d2` | | [schemas/v1/anchor-receipt-record.schema.json](/schemas/v1/anchor-receipt-record.schema.json) | `a686b09a83f4a20f691890591f0beef55296d82b877beb71aa79a88fe37c0e46` | | [schemas/v1/anchor-receipt-state.schema.json](/schemas/v1/anchor-receipt-state.schema.json) | `8993748b74b80465d0cc10ec8cdf1e23886c3a2754669374cf587e5e31c5d520` | | [schemas/v1/anchor-record.schema.json](/schemas/v1/anchor-record.schema.json) | `9789c65841b7711388928f867fd940df8b3e831538a0719a986c881590b603ae` | | [schemas/v1/anchor-request.schema.json](/schemas/v1/anchor-request.schema.json) | `dc9a5e0fc24bf44eabef1e51bb948cc7978977684bd7d0a2c3fb389a93f87cba` | | [schemas/v1/anchor-response.schema.json](/schemas/v1/anchor-response.schema.json) | `ab1b9a71aea47c25b632faac0c0e07b8e8d1672dcf54341fe6e8eb2bf588fd90` | | [schemas/v1/anchor-state.schema.json](/schemas/v1/anchor-state.schema.json) | `88e2d3c9d47f0d883b54fa83207e85e1cd3f9fc34351c8ec4a097b803615e71b` | | [schemas/v1/anchor-status-record.schema.json](/schemas/v1/anchor-status-record.schema.json) | `63fd244c43339d66528be9fed714585d323e481d6a663960bfada7b3d606acb4` | | [schemas/v1/attestation-query.schema.json](/schemas/v1/attestation-query.schema.json) | `698d08c22a07b66e549e639693bd45d1d83ff18fa037199aa72bad943c1e0d62` | | [schemas/v1/attestation-request.schema.json](/schemas/v1/attestation-request.schema.json) | `b4517399c43fcb16505883065df885a12153df1fb74854b4eff66cbf57b43be4` | | [schemas/v1/bond-provision-request.schema.json](/schemas/v1/bond-provision-request.schema.json) | `03dd64b4ff74095abc204c1feda0e34231182501e50ad3c00cab4df452026676` | | [schemas/v1/bond-reference.schema.json](/schemas/v1/bond-reference.schema.json) | `aa0225ebfbd5d889d1286531fe509d6109ca1f911537c6a9451b59ae14826aaa` | | [schemas/v1/bond.schema.json](/schemas/v1/bond.schema.json) | `78e3af8304f5fc500d1e83dbddc2053dcbe6d7274d1383fe9e61fc21daa70347` | | [schemas/v1/deep-health-response.schema.json](/schemas/v1/deep-health-response.schema.json) | `2d7605a14ab761aba366c8adc5e9ef5ae62bf64d353f079c7dd16e4d356af0de` | | [schemas/v1/discover-request.schema.json](/schemas/v1/discover-request.schema.json) | `eb17d204096a631ffc2e4ffd03017cd94198f9c024d638fd17d53abb15c8067d` | | [schemas/v1/entry-lineage-response.schema.json](/schemas/v1/entry-lineage-response.schema.json) | `332a10db3bd10058ca9e155ddd35d4e3648327fe794524027dac816b96611525` | | [schemas/v1/entry-versions-query.schema.json](/schemas/v1/entry-versions-query.schema.json) | `a36968715d429d6b3331af71869e9b0c02496780597d52d6585de7aedf0786de` | | [schemas/v1/entry-versions-response.schema.json](/schemas/v1/entry-versions-response.schema.json) | `9ec17d0f2e23adfe41001a83b37f13431f31075f885d09985a79e5aa6208bae5` | | [schemas/v1/error-response.schema.json](/schemas/v1/error-response.schema.json) | `b5533eb76aa74ef8771ffc511d71ac1bd4f94cc1a1aa58e3b93dd2f66e0a7563` | | [schemas/v1/federated-discovery-request.schema.json](/schemas/v1/federated-discovery-request.schema.json) | `208e74cf561bf61ef3e3ffa85fa8ab35a4a5defe8ced272ef7bc9368779f2b9c` | | [schemas/v1/federated-discovery-response.schema.json](/schemas/v1/federated-discovery-response.schema.json) | `84a50b7d91f0ec1d4a2b3fa0b27c8e4cf8c3aff948ebd1c1988a66f8c2ac3f78` | | [schemas/v1/federated-discovery-result.schema.json](/schemas/v1/federated-discovery-result.schema.json) | `b9c8853d80165b18b9b72936a60668a54894e1720f043ba7da168717f1f7fc0d` | | [schemas/v1/federation-agreement.schema.json](/schemas/v1/federation-agreement.schema.json) | `c8a654fba32483cc03fa5e52b0dca74268c7978e4a082f978ba6b135c1f65a6b` | | [schemas/v1/federation-breaker-state.schema.json](/schemas/v1/federation-breaker-state.schema.json) | `d5e612dc612e312f8b20f7995594399cdbcc8f8acf04e1ff0e12edc347b4dd44` | | [schemas/v1/federation-peer-status.schema.json](/schemas/v1/federation-peer-status.schema.json) | `7d95a4a5505a332da036116f4d477fa29c7c95f51059c300b4ea42cf16b3b0b7` | | [schemas/v1/federation-peer-update-request.schema.json](/schemas/v1/federation-peer-update-request.schema.json) | `3a814e4c17835fb2627daca0185ac647a97de4c05b187fe197827459931c3e8b` | | [schemas/v1/federation-peer.schema.json](/schemas/v1/federation-peer.schema.json) | `bd664db85e7110267e4c58b09d82e005249e6bd4295d458f707198645a270270` | | [schemas/v1/health-response.schema.json](/schemas/v1/health-response.schema.json) | `03f876520c9ae6169a9f50241da8264fc00267868a6b3a03c54c9b92053c8743` | | [schemas/v1/lifecycle-status.schema.json](/schemas/v1/lifecycle-status.schema.json) | `c3420bc67453317308dff0a566dc202fb0e0e921357e20758f99041f748af7fb` | | [schemas/v1/lineage-reference.schema.json](/schemas/v1/lineage-reference.schema.json) | `e0e196ea48691f59b86f3345cb136181fa63d06c2351b02333fa59f878c817f7` | | [schemas/v1/mars-anchor.schema.json](/schemas/v1/mars-anchor.schema.json) | `6713321ad55213ddb24a57698e04eea674346b1da7e71f3504213e0df09da64b` | | [schemas/v1/mars-entry.schema.json](/schemas/v1/mars-entry.schema.json) | `adf24419ff5dec99302dc861677e7785480ed27c8b2ac10b1008e90447a58229` | | [schemas/v1/mars-error-code.schema.json](/schemas/v1/mars-error-code.schema.json) | `8531f582f25c35a556c16b741bcba564a50fb43ff80776374c497adda3b7e10a` | | [schemas/v1/mars-event.schema.json](/schemas/v1/mars-event.schema.json) | `a50e7616935cfc2c2027cc250107356b0c712b0e0f0919f632b6fca287b7af3a` | | [schemas/v1/marsql-request.schema.json](/schemas/v1/marsql-request.schema.json) | `79bae6cbac2d4f36af1c09bfd8cef3e80767638c0483d6ab982196cccee98f99` | | [schemas/v1/marsql-result.schema.json](/schemas/v1/marsql-result.schema.json) | `ac4a8800b1fe3e8728c298a7b99a1fa78add94101ce0409bbee25fe964d95558` | | [schemas/v1/marsql.schema.json](/schemas/v1/marsql.schema.json) | `8deeb8a2c2de2362db7eb2b260d3cb016bb21cc567f6754fe65ff831a2293c81` | | [schemas/v1/report-request.schema.json](/schemas/v1/report-request.schema.json) | `c21593ee173706c49fdac64c777ebbdfd7f11611d3f92a2fc575e57d52834ea9` | | [schemas/v1/report-response.schema.json](/schemas/v1/report-response.schema.json) | `9138bae058a7c9963478fd4c5b631ff6aedc5ac5ca058a825e3b25613c8c05e4` | | [schemas/v1/report-status.schema.json](/schemas/v1/report-status.schema.json) | `f86767541144eefa7d9b9a2e34397119122560fbcd54dd8a5187e4b9b6f8d9a4` | | [schemas/v1/signed-federated-discovery-request.schema.json](/schemas/v1/signed-federated-discovery-request.schema.json) | `3303e50c7cb3860ccb3f4c432b628b23f378041b05e891001d1cedabcf7ac120` | | [schemas/v1/signed-federated-discovery-response.schema.json](/schemas/v1/signed-federated-discovery-response.schema.json) | `23827766f7a0691dad970ce4f7b49f04feb3894dbbdccc4a43adccc07e7a0bb5` | | [schemas/v1/signed-sync-request.schema.json](/schemas/v1/signed-sync-request.schema.json) | `b9faa1e248a54a0c010c50ab8639550c8b04e316e8e20b340f07c3c7e541def5` | | [schemas/v1/signed-sync-response.schema.json](/schemas/v1/signed-sync-response.schema.json) | `16e497b4f71c14aebf9d2eebeff77d71a5b7cf686b4249b9b683b19d913ceceb` | | [schemas/v1/siws-challenge-request.schema.json](/schemas/v1/siws-challenge-request.schema.json) | `fe55081de5067559fa88c4d76afc937a45ad93a3faf5627bbc9838939f8e4c12` | | [schemas/v1/siws-challenge-response.schema.json](/schemas/v1/siws-challenge-response.schema.json) | `cf6894e22fdbbc72c0ff011fa8dff2760d5dea43fb153981aa486ec6b32c213a` | | [schemas/v1/siws-challenge.schema.json](/schemas/v1/siws-challenge.schema.json) | `997b369146c6a10dcc79b9167dde71d79351a8dc27aa412cd2819bd76f74d7bb` | | [schemas/v1/siws-session-response.schema.json](/schemas/v1/siws-session-response.schema.json) | `8beaadbb173232db500c9856d65b764124fcd95ee2d2090d34051e3a757ca4fd` | | [schemas/v1/siws-signed-response.schema.json](/schemas/v1/siws-signed-response.schema.json) | `80d7601d360a7c631d46024de4ebc2988bbc3fbe01fa4836a1f3602938335d91` | | [schemas/v1/siws-verify-request.schema.json](/schemas/v1/siws-verify-request.schema.json) | `37a3e660e6d20d0840af000530a18188f6f02c7391275ad9dd0827e371f872d6` | | [schemas/v1/siws-verify-response.schema.json](/schemas/v1/siws-verify-response.schema.json) | `a5ec1921875462d9deb1408560db6298d53320fa0507e2d88b151eb881a121ff` | | [schemas/v1/subscription-message.schema.json](/schemas/v1/subscription-message.schema.json) | `3f761f53a25415b71a889276ad6980b447f38b2ac49e0f4a8c593f5e2972469f` | | [schemas/v1/sync-request.schema.json](/schemas/v1/sync-request.schema.json) | `3eba3945bf225aafb493d3c757e75eeb0e5627cc3aaabec22ae03641cb872799` | | [schemas/v1/sync-response.schema.json](/schemas/v1/sync-response.schema.json) | `fa28a1e78795910ec320e6b213dbe4696d781fa93b8170195b1295d10625a034` | | [schemas/v1/transfer-accept-request.schema.json](/schemas/v1/transfer-accept-request.schema.json) | `11cfb0b0de4687d1bc3309662c96bef0c939a338472f77dbabccab05c5d8fc41` | | [schemas/v1/transfer-decline-request.schema.json](/schemas/v1/transfer-decline-request.schema.json) | `32174704f907b30fb1f65c566b337195c1066441fd935c588e1c4894b22755b9` | | [schemas/v1/transfer-offer-request.schema.json](/schemas/v1/transfer-offer-request.schema.json) | `0fa4bef7142565754bffcf607b3e5dee08eb17e1193f2e12554f407d328f1fef` | | [schemas/v1/transfer-offer-status.schema.json](/schemas/v1/transfer-offer-status.schema.json) | `6567461ee5f8dc429dbba8ab41e8b5ecde3cf29a5e2cf49f4da9a7bb153c8c61` | | [schemas/v1/transfer-offer.schema.json](/schemas/v1/transfer-offer.schema.json) | `df64198ead1b7c9ec206c807165bf95d897a75aca88b6faeab33dd1487f1a4e3` | | [schemas/v1/verifiable-attestation-record.schema.json](/schemas/v1/verifiable-attestation-record.schema.json) | `cec6bce4aad6ecae023266bbd84aa92964bace6b3150bd56003550eb8b2a0b9b` | | [mars-protocol/test-vectors/publisher-signing-profile-v1.json](/test-vectors/publisher-signing-profile-v1.json) | `36977f0004bf382bc4b1765d4cca58426306e91ecaed24433035b27838f0bb20` | | [docs/adr/0001-production-registry-and-contract-authority.md](/reference/adr/0001-production-registry-and-contract-authority.md) | `ffdf6bd24c75b19b675a60f4050e15853885fa1d7d0af91733bb5c869dcd6669` | | [docs/adr/0002-publisher-signing-profile-v1-erratum.md](/reference/adr/0002-publisher-signing-profile-v1-erratum.md) | `351b6a46125068e58485c145efcb30ea0228cb99c82ada49dc308948efd9281d` | ## Interpretation [#interpretation] There are **35 HTTP operations**, **64 standalone JSON schemas**, and **14 concrete entry types**. OpenAPI component schemas additionally include envelope specializations. `marsVersion` is 1.0.0; the Rust workspace is 0.1.0. Some source description strings retain historical wording; the typed enum and current router are authoritative. ## Regenerate and check [#regenerate-and-check] The actual `mars-contracts` binary supplies `generate` and `check`. Building this docs app copies and hashes committed artifacts; it does not execute Rust contract regeneration. Run contract drift verification in the approved backend build environment before publishing a changed protocol contract. # Resolution cascade URL: https://docs.mars.glass/sharding/cascade Markdown: https://docs.mars.glass/sharding/cascade.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Feature-gated prototype; separate from the durable production reference. **Status: prototype / draft.** ## Design scope [#design-scope] The `resolution` module models the prototype multi-hop resolution path; `shadow` models secondary copies and `cross_shard` coordinates cross-partition work. Design-hop counts and latency targets are not current benchmark results. Resolve normal registry entries through the production HTTP contract. ## Explore the implementation [#explore-the-implementation] The [mars-shard library reference](/libraries/mars-shard) lists every module and source boundary. Feature flags and local types are implementation evidence, not live network evidence. ## Use the current registry [#use-the-current-registry] For production integration, start with [HTTP discovery](/protocol/quickstart), [PostgreSQL operations](/operators/production), and the [generated API contract](/api-reference). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. MARS-S is a feature-gated prototype; it is not the production storage topology. * `mars-shard/src/resolution.rs` * `mars-shard/src/shadow.rs` * `mars-shard/src/cross_shard.rs` # Global anchor layer URL: https://docs.mars.glass/sharding/global-anchor-layer Markdown: https://docs.mars.glass/sharding/global-anchor-layer.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Feature-gated prototype; separate from the durable production reference. **Status: prototype / draft.** ## Design scope [#design-scope] The design uses a global anchor layer to describe registry/shard authority and topology. The `gal` module defines its interface and records. A GAL record or reserved anchor field is not proof of a live admission or finality result. Keep this design separate from current registry entry persistence. ## Explore the implementation [#explore-the-implementation] The [mars-shard library reference](/libraries/mars-shard) lists every module and source boundary. Feature flags and local types are implementation evidence, not live network evidence. ## Use the current registry [#use-the-current-registry] For production integration, start with [HTTP discovery](/protocol/quickstart), [PostgreSQL operations](/operators/production), and the [generated API contract](/api-reference). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. MARS-S is a feature-gated prototype; it is not the production storage topology. * `mars-shard/src/gal.rs` * `SHARDING_SPECIFICATION.md` # MARS-S status URL: https://docs.mars.glass/sharding/overview Markdown: https://docs.mars.glass/sharding/overview.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Feature-gated prototype; separate from the durable production reference. **Status: prototype / draft.** ## Design scope [#design-scope] MARS-S is a feature-gated sharding prototype. Its global anchor, regional shard, affinity, resolution, shadow, and lifecycle types are implemented as an experimental library surface. Current production reference storage remains PostgreSQL. No planetary capacity or latency target is certified by these docs. ## Explore the implementation [#explore-the-implementation] The [mars-shard library reference](/libraries/mars-shard) lists every module and source boundary. Feature flags and local types are implementation evidence, not live network evidence. ## Use the current registry [#use-the-current-registry] For production integration, start with [HTTP discovery](/protocol/quickstart), [PostgreSQL operations](/operators/production), and the [generated API contract](/api-reference). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. MARS-S is a feature-gated prototype; it is not the production storage topology. * `SHARDING_SPECIFICATION.md` * `mars-server/Cargo.toml` * `mars-shard/src/lib.rs` # Regional shard layer URL: https://docs.mars.glass/sharding/regional-shard-layer Markdown: https://docs.mars.glass/sharding/regional-shard-layer.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Feature-gated prototype; separate from the durable production reference. **Status: prototype / draft.** ## Design scope [#design-scope] Regional shards are a proposed partitioning and locality layer. The `topology` and `affinity` modules model assignments and routing. They do not replace the default PostgreSQL store or establish an automatically deployed regional service. ## Explore the implementation [#explore-the-implementation] The [mars-shard library reference](/libraries/mars-shard) lists every module and source boundary. Feature flags and local types are implementation evidence, not live network evidence. ## Use the current registry [#use-the-current-registry] For production integration, start with [HTTP discovery](/protocol/quickstart), [PostgreSQL operations](/operators/production), and the [generated API contract](/api-reference). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. MARS-S is a feature-gated prototype; it is not the production storage topology. * `mars-shard/src/topology.rs` * `mars-shard/src/affinity.rs` # Topology and lifecycle URL: https://docs.mars.glass/sharding/topology Markdown: https://docs.mars.glass/sharding/topology.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Feature-gated prototype; separate from the durable production reference. **Status: prototype / draft.** ## Design scope [#design-scope] The prototype topology/lifecycle modules describe shard state and transitions. Enabling the server `sharding` feature adds experimental integrations; it does not certify deployment topology or safe migration of an existing registry. Operators must follow a separate reviewed activation and migration plan. ## Explore the implementation [#explore-the-implementation] The [mars-shard library reference](/libraries/mars-shard) lists every module and source boundary. Feature flags and local types are implementation evidence, not live network evidence. ## Use the current registry [#use-the-current-registry] For production integration, start with [HTTP discovery](/protocol/quickstart), [PostgreSQL operations](/operators/production), and the [generated API contract](/api-reference). ## Source authority [#source-authority] This page describes the checked-in implementation, not the availability of a public registry. MARS-S is a feature-gated prototype; it is not the production storage topology. * `mars-shard/src/topology.rs` * `mars-shard/src/lifecycle.rs` * `mars-server/src/store/sharded_memory.rs` # mars-shard · affinity URL: https://docs.mars.glass/libraries/mars-shard/affinity Markdown: https://docs.mars.glass/libraries/mars-shard/affinity.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-shard::affinity. **Package:** `mars-shard` · **Workspace version:** `0.1.0` · **Module:** `affinity` **Status: prototype / draft.** This is not the production registry topology. This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## affinity::AffinityFunction [#affinityaffinityfunction] Determines the key extraction strategy for shard assignment. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum AffinityFunction { /// Hash on the organization DID from lineage. Organization, /// Hash on the human root DID. HumanRoot, /// Hash on the entry DID prefix/namespace. Namespace, } ``` Source line: `20`. ## affinity::AffinityRouter [#affinityaffinityrouter] Consistent-hashing ring that maps entries to shard IDs. Each shard is represented by `virtual_nodes_per_shard` positions on the ring. SHA-256 is used for hash computation. ```rust pub struct AffinityRouter { } ``` Source line: `37`. ## affinity::AffinityRouter::new [#affinityaffinityrouternew] Create a new router with the given shard IDs and virtual node count. `virtual_nodes_per_shard` should be at least 1. A typical value is 150. ```rust pub fn new(shard_ids: &[String], virtual_nodes_per_shard: u32) -> Self; ``` Source line: `48`. ## affinity::AffinityRouter::assign [#affinityaffinityrouterassign] Assign a raw key to a shard using the consistent hashing ring. Returns the shard ID that owns the key, or an error if the ring is empty. ```rust pub fn assign(&self, key: &str) -> Result; ``` Source line: `70`. ## affinity::AffinityRouter::assign\_entry [#affinityaffinityrouterassign_entry] Assign an entry to a shard using the specified affinity function. The affinity function determines which key is extracted from the entry metadata for hashing. ```rust pub fn assign_entry( &self, entry_did: &str, publisher_did: &str, affinity: AffinityFunction, ) -> Result; ``` Source line: `90`. ## affinity::AffinityRouter::add\_shard [#affinityaffinityrouteradd_shard] Add a shard to the ring. Generates virtual nodes for it. ```rust pub fn add_shard(&mut self, shard_id: &str); ``` Source line: `105`. ## affinity::AffinityRouter::remove\_shard [#affinityaffinityrouterremove_shard] Remove a shard from the ring and its virtual nodes. ```rust pub fn remove_shard(&mut self, shard_id: &str); ``` Source line: `118`. ## affinity::AffinityRouter::shard\_count [#affinityaffinityroutershard_count] Returns the number of shards currently in the ring. ```rust pub fn shard_count(&self) -> u32; ``` Source line: `125`. ## affinity::AffinityRouter::ring\_size [#affinityaffinityrouterring_size] Returns the total number of virtual nodes on the ring. ```rust pub fn ring_size(&self) -> usize; ``` Source line: `130`. ## Source provenance [#source-provenance] Source: `mars-shard/src/affinity.rs` · SHA-256 `1bcd918d3e55a21b535ceb5557ee757a90de9da9e1549454a7aab58b0a719aa5`. [Package overview](/libraries/mars-shard). # mars-shard · cross_shard URL: https://docs.mars.glass/libraries/mars-shard/cross_shard Markdown: https://docs.mars.glass/libraries/mars-shard/cross_shard.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-shard::cross_shard. **Package:** `mars-shard` · **Workspace version:** `0.1.0` · **Module:** `cross_shard` **Status: prototype / draft.** This is not the production registry topology. This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## cross\_shard::CrossShardQuery [#cross_shardcrossshardquery] A query that must be executed across multiple shards. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CrossShardQuery { /// Unique query ID for correlation. pub query_id: String, /// Shard IDs that must be queried. pub target_shards: Vec, /// The MARS-QL query string. pub query: String, /// Per-shard timeout in milliseconds. pub timeout_ms: u64 } ``` Source line: `21`. ## cross\_shard::ShardPartialResult [#cross_shardshardpartialresult] Partial result from a single shard. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShardPartialResult { /// The shard that produced this result. pub shard_id: String, /// Whether the shard responded successfully. pub success: bool, /// Matching entry IDs from this shard. pub entry_ids: Vec, /// Optional error message on failure. #[serde(skip_serializing_if = "Option::is_none")] pub error: Option } ``` Source line: `39`. ## cross\_shard::CrossShardResult [#cross_shardcrossshardresult] Aggregated result from a cross-shard scatter/gather query. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CrossShardResult { /// The original query ID. pub query_id: String, /// Per-shard partial results. pub shard_results: Vec, /// Merged entry IDs across all successful shards. pub merged_entry_ids: Vec, /// Number of shards that responded successfully. pub success_count: usize, /// Number of shards that failed. pub failure_count: usize } ``` Source line: `58`. ## cross\_shard::scatter\_query [#cross_shardscatter_query] Scatter a cross-shard query into per-shard work items. Returns a list of `(shard_id, query_string)` pairs that the coordinator should dispatch to individual shard workers. ```rust pub fn scatter_query(query: &CrossShardQuery) -> Vec<(String, String)>; ``` Source line: `79`. ## cross\_shard::gather\_results [#cross_shardgather_results] Gather partial results from shard workers into a unified cross-shard result. Merges all successful entry IDs and tallies success/failure counts. ```rust pub fn gather_results(query_id: &str, partials: Vec) -> CrossShardResult; ``` Source line: `90`. ## cross\_shard::TransferState [#cross_shardtransferstate] State machine for an atomic cross-shard entry transfer. ```rust #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum TransferState { /// Transfer has been initiated; no locks yet. Initiated, /// The entry is locked on the source shard (preventing mutations). SourceLocked, /// The entry has been written to the target shard. TargetWritten, /// The entry has been deleted from the source shard. SourceDeleted, /// Transfer completed successfully. Complete, /// Transfer was rolled back after a failure. RolledBack, } ``` Source line: `123`. ## cross\_shard::CrossShardTransfer [#cross_shardcrossshardtransfer] Tracks an atomic entry transfer between two shards. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CrossShardTransfer { /// Unique transfer ID. pub transfer_id: String, /// The entry being transferred. pub entry_id: String, /// Source shard ID. pub source_shard: String, /// Target shard ID. pub target_shard: String, /// Current state of the transfer. pub state: TransferState, /// When the transfer was initiated. pub initiated_at: chrono::DateTime, /// When the transfer completed or was rolled back. #[serde(skip_serializing_if = "Option::is_none")] pub finished_at: Option> } ``` Source line: `145`. ## cross\_shard::AtomicTransfer [#cross_shardatomictransfer] Manages atomic cross-shard entry transfers. Implements a two-phase state machine: `Initiated -> SourceLocked -> TargetWritten -> SourceDeleted -> Complete` Any state before `SourceDeleted` can be rolled back. ```rust pub struct AtomicTransfer { } ``` Source line: `173`. ## cross\_shard::AtomicTransfer::new [#cross_shardatomictransfernew] Create a new atomic transfer manager. ```rust pub fn new() -> Self; ``` Source line: `180`. ## cross\_shard::AtomicTransfer::initiate [#cross_shardatomictransferinitiate] Initiate a new cross-shard transfer. ```rust pub fn initiate( &mut self, entry_id: &str, source_shard: &str, target_shard: &str, ) -> Result; ``` Source line: `188`. ## cross\_shard::AtomicTransfer::advance [#cross_shardatomictransferadvance] Advance a transfer to the next state. Valid transitions: * `Initiated -> SourceLocked` * `SourceLocked -> TargetWritten` * `TargetWritten -> SourceDeleted` * `SourceDeleted -> Complete` ```rust pub fn advance(&mut self, transfer_id: &str) -> Result<&CrossShardTransfer, ShardError>; ``` Source line: `250`. ## cross\_shard::AtomicTransfer::rollback [#cross_shardatomictransferrollback] Roll back a transfer. Only possible from `Initiated`, `SourceLocked`, or `TargetWritten`. Once `SourceDeleted` is reached, rollback is not safe. ```rust pub fn rollback(&mut self, transfer_id: &str) -> Result<&CrossShardTransfer, ShardError>; ``` Source line: `284`. ## cross\_shard::AtomicTransfer::get [#cross_shardatomictransferget] Get a transfer by ID. ```rust pub fn get(&self, transfer_id: &str) -> Option<&CrossShardTransfer>; ``` Source line: `310`. ## cross\_shard::AtomicTransfer::in\_flight [#cross_shardatomictransferin_flight] List all in-flight transfers (not complete, not rolled back). ```rust pub fn in_flight(&self) -> Vec<&CrossShardTransfer>; ``` Source line: `315`. ## cross\_shard::AtomicTransfer::all\_transfers [#cross_shardatomictransferall_transfers] List all transfers. ```rust pub fn all_transfers(&self) -> Vec<&CrossShardTransfer>; ``` Source line: `323`. ## Source provenance [#source-provenance] Source: `mars-shard/src/cross_shard.rs` · SHA-256 `a3c33ae417daed2d3670c3774518c74ed6c6dbf725a3f224fcee23f27d3e5783`. [Package overview](/libraries/mars-shard). # mars-shard · error URL: https://docs.mars.glass/libraries/mars-shard/error Markdown: https://docs.mars.glass/libraries/mars-shard/error.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-shard::error. **Package:** `mars-shard` · **Workspace version:** `0.1.0` · **Module:** `error` **Status: prototype / draft.** This is not the production registry topology. This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## error::ShardError [#errorsharderror] ```rust #[derive(Debug, Clone, thiserror::Error)] pub enum ShardError { #[error("GAL anchoring error: {0}")] GalError(String), #[error("affinity error: {0}")] AffinityError(String), #[error("topology error: {0}")] TopologyError(String), #[error("resolution error: {0}")] ResolutionError(String), #[error("shadow copy error: {0}")] ShadowError(String), #[error("lifecycle error: {0}")] LifecycleError(String), #[error("cross-shard error: {0}")] CrossShardError(String), #[error("serialization error: {0}")] SerializationError(String), #[error("not found: {0}")] NotFound(String), #[error("invalid state transition: {0}")] InvalidTransition(String), #[error("timeout: {0}")] Timeout(String), #[error("cache error: {0}")] CacheError(String), #[error("validation error: {0}")] ValidationError(String), } ``` Source line: `2`. ## Source provenance [#source-provenance] Source: `mars-shard/src/error.rs` · SHA-256 `804b19474c0db3cd3af79532400dad976381d025cc4e0c2d58d4f46ba2dcdc8b`. [Package overview](/libraries/mars-shard). # mars-shard · gal URL: https://docs.mars.glass/libraries/mars-shard/gal Markdown: https://docs.mars.glass/libraries/mars-shard/gal.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-shard::gal. **Package:** `mars-shard` · **Workspace version:** `0.1.0` · **Module:** `gal` **Status: prototype / draft.** This is not the production registry topology. This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## gal::GalEntryType [#galgalentrytype] The type of anchor stored in the Global Anchor Layer. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum GalEntryType { /// An HMR identity anchor. HmrAnchor, /// An MHR (multi-human root) identity anchor. MhrAnchor, /// Root of an organization lineage chain. OrgLineageRoot, /// A revocation record for a previously published entry. RevocationRecord, /// Assignment of a DID to a specific RSL shard. ShardAssignment, /// Topology metadata for a shard in the network. ShardTopologyEntry, } ``` Source line: `19`. ## gal::GalEntryType::all [#galgalentrytypeall] Returns all variants. ```rust pub fn all() -> &'static [GalEntryType; 6]; ``` Source line: `36`. ## gal::GalEntry [#galgalentry] A GAL entry stored on-chain in the Sigil execution layer. Only root-level anchors live in GAL. Full entries stay in RSL shards. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GalEntry { /// The type of GAL anchor. pub entry_type: GalEntryType, /// The DID this anchor references. pub did: String, /// SHA-256 content hash of the full entry in RSL. pub content_hash: String, /// DID of the publisher who created the anchor. pub publisher_did: String, /// When this anchor was created. pub created_at: chrono::DateTime, /// When this anchor was last updated. pub updated_at: chrono::DateTime, /// Which RSL shard holds the full entry. pub shard_id: String, /// Merkle inclusion proof from the shard (optional). #[serde(skip_serializing_if = "Option::is_none")] pub proof: Option> } ``` Source line: `57`. ## gal::GalEntry::validate [#galgalentryvalidate] Validate that required fields are non-empty. ```rust pub fn validate(&self) -> Result<(), ShardError>; ``` Source line: `79`. ## gal::GalEntry::hash [#galgalentryhash] Compute the SHA-256 hash of this entry's core fields for Merkle tree insertion. ```rust pub fn hash(&self) -> [u8; 32]; ``` Source line: `101`. ## gal::HmrAnchorData [#galhmranchordata] Anchor data specific to an HMR (Human Root) entry. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HmrAnchorData { /// DID of the HMR. pub hmr_did: String, /// DID of the entry being anchored. pub entry_did: String, /// SHA-256 hash of the item data. pub item_data_hash: String, /// Proof-of-humanity attestation reference. pub proof_of_humanity: String } ``` Source line: `121`. ## gal::MhrAnchorData [#galmhranchordata] Anchor data specific to an MHR (Multi-Human Root) entry. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MhrAnchorData { /// DID of the MHR. pub mhr_did: String, /// Hash of the threshold ceremony. pub ceremony_hash: String, /// Threshold required (e.g. 3 of 5). pub threshold: u8, /// DIDs of participants in the MHR ceremony. pub participants: Vec } ``` Source line: `139`. ## gal::OrgLineageRootData [#galorglineagerootdata] Anchor data for an organization lineage root. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OrgLineageRootData { /// DID of the organization. pub org_did: String, /// DID of the originating human root. pub human_root_did: String, /// Ordered chain of DIDs from root to org. pub lineage_chain: Vec, /// Generation depth from human root. pub depth: u32 } ``` Source line: `157`. ## gal::RevocationRecord [#galrevocationrecord] A record of a revoked entry. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RevocationRecord { /// DID of the revoked entry. pub entry_did: String, /// DID of the entity that performed the revocation. pub revoked_by: String, /// Human-readable reason for revocation. pub reason: String, /// When the revocation occurred. pub revoked_at: chrono::DateTime, /// Current propagation status across shards. pub propagation_status: PropagationStatus } ``` Source line: `175`. ## gal::PropagationStatus [#galpropagationstatus] Status of revocation propagation across shards. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum PropagationStatus { /// Revocation initiated, not yet propagated. Pending, /// Revocation being propagated to shards. Propagating, /// Revocation fully propagated to all shards. Complete, } ``` Source line: `194`. ## gal::GalMerkleTree [#galgalmerkletree] A simple SHA-256 Merkle tree for GAL entries. Entries are hashed leaf-first, then combined pairwise up to the root. Supports inclusion proofs and verification. ```rust pub struct GalMerkleTree { } ``` Source line: `211`. ## gal::GalMerkleTree::new [#galgalmerkletreenew] Create a new empty Merkle tree. ```rust pub fn new() -> Self; ``` Source line: `218`. ## gal::GalMerkleTree::insert [#galgalmerkletreeinsert] Insert a GAL entry as a leaf in the tree. ```rust pub fn insert(&mut self, entry: &GalEntry); ``` Source line: `223`. ## gal::GalMerkleTree::len [#galgalmerkletreelen] Returns the number of leaves in the tree. ```rust pub fn len(&self) -> usize; ``` Source line: `228`. ## gal::GalMerkleTree::is\_empty [#galgalmerkletreeis_empty] Returns `true` if the tree has no leaves. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `233`. ## gal::GalMerkleTree::root [#galgalmerkletreeroot] Compute the Merkle root hash. Returns all-zeros for an empty tree. ```rust pub fn root(&self) -> [u8; 32]; ``` Source line: `238`. ## gal::GalMerkleTree::proof [#galgalmerkletreeproof] Generate an inclusion proof for the leaf at `index`. Returns `None` if `index` is out of bounds. ```rust pub fn proof(&self, index: usize) -> Option>>; ``` Source line: `248`. ## gal::GalMerkleTree::verify [#galgalmerkletreeverify] Verify an inclusion proof against a root hash. `index` is the original leaf position. ```rust pub fn verify(root: &[u8; 32], entry_hash: &[u8; 32], proof: &[Vec], index: usize) -> bool; ``` Source line: `258`. ## Source provenance [#source-provenance] Source: `mars-shard/src/gal.rs` · SHA-256 `6332d9bc8eb410ac0e85c3b452088bcdc4f73a52c749d7cc8eae737336f9c44e`. [Package overview](/libraries/mars-shard). # mars-shard URL: https://docs.mars.glass/libraries/mars-shard Markdown: https://docs.mars.glass/libraries/mars-shard.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json MARS-S prototype affinity, topology, shadow copies, resolution, and cross-shard coordination. MARS-S prototype affinity, topology, shadow copies, resolution, and cross-shard coordination. This crate is experimental. Its integration is feature-gated by mars-server/sharding and is separate from the PostgreSQL production reference. ## Package contract [#package-contract] Workspace version: **0.1.0**. Rust edition **2021**, minimum declared toolchain **1.81**, Apache-2.0 license. Protocol wire version stays **1.0.0**. Use the source checkout as the installation authority; package registry publication is not verified by this documentation build. In a consumer Cargo manifest, use an explicit path dependency to your checked-out crate. ```toml [dependencies] mars-shard = { path = "../mars/mars-shard" } ``` ## Feature flags [#feature-flags] | Feature | Enables | | ------- | ------- | No crate-specific feature flags are declared. ## Public root modules [#public-root-modules] `affinity`, `cross_shard`, `error`, `gal`, `lifecycle`, `resolution`, `shadow`, `topology`. Conditional availability follows the source attributes. ## Public module reference [#public-module-reference] | Module | Source | | ------------------------------------------------- | ------------------------------- | | [crate](/libraries/mars-shard/root) | `mars-shard/src/lib.rs` | | [affinity](/libraries/mars-shard/affinity) | `mars-shard/src/affinity.rs` | | [cross\_shard](/libraries/mars-shard/cross_shard) | `mars-shard/src/cross_shard.rs` | | [error](/libraries/mars-shard/error) | `mars-shard/src/error.rs` | | [gal](/libraries/mars-shard/gal) | `mars-shard/src/gal.rs` | | [lifecycle](/libraries/mars-shard/lifecycle) | `mars-shard/src/lifecycle.rs` | | [resolution](/libraries/mars-shard/resolution) | `mars-shard/src/resolution.rs` | | [shadow](/libraries/mars-shard/shadow) | `mars-shard/src/shadow.rs` | | [topology](/libraries/mars-shard/topology) | `mars-shard/src/topology.rs` | ## API documentation boundary [#api-documentation-boundary] The linked pages contain syntax-derived public declarations, method signatures, and documentation comments. They omit function bodies and constant values, and skip test-only modules. Compiler-resolved re-exports, trait resolution, and target availability require Rustdoc with the selected feature profile; no backend build or conformance tests ran here. # mars-shard · lifecycle URL: https://docs.mars.glass/libraries/mars-shard/lifecycle Markdown: https://docs.mars.glass/libraries/mars-shard/lifecycle.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-shard::lifecycle. **Package:** `mars-shard` · **Workspace version:** `0.1.0` · **Module:** `lifecycle` **Status: prototype / draft.** This is not the production registry topology. This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## lifecycle::LifecycleEvent [#lifecyclelifecycleevent] A lifecycle event describing a shard operation. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "camelCase")] pub enum LifecycleEvent { /// A shard is being split into two new shards. Split { source_shard: String, new_shard_a: String, new_shard_b: String, }, /// Two shards are being merged into one. Merge { shard_a: String, shard_b: String, target_shard: String, }, /// A shard is being migrated between clusters. Migrate { shard: String, from_cluster: String, to_cluster: String, }, } ``` Source line: `20`. ## lifecycle::OperationState [#lifecycleoperationstate] State machine for a lifecycle operation. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum OperationState { /// Operation has been created but not started. Initiated, /// Operation is actively executing. InProgress, /// Operation is finalizing (writing metadata, updating topology). Completing, /// Operation completed successfully. Complete, /// Operation failed with a reason. Failed(String), } ``` Source line: `47`. ## lifecycle::LifecycleOperation [#lifecyclelifecycleoperation] A tracked lifecycle operation. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LifecycleOperation { /// Unique operation ID. pub id: String, /// The lifecycle event being executed. pub event: LifecycleEvent, /// Current state of the operation. pub state: OperationState, /// When the operation was initiated. pub started_at: chrono::DateTime, /// When the operation completed (if it has). #[serde(skip_serializing_if = "Option::is_none")] pub completed_at: Option> } ``` Source line: `67`. ## lifecycle::LifecycleManager [#lifecyclelifecyclemanager] Manages shard split, merge, and migrate operations. ```rust pub struct LifecycleManager { } ``` Source line: `86`. ## lifecycle::LifecycleManager::new [#lifecyclelifecyclemanagernew] Create a new lifecycle manager with the given thresholds. * `split_threshold`: capacity fraction above which a shard should split (default 0.80). * `merge_threshold`: capacity fraction below which a shard should merge (default 0.20). ```rust pub fn new(split_threshold: f64, merge_threshold: f64) -> Self; ``` Source line: `100`. ## lifecycle::LifecycleManager::check\_split\_needed [#lifecyclelifecyclemanagercheck_split_needed] Check whether a shard's capacity exceeds the split threshold. ```rust pub fn check_split_needed(&self, shard: &ShardInfo) -> bool; ``` Source line: `130`. ## lifecycle::LifecycleManager::check\_merge\_needed [#lifecyclelifecyclemanagercheck_merge_needed] Check whether a shard's capacity is below the merge threshold. ```rust pub fn check_merge_needed(&self, shard: &ShardInfo) -> bool; ``` Source line: `135`. ## lifecycle::LifecycleManager::initiate\_split [#lifecyclelifecyclemanagerinitiate_split] Initiate a split operation for a shard. Creates two new shard IDs derived from the source shard. ```rust pub fn initiate_split(&mut self, shard_id: &str) -> Result; ``` Source line: `142`. ## lifecycle::LifecycleManager::initiate\_merge [#lifecyclelifecyclemanagerinitiate_merge] Initiate a merge operation combining two shards. ```rust pub fn initiate_merge( &mut self, shard_a: &str, shard_b: &str, ) -> Result; ``` Source line: `168`. ## lifecycle::LifecycleManager::initiate\_migrate [#lifecyclelifecyclemanagerinitiate_migrate] Initiate a migration operation. ```rust pub fn initiate_migrate( &mut self, shard_id: &str, from_cluster: &str, to_cluster: &str, ) -> Result; ``` Source line: `207`. ## lifecycle::LifecycleManager::advance [#lifecyclelifecyclemanageradvance] Advance a lifecycle operation to a new state. ```rust pub fn advance(&mut self, op_id: &str, new_state: OperationState) -> Result<(), ShardError>; ``` Source line: `237`. ## lifecycle::LifecycleManager::pending\_operations [#lifecyclelifecyclemanagerpending_operations] List all pending (non-complete, non-failed) operations. ```rust pub fn pending_operations(&self) -> Vec<&LifecycleOperation>; ``` Source line: `268`. ## lifecycle::LifecycleManager::all\_operations [#lifecyclelifecyclemanagerall_operations] List all operations (including completed and failed). ```rust pub fn all_operations(&self) -> &[LifecycleOperation]; ``` Source line: `281`. ## lifecycle::LifecycleManager::split\_threshold [#lifecyclelifecyclemanagersplit_threshold] Returns the split threshold. ```rust pub fn split_threshold(&self) -> f64; ``` Source line: `286`. ## lifecycle::LifecycleManager::merge\_threshold [#lifecyclelifecyclemanagermerge_threshold] Returns the merge threshold. ```rust pub fn merge_threshold(&self) -> f64; ``` Source line: `291`. ## Source provenance [#source-provenance] Source: `mars-shard/src/lifecycle.rs` · SHA-256 `1a0713b91233ac4dd92ade4240deb3ba285cef98732e485fd9e773fbee863341`. [Package overview](/libraries/mars-shard). # mars-shard · resolution URL: https://docs.mars.glass/libraries/mars-shard/resolution Markdown: https://docs.mars.glass/libraries/mars-shard/resolution.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-shard::resolution. **Package:** `mars-shard` · **Workspace version:** `0.1.0` · **Module:** `resolution` **Status: prototype / draft.** This is not the production registry topology. This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## resolution::CachedEntry [#resolutioncachedentry] A cached resolution result for a DID. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CachedEntry { /// The DID that was resolved. pub did: String, /// Content hash of the full entry in the shard. pub content_hash: String, /// The shard that holds the full entry. pub shard_id: String, /// Unix timestamp (seconds) when this was cached. pub cached_at: u64, /// Time-to-live in seconds. pub ttl: u64 } ``` Source line: `23`. ## resolution::CachedEntry::is\_expired [#resolutioncachedentryis_expired] Returns `true` if this cache entry has expired given the current time. ```rust pub fn is_expired(&self, now: u64) -> bool; ``` Source line: `38`. ## resolution::ResolutionResult [#resolutionresolutionresult] Outcome of a three-hop resolution. ```rust #[derive(Debug, Clone, PartialEq)] pub enum ResolutionResult { /// Found in the local cache. CacheHit(CachedEntry), /// Found by querying the primary shard. ShardHit { shard_id: String, content_hash: String, }, /// Found by querying GAL, then the assigned shard. GalLookup { shard_id: String, content_hash: String, }, /// DID not found at any hop. NotFound, /// DID has been revoked. Revoked(RevocationRecord), } ``` Source line: `49`. ## resolution::ResolutionCache [#resolutionresolutioncache] In-memory cache for resolved DIDs with TTL eviction. ```rust pub struct ResolutionCache { } ``` Source line: `73`. ## resolution::ResolutionCache::new [#resolutionresolutioncachenew] Create a new cache with the given capacity and default TTL. ```rust pub fn new(max_entries: usize, default_ttl: u64) -> Self; ``` Source line: `81`. ## resolution::ResolutionCache::get [#resolutionresolutioncacheget] Look up a DID in the cache. Returns `None` if missing or expired. ```rust pub fn get(&self, did: &str, now: u64) -> Option<&CachedEntry>; ``` Source line: `90`. ## resolution::ResolutionCache::put [#resolutionresolutioncacheput] Insert an entry into the cache. If the cache is full, evict expired entries first, then the oldest entry if still at capacity. ```rust pub fn put(&mut self, entry: CachedEntry); ``` Source line: `96`. ## resolution::ResolutionCache::invalidate [#resolutionresolutioncacheinvalidate] Invalidate (remove) a specific DID from the cache. ```rust pub fn invalidate(&mut self, did: &str); ``` Source line: `104`. ## resolution::ResolutionCache::stats [#resolutionresolutioncachestats] Returns `(current_entries, max_entries)`. ```rust pub fn stats(&self) -> (usize, usize); ``` Source line: `109`. ## resolution::ResolutionCache::default\_ttl [#resolutionresolutioncachedefault_ttl] Returns the default TTL in seconds. ```rust pub fn default_ttl(&self) -> u64; ``` Source line: `114`. ## resolution::Resolver [#resolutionresolver] Three-hop DID resolver with cache and topology awareness. The resolver holds a local cache and a reference to the shard topology. Actual shard I/O is simulated via the registered shard data and GAL data maps. ```rust pub struct Resolver { } ``` Source line: `154`. ## resolution::Resolver::new [#resolutionresolvernew] Create a new resolver with the given cache parameters. ```rust pub fn new(cache_size: usize, cache_ttl: u64) -> Self; ``` Source line: `166`. ## resolution::Resolver::register\_shard\_entry [#resolutionresolverregister_shard_entry] Register shard data for testing/simulation. ```rust pub fn register_shard_entry(&mut self, shard_id: &str, did: &str, content_hash: &str); ``` Source line: `176`. ## resolution::Resolver::register\_gal\_entry [#resolutionresolverregister_gal_entry] Register GAL data for testing/simulation. ```rust pub fn register_gal_entry(&mut self, did: &str, shard_id: &str, content_hash: &str); ``` Source line: `184`. ## resolution::Resolver::register\_revocation [#resolutionresolverregister_revocation] Register a revocation. ```rust pub fn register_revocation(&mut self, record: RevocationRecord); ``` Source line: `192`. ## resolution::Resolver::resolve [#resolutionresolverresolve] Three-hop resolution: 1. Check local cache -> if found and not expired, return `CacheHit`. 2. Query primary shard -> if found, cache and return `ShardHit`. 3. Query GAL on-chain -> get shard assignment, query that shard. At ANY hop: if revocation found, abort immediately with `Revoked`. ```rust pub fn resolve(&mut self, did: &str, now: u64) -> ResolutionResult; ``` Source line: `203`. ## resolution::Resolver::cache\_entry [#resolutionresolvercache_entry] Directly cache an entry (for pre-warming). ```rust pub fn cache_entry(&mut self, entry: CachedEntry); ``` Source line: `251`. ## resolution::Resolver::invalidate [#resolutionresolverinvalidate] Invalidate a cached DID. ```rust pub fn invalidate(&mut self, did: &str); ``` Source line: `256`. ## resolution::Resolver::cache\_stats [#resolutionresolvercache_stats] Returns cache statistics. ```rust pub fn cache_stats(&self) -> (usize, usize); ``` Source line: `261`. ## Source provenance [#source-provenance] Source: `mars-shard/src/resolution.rs` · SHA-256 `1b3e6d2f417b2462ffac928e855ab1a5540beecff337f32908ce613b7f5ef3a3`. [Package overview](/libraries/mars-shard). # mars-shard · crate URL: https://docs.mars.glass/libraries/mars-shard/root Markdown: https://docs.mars.glass/libraries/mars-shard/root.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json MARS-S prototype affinity, topology, shadow copies, resolution, and cross-shard coordination. **Package:** `mars-shard` · **Workspace version:** `0.1.0` · **Module:** `crate` **Status: prototype / draft.** This is not the production registry topology. This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## affinity [#affinity] ```rust pub mod affinity; ``` Source line: `8`. ## cross\_shard [#cross_shard] ```rust pub mod cross_shard; ``` Source line: `9`. ## error [#error] ```rust pub mod error; ``` Source line: `10`. ## gal [#gal] ```rust pub mod gal; ``` Source line: `11`. ## lifecycle [#lifecycle] ```rust pub mod lifecycle; ``` Source line: `12`. ## resolution [#resolution] ```rust pub mod resolution; ``` Source line: `13`. ## shadow [#shadow] ```rust pub mod shadow; ``` Source line: `14`. ## topology [#topology] ```rust pub mod topology; ``` Source line: `15`. ## Source provenance [#source-provenance] Source: `mars-shard/src/lib.rs` · SHA-256 `24081c9c1ca65150128e71504764df9a681b4a4c765c00d8429426a744bb0ece`. [Package overview](/libraries/mars-shard). # mars-shard · shadow URL: https://docs.mars.glass/libraries/mars-shard/shadow Markdown: https://docs.mars.glass/libraries/mars-shard/shadow.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-shard::shadow. **Package:** `mars-shard` · **Workspace version:** `0.1.0` · **Module:** `shadow` **Status: prototype / draft.** This is not the production registry topology. This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## shadow::ShadowConfig [#shadowshadowconfig] Configuration for shadow shard replication. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShadowConfig { /// Minimum number of shadow copies per primary (must be >= 1). pub min_shadows: usize, /// Maximum number of shadow copies per primary. pub max_shadows: usize, /// Whether shadows must be in different clusters than the primary. #[serde(default = "default_true")] pub require_different_clusters: bool } ``` Source line: `21`. ## shadow::ShadowStatus [#shadowshadowstatus] Replication status of a shadow shard. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ShadowStatus { /// Shadow is catching up with the primary. Syncing, /// Shadow is fully synced and serving reads. Active, /// Shadow has fallen behind the primary. Stale, /// Shadow is being promoted to primary. Promoting, } ``` Source line: `51`. ## shadow::ShadowShard [#shadowshadowshard] A shadow (replica) shard tracking replication state. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShadowShard { /// Unique ID for this shadow shard. pub shadow_id: String, /// ID of the primary shard being replicated. pub primary_shard_id: String, /// Cluster where this shadow is deployed. pub cluster_id: String, /// Region where this shadow is deployed. pub region: String, /// Last replicated sequence number. pub last_sync_sequence: u64, /// Current replication status. pub status: ShadowStatus } ``` Source line: `69`. ## shadow::ShadowManager [#shadowshadowmanager] Manages shadow shard assignment, promotion, and staleness tracking. ```rust pub struct ShadowManager { } ``` Source line: `89`. ## shadow::ShadowManager::new [#shadowshadowmanagernew] Create a new shadow manager with the given configuration. ```rust pub fn new(config: ShadowConfig) -> Self; ``` Source line: `99`. ## shadow::ShadowManager::assign\_shadows [#shadowshadowmanagerassign_shadows] Assign shadow shards to a primary shard based on topology. Picks candidate shards from different clusters (if configured) and creates shadow entries up to `max_shadows`. ```rust pub fn assign_shadows( &mut self, primary_shard_id: &str, topology: &ShardTopology, ) -> Result, ShardError>; ``` Source line: `111`. ## shadow::ShadowManager::promote\_shadow [#shadowshadowmanagerpromote_shadow] Promote the best shadow to primary status. Selects the shadow with the highest `last_sync_sequence` and sets it to `Promoting` status. Returns the promoted shadow. ```rust pub fn promote_shadow(&mut self, primary_shard_id: &str) -> Result; ``` Source line: `169`. ## shadow::ShadowManager::sync\_update [#shadowshadowmanagersync_update] Update a shadow's replication progress. ```rust pub fn sync_update(&mut self, shadow_id: &str, sequence: u64) -> Result<(), ShardError>; ``` Source line: `196`. ## shadow::ShadowManager::shadows\_for [#shadowshadowmanagershadows_for] List shadows for a primary shard. ```rust pub fn shadows_for(&self, primary_shard_id: &str) -> Vec<&ShadowShard>; ``` Source line: `226`. ## shadow::ShadowManager::stale\_shadows [#shadowshadowmanagerstale_shadows] Find shadows that have fallen behind by more than `max_lag` sequences. Compares each shadow's `last_sync_sequence` against the primary's current sequence (approximated as the max across all shadows + max\_lag). ```rust pub fn stale_shadows(&self, max_lag: u64) -> Vec<&ShadowShard>; ``` Source line: `237`. ## Source provenance [#source-provenance] Source: `mars-shard/src/shadow.rs` · SHA-256 `2fa83f34f08d190d42e8b21009b4f2ce28d276b61d9a6ef532877fb13d62eefd`. [Package overview](/libraries/mars-shard). # mars-shard · topology URL: https://docs.mars.glass/libraries/mars-shard/topology Markdown: https://docs.mars.glass/libraries/mars-shard/topology.md Status: draft Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-shard::topology. **Package:** `mars-shard` · **Workspace version:** `0.1.0` · **Module:** `topology` **Status: prototype / draft.** This is not the production registry topology. This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## topology::ShardStatus [#topologyshardstatus] Operational status of a shard. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ShardStatus { /// Shard is operational and accepting reads/writes. Active, /// Shard is in the process of splitting into two. Splitting, /// Shard is being merged with another shard. Merging, /// Shard data is being migrated to another cluster. Migrating, /// Shard is not available. Offline, } ``` Source line: `18`. ## topology::ShardInfo [#topologyshardinfo] Metadata about a single shard in the topology. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShardInfo { /// Unique shard identifier. pub shard_id: String, /// Cluster this shard belongs to. pub cluster_id: String, /// Region where this shard is deployed. pub region: String, /// Current operational status. pub status: ShardStatus, /// Capacity utilization as a fraction (0.0 to 1.0). pub capacity_pct: f64, /// Number of entries stored in this shard. pub entry_count: u64, /// IDs of shadow (replica) shards. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub shadow_shard_ids: Vec, /// Primary node responsible for this shard. #[serde(skip_serializing_if = "Option::is_none")] pub primary_node: Option, /// When this shard was created. pub created_at: chrono::DateTime } ``` Source line: `38`. ## topology::ShardTopology [#topologyshardtopology] The complete shard topology map. Tracks all shards and their organization into clusters and regions. ```rust pub struct ShardTopology { } ``` Source line: `68`. ## topology::ShardTopology::new [#topologyshardtopologynew] Create a new empty topology. ```rust pub fn new() -> Self; ``` Source line: `76`. ## topology::ShardTopology::add\_shard [#topologyshardtopologyadd_shard] Add a shard to the topology. Returns an error if a shard with the same ID already exists. ```rust pub fn add_shard(&mut self, info: ShardInfo) -> Result<(), ShardError>; ``` Source line: `87`. ## topology::ShardTopology::remove\_shard [#topologyshardtopologyremove_shard] Remove a shard from the topology. Returns an error if the shard does not exist. ```rust pub fn remove_shard(&mut self, shard_id: &str) -> Result<(), ShardError>; ``` Source line: `135`. ## topology::ShardTopology::get\_shard [#topologyshardtopologyget_shard] Get a shard by ID. ```rust pub fn get_shard(&self, shard_id: &str) -> Option<&ShardInfo>; ``` Source line: `160`. ## topology::ShardTopology::get\_shard\_mut [#topologyshardtopologyget_shard_mut] Get a mutable reference to a shard by ID. ```rust pub fn get_shard_mut(&mut self, shard_id: &str) -> Option<&mut ShardInfo>; ``` Source line: `165`. ## topology::ShardTopology::shards\_in\_cluster [#topologyshardtopologyshards_in_cluster] List all shards in a cluster. ```rust pub fn shards_in_cluster(&self, cluster_id: &str) -> Vec<&ShardInfo>; ``` Source line: `170`. ## topology::ShardTopology::shards\_in\_region [#topologyshardtopologyshards_in_region] List all shards in a region (across all clusters in that region). ```rust pub fn shards_in_region(&self, region: &str) -> Vec<&ShardInfo>; ``` Source line: `178`. ## topology::ShardTopology::active\_shards [#topologyshardtopologyactive_shards] List all shards with `Active` status. ```rust pub fn active_shards(&self) -> Vec<&ShardInfo>; ``` Source line: `191`. ## topology::ShardTopology::overloaded\_shards [#topologyshardtopologyoverloaded_shards] List shards whose capacity exceeds the given threshold. ```rust pub fn overloaded_shards(&self, threshold: f64) -> Vec<&ShardInfo>; ``` Source line: `199`. ## topology::ShardTopology::underloaded\_shards [#topologyshardtopologyunderloaded_shards] List shards whose capacity is below the given threshold. ```rust pub fn underloaded_shards(&self, threshold: f64) -> Vec<&ShardInfo>; ``` Source line: `207`. ## topology::ShardTopology::total\_entries [#topologyshardtopologytotal_entries] Total number of entries across all shards. ```rust pub fn total_entries(&self) -> u64; ``` Source line: `215`. ## topology::ShardTopology::shard\_count [#topologyshardtopologyshard_count] Total number of shards in the topology. ```rust pub fn shard_count(&self) -> usize; ``` Source line: `222`. ## topology::ShardTopology::cluster\_count [#topologyshardtopologycluster_count] Total number of clusters. ```rust pub fn cluster_count(&self) -> usize; ``` Source line: `227`. ## topology::ShardTopology::region\_count [#topologyshardtopologyregion_count] Total number of regions. ```rust pub fn region_count(&self) -> usize; ``` Source line: `232`. ## Source provenance [#source-provenance] Source: `mars-shard/src/topology.rs` · SHA-256 `fa790e6d4372ac79f0fa195271074df00abea570b5920af8afe5c48ef5d4c8db`. [Package overview](/libraries/mars-shard). # mars-protocol · anchor URL: https://docs.mars.glass/libraries/mars-protocol/anchor Markdown: https://docs.mars.glass/libraries/mars-protocol/anchor.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::anchor. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `anchor` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## Module condition [#module-condition] ```rust #[cfg(feature = "sigil")] ``` ## anchor::AnchorRecord [#anchoranchorrecord] A confirmed on-chain anchor for a MARS entry. Created after a transaction is committed to the Sigil blockchain, this record links a MARS entry to a specific block and transaction hash, and optionally includes a Merkle proof for independent verification. ```rust #[cfg(feature = "sigil")] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct AnchorRecord { /// DID of the anchored entry. pub entry_did: String, /// SHA-256 content hash of the entry's `item_data`. pub item_data_hash: String, /// Block height at which the anchor was committed. pub block_height: u64, /// Transaction hash on the Sigil chain. pub tx_hash: String, /// Timestamp when the anchor was created on-chain. pub anchor_time: chrono::DateTime, /// Optional Merkle proof for independent verification. #[serde(skip_serializing_if = "Option::is_none")] pub proof: Option } ``` Source line: `24`. ## anchor::MerkleProof [#anchormerkleproof] A Merkle inclusion proof linking a leaf hash to a root hash. Verifiers walk the `path` from the `leaf_hash` to the `root`, combining each `ProofNode` in sequence according to its `direction`. ## MARS Merkle Proof v1 encoding [#mars-merkle-proof-v1-encoding] `root`, `leafHash`, and every sibling `hash` are textual lowercase hexadecimal SHA-256 digests. Each level hashes the UTF-8 bytes of the concatenated left and right hexadecimal strings, then lowercase-hex encodes the resulting digest before processing the next level. This is a compatibility contract; it is intentionally not raw 32-byte digest concatenation. ```rust #[cfg(feature = "sigil")] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct MerkleProof { /// Merkle root hash. pub root: String, /// Ordered path of sibling hashes from leaf to root. pub path: Vec, /// Hash of the leaf being proved. pub leaf_hash: String } ``` Source line: `60`. ## anchor::ProofNode [#anchorproofnode] A single node in a Merkle proof path. ```rust #[cfg(feature = "sigil")] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct ProofNode { /// Sibling hash at this level of the tree. pub hash: String, /// Whether this sibling is to the left or right of the current node. pub direction: Direction } ``` Source line: `77`. ## anchor::Direction [#anchordirection] Direction of a sibling node in a Merkle proof path. ```rust #[cfg(feature = "sigil")] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub enum Direction { /// Sibling is on the left. Left, /// Sibling is on the right. Right, } ``` Source line: `92`. ## anchor::AnchorStatus [#anchoranchorstatus] Status of an on-chain anchor operation. ```rust #[cfg(feature = "sigil")] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", tag = "status")] pub enum AnchorStatus { /// Transaction submitted but not yet confirmed. Pending, /// Transaction confirmed on-chain. Confirmed, /// Anchor operation failed. Failed { /// Human-readable failure reason. reason: String, }, } ``` Source line: `107`. ## anchor::AnchorRequest [#anchoranchorrequest] A request to anchor a MARS entry on the Sigil chain. ```rust #[cfg(feature = "sigil")] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct AnchorRequest { /// DID of the entry to anchor. pub entry_did: String, /// SHA-256 content hash of the entry's `item_data`. pub item_data_hash: String, /// DID of the publisher submitting the anchor. pub publisher_did: String, /// Ed25519 signature over the canonical anchor payload. pub signature: String } ``` Source line: `127`. ## anchor::AnchorResponse [#anchoranchorresponse] Response to an anchor submission. ```rust #[cfg(feature = "sigil")] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct AnchorResponse { /// Transaction hash assigned by the Sigil chain. pub tx_hash: String, /// Current status of the anchor operation. pub status: AnchorStatus } ``` Source line: `146`. ## anchor::verify\_merkle\_proof [#anchorverify_merkle_proof] Verify a Merkle proof by recomputing the root from the leaf hash. Walks the proof path from `leaf_hash` to the root, hashing left/right hexadecimal UTF-8 strings at each level using SHA-256. Returns `true` if the recomputed lowercase-hex string matches `proof.root`. See \[`MerkleProof`] for the exact v1 encoding contract. ```rust #[cfg(feature = "sigil")] pub fn verify_merkle_proof(proof: &MerkleProof) -> bool; ``` Source line: `163`. ## anchor::AnchorError [#anchoranchorerror] Errors returned by \[`SigilAnchorClient`]. ```rust #[cfg(feature = "sigil")] #[derive(Debug, thiserror::Error)] pub enum AnchorError { /// Network / transport failure. #[error("transport error: {0}")] Transport(String), /// The Sigil node returned a JSON-RPC error. #[error("sigil rpc error: {code}: {message}")] Rpc { /// JSON-RPC error code. code: i64, /// Human-readable message. message: String, }, /// Anchor submission rejected by the chain. #[error("anchor rejected: {0}")] Rejected(String), /// Invalid response payload. #[error("invalid response: {0}")] InvalidResponse(String), } ``` Source line: `202`. ## anchor::SigilAnchorClient [#anchorsigilanchorclient] Async client that mediates real Sigil RPC anchor submission and queries. Resolvers MUST call \[`check_revocation`] first on every resolution path — the revocation-first invariant from the GAL design doc. The trait does not enforce that ordering; the caller does. All query methods return `Option<serde_json::Value>` (or `serde_json::Value` for the topology snapshot) so this crate can stay free of a `sigil-core` dependency. Higher layers (`sigil-sdk`, `oas-resolve`) deserialize into the canonical typed records. ```rust #[cfg(feature = "sigil")] #[async_trait::async_trait] pub trait SigilAnchorClient: Send + Sync { /// Submit a MARS entry anchor to the Sigil chain. async fn submit_anchor(&self, req: AnchorRequest) -> Result; /// Fetch the typed `HmrAnchor` JSON for a DID, or `None` if absent. async fn get_hmr(&self, did: &str) -> Result, AnchorError>; /// Fetch the typed `MhrAnchor` JSON for a DID, or `None` if absent. async fn get_mhr(&self, did: &str) -> Result, AnchorError>; /// Fetch the typed `EnrAnchor` JSON for a DID, or `None` if absent. async fn get_enr(&self, did: &str) -> Result, AnchorError>; /// Fetch the typed `OrgLineageRoot` JSON for an org DID, or `None` if /// absent. async fn get_org_root(&self, org_did: &str) -> Result, AnchorError>; /// Fetch the `ShardAssignment` (and any topology lineage) for a subject /// DID, or `None` if absent. async fn get_shard_assignment( &self, did: &str, ) -> Result, AnchorError>; /// **Revocation-first**: fetch the `RevocationStatus` JSON for a DID. /// Always succeeds; an unrevoked DID returns /// `{ "revoked": false, "record": null }`. async fn check_revocation(&self, did: &str) -> Result; /// Fetch the full `ShardTopologyEntry` snapshot. async fn get_shard_topology(&self) -> Result; } ``` Source line: `233`. ## anchor::MockSigilAnchorClient [#anchormocksigilanchorclient] Deterministic in-memory `SigilAnchorClient` impl for development and integration tests. Building a release with `--features prod` and `--features mock-anchor` triggers a top-of-crate `compile_error!`, so the mock cannot ship to production by accident. ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub struct MockSigilAnchorClient { } ``` Source line: `277`. ## anchor::MockSigilAnchorClient::new [#anchormocksigilanchorclientnew] Create an empty mock client. ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub fn new() -> Self; ``` Source line: `305`. ## anchor::MockSigilAnchorClient::insert\_hmr [#anchormocksigilanchorclientinsert_hmr] Pre-populate an HMR record at the given DID. ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub fn insert_hmr(&self, did: &str, record: serde_json::Value) -> Result<(), AnchorError>; ``` Source line: `316`. ## anchor::MockSigilAnchorClient::insert\_mhr [#anchormocksigilanchorclientinsert_mhr] Pre-populate an MHR record. ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub fn insert_mhr(&self, did: &str, record: serde_json::Value) -> Result<(), AnchorError>; ``` Source line: `322`. ## anchor::MockSigilAnchorClient::insert\_enr [#anchormocksigilanchorclientinsert_enr] Pre-populate an ENR record. ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub fn insert_enr(&self, did: &str, record: serde_json::Value) -> Result<(), AnchorError>; ``` Source line: `328`. ## anchor::MockSigilAnchorClient::insert\_org\_root [#anchormocksigilanchorclientinsert_org_root] Pre-populate an org lineage root. ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub fn insert_org_root( &self, org_did: &str, record: serde_json::Value, ) -> Result<(), AnchorError>; ``` Source line: `334`. ## anchor::MockSigilAnchorClient::insert\_shard\_assignment [#anchormocksigilanchorclientinsert_shard_assignment] Pre-populate a shard assignment. ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub fn insert_shard_assignment( &self, did: &str, record: serde_json::Value, ) -> Result<(), AnchorError>; ``` Source line: `346`. ## anchor::MockSigilAnchorClient::insert\_revocation [#anchormocksigilanchorclientinsert_revocation] Mark a DID as revoked. ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub fn insert_revocation( &self, did: &str, record: serde_json::Value, ) -> Result<(), AnchorError>; ``` Source line: `356`. ## anchor::MockSigilAnchorClient::set\_topology [#anchormocksigilanchorclientset_topology] Set the full topology snapshot. ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub fn set_topology(&self, snapshot: serde_json::Value) -> Result<(), AnchorError>; ``` Source line: `369`. ## anchor::MockSigilAnchorClient::anchor\_for [#anchormocksigilanchorclientanchor_for] Look up an anchor record by entry DID (for tests). ```rust #[cfg(feature = "sigil")] #[cfg(feature = "mock-anchor")] pub fn anchor_for(&self, entry_did: &str) -> Result, AnchorError>; ``` Source line: `375`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/anchor.rs` · SHA-256 `01fe89586dcca37ad30197952dad161545b2d648d1e90aa403645af3fefe9f7a`. [Package overview](/libraries/mars-protocol). # mars-protocol · anchoring URL: https://docs.mars.glass/libraries/mars-protocol/anchoring Markdown: https://docs.mars.glass/libraries/mars-protocol/anchoring.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::anchoring. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `anchoring` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## anchoring::AnchorState [#anchoringanchorstate] Registry-managed lifecycle of an anchor intent or entry projection. ```rust #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "snake_case")] pub enum AnchorState { /// No anchor has been requested for the current entry snapshot. #[default] Unanchored, /// Durable work exists and is ready for a worker. Pending, /// A provider accepted the submission but has not confirmed it. Submitted, /// The provider reported final confirmation. Confirmed, /// The latest attempt failed and is eligible for a bounded retry. Failed, /// Retry policy or an administrator ended processing permanently. Abandoned, } ``` Source line: `13`. ## anchoring::AnchorState::as\_str [#anchoringanchorstateas_str] Stable database and metric label. ```rust #[must_use] pub const fn as_str(self) -> &'static str; ``` Source line: `32`. ## anchoring::AnchorState::is\_confirmed [#anchoringanchorstateis_confirmed] Whether public discovery may expose this entry when anchoring is mandatory. ```rust #[must_use] pub const fn is_confirmed(self) -> bool; ``` Source line: `46`. ## anchoring::AnchorOutboxState [#anchoringanchoroutboxstate] Durable outbox state, including the internal worker-lease transition. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "snake_case")] pub enum AnchorOutboxState { Pending, Claimed, Submitted, Confirmed, Failed, Abandoned, } ``` Source line: `55`. ## anchoring::AnchorOutboxState::as\_str [#anchoringanchoroutboxstateas_str] ```rust #[must_use] pub const fn as_str(self) -> &'static str; ``` Source line: `66`. ## anchoring::AnchorOutboxState::projection [#anchoringanchoroutboxstateprojection] Entry projection corresponding to this internal outbox state. ```rust #[must_use] pub const fn projection(self) -> AnchorState; ``` Source line: `79`. ## anchoring::AnchorOperation [#anchoringanchoroperation] Registry mutation represented by an anchor intent. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "snake_case")] pub enum AnchorOperation { Create, Update, Revoke, Transfer, Attest, } ``` Source line: `94`. ## anchoring::AnchorOperation::as\_str [#anchoringanchoroperationas_str] Stable database and wire label. ```rust #[must_use] pub const fn as_str(self) -> &'static str; ``` Source line: `105`. ## anchoring::AnchorReceiptState [#anchoringanchorreceiptstate] State represented by an immutable adapter receipt. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "snake_case")] pub enum AnchorReceiptState { Submitted, Confirmed, } ``` Source line: `120`. ## anchoring::AnchorReceiptState::as\_str [#anchoringanchorreceiptstateas_str] ```rust #[must_use] pub const fn as_str(self) -> &'static str; ``` Source line: `127`. ## anchoring::AnchorReceiptState::outbox\_state [#anchoringanchorreceiptstateoutbox_state] ```rust #[must_use] pub const fn outbox_state(self) -> AnchorOutboxState; ``` Source line: `135`. ## anchoring::AnchorReceiptRecord [#anchoringanchorreceiptrecord] One immutable observation returned by an anchor adapter. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct AnchorReceiptRecord { /// Adapter-defined idempotency key for this observation. pub receipt_key: String, /// Provider-neutral external transaction or operation identifier. pub transaction_id: String, /// Submitted or confirmed state represented by this receipt. pub state: AnchorReceiptState, /// Optional finalized ledger height. #[serde(skip_serializing_if = "Option::is_none")] pub block_height: Option, /// Optional provider-neutral proof document. #[serde(skip_serializing_if = "Option::is_none")] pub proof: Option, /// Time the adapter observed this state. pub observed_at: chrono::DateTime } ``` Source line: `147`. ## anchoring::AnchorStatusRecord [#anchoringanchorstatusrecord] Persisted status of one durable anchor intent. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct AnchorStatusRecord { pub intent_id: String, pub entry_did: String, pub sequence: u64, pub operation: AnchorOperation, pub state: AnchorOutboxState, pub attempts: u32, pub available_at: chrono::DateTime, #[serde(skip_serializing_if = "Option::is_none")] pub transaction_id: Option, pub created_at: chrono::DateTime, pub updated_at: chrono::DateTime, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub receipts: Vec } ``` Source line: `168`. ## anchoring::AnchorListQuery [#anchoringanchorlistquery] Query parameters for `GET /v1/anchors/{did}`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] #[cfg_attr( feature = "contracts", derive(schemars::JsonSchema, utoipa::IntoParams) )] #[cfg_attr(feature = "contracts", into_params(parameter_in = Query))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct AnchorListQuery { /// Maximum number of anchor records to return. The server clamps this to /// its configured maximum page size. #[cfg_attr(feature = "contracts", schemars(range(min = 1)))] #[cfg_attr(feature = "contracts", param(minimum = 1))] pub limit: Option, /// Opaque URL-safe cursor returned by the preceding page. /// /// The cursor identifies the last-seen `(sequence, createdAt, intentId)` /// tuple. Clients must echo it unchanged and must not construct cursors. #[cfg_attr( feature = "contracts", schemars(length(min = 1, max = 2048), regex(pattern = r"^[A-Za-z0-9_-]+$")) )] #[cfg_attr( feature = "contracts", param(min_length = 1, max_length = 2048, pattern = r"^[A-Za-z0-9_-]+$") )] pub cursor: Option } ``` Source line: `192`. ## anchoring::AnchorListResponse [#anchoringanchorlistresponse] Response body for `GET /v1/anchors/{did}`. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct AnchorListResponse { pub entry_did: String, pub anchor_state: AnchorState, /// Anchor records in stable ascending `(sequence, createdAt, intentId)` /// order. pub records: Vec, /// Opaque last-seen tuple to pass to the next request, or `null` on the /// final page. pub cursor: Option, /// Whether another page exists after this response. pub has_more: bool } ``` Source line: `217`. ## anchoring::AnchorControlResponse [#anchoringanchorcontrolresponse] Response body for an administrative retry or abandon transition. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct AnchorControlResponse { pub intent_id: String, pub state: AnchorState } ``` Source line: `234`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/anchoring.rs` · SHA-256 `52708945a65b388171e50ade51a54ea772d888e206b97ed0ac40052ff8f3e072`. [Package overview](/libraries/mars-protocol). # mars-protocol · api URL: https://docs.mars.glass/libraries/mars-protocol/api Markdown: https://docs.mars.glass/libraries/mars-protocol/api.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::api. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `api` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## api::DiscoverRequest [#apidiscoverrequest] Request body for `POST /v1/discover`. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct DiscoverRequest { /// Exact canonical [`crate::entry::EntryType`] name. Omit to search every /// entry type; clause fragments and aliases are rejected. pub entry_type: Option, /// Filter conditions joined with logical AND. #[serde(default)] pub conditions: Vec, /// Maximum number of results. pub limit: Option, /// Opaque, expiring HMAC-authenticated keyset cursor from the preceding page. #[serde(skip_serializing_if = "Option::is_none")] pub cursor: Option } ``` Source line: `19`. ## api::DiscoverCondition [#apidiscovercondition] A single structured discovery filter. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct DiscoverCondition { /// Allowlisted canonical field path evaluated by the structured API. /// Arbitrary `itemData` traversal is available only through raw MARS-QL. pub field: String, /// Canonical operator compatible with the selected field's value type. pub op: String, /// Typed scalar or bounded array required by the selected field/operator. pub value: serde_json::Value } ``` Source line: `37`. ## api::MarsQlRequest [#apimarsqlrequest] Request body for `POST /v1/discover/marsql`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct MarsQlRequest { /// A MARS-QL `DISCOVER` expression. pub query: String } ``` Source line: `51`. ## api::TransferOfferRequest [#apitransferofferrequest] Request body for creating a signed transfer offer. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct TransferOfferRequest { /// DID invited to become the entry's publisher. pub recipient_did: String, /// Current entry sequence covered by the owner's signature. pub entry_sequence: u64, /// Server-verifiable expiry for this offer. pub expires_at: chrono::DateTime, /// Owner signature over the canonical transfer-offer payload. pub signature: EntrySignature } ``` Source line: `60`. ## api::TransferRequest [#apitransferrequest] Backward-compatible Rust alias for the former direct-transfer request. The HTTP route now creates an offer; it never changes ownership directly. ```rust pub type TransferRequest = TransferOfferRequest; ``` Source line: `74`. ## api::TransferOffer [#apitransferoffer] Persisted transfer-offer state returned by transfer endpoints. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct TransferOffer { /// Registry-generated immutable offer identifier. pub offer_id: String, /// Entry whose ownership may change. pub entry_did: String, /// Current owner derived from the authenticated principal. pub owner_did: String, /// Intended recipient. pub recipient_did: String, /// Entry sequence signed by the owner. pub entry_sequence: u64, /// Offer creation time. pub created_at: chrono::DateTime, /// Offer expiry. pub expires_at: chrono::DateTime, /// Current state. pub status: TransferOfferStatus, /// Owner's signature over the offer payload. pub owner_signature: EntrySignature } ``` Source line: `80`. ## api::TransferOfferStatus [#apitransferofferstatus] Closed transfer-offer state machine. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "snake_case")] pub enum TransferOfferStatus { Offered, Accepted, Declined, Expired, } ``` Source line: `105`. ## api::TransferAcceptRequest [#apitransferacceptrequest] Request body for accepting a transfer offer. `entry` must preserve every publisher-authored field from the offered snapshot, bind `publisherDid` and its signature key controller to the authenticated recipient, advance the registry sequence, and omit registry-managed `verifiableAttestations`. The recipient must re-sign the complete canonical publisher payload; the owner's offer signature never substitutes for the recipient entry signature. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct TransferAcceptRequest { /// Complete replacement entry signed by the recipient. pub entry: MarsEntry } ``` Source line: `123`. ## api::TransferDeclineRequest [#apitransferdeclinerequest] Request body for declining a transfer offer. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct TransferDeclineRequest { /// Optional non-authoritative explanation retained in private audit data. pub reason: Option } ``` Source line: `132`. ## api::AttestationRequest [#apiattestationrequest] Request body for `POST /v1/attestations`. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct AttestationRequest { /// DID of the entry receiving the attestation. pub entry_did: String, /// Verifiable attestation payload. pub attestation: serde_json::Value } ``` Source line: `141`. ## api::AttestationQuery [#apiattestationquery] Query controls for reading separately stored attestations. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[cfg_attr( feature = "contracts", derive(schemars::JsonSchema, utoipa::IntoParams) )] #[cfg_attr(feature = "contracts", into_params(parameter_in = Query))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct AttestationQuery { /// Include credentials whose expiration date has passed. #[serde(default)] pub include_expired: bool, /// Include credentials revoked in the local registry. #[serde(default)] pub include_revoked: bool } ``` Source line: `156`. ## api::VerifiableAttestationRecord [#apiverifiableattestationrecord] Canonical, separately stored OAS verifiable attestation. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct VerifiableAttestationRecord { /// SHA-256 identifier of the JCS-canonical credential. pub attestation_id: String, /// Subject entry DID. pub entry_did: String, /// Issuer DID derived from and bound to the authenticated principal. pub issuer_did: String, /// Canonical OAS Verifiable Credential. pub credential: serde_json::Value, /// Credential issuance time. pub issued_at: chrono::DateTime, /// Optional credential expiration time. pub expires_at: Option>, /// Local revocation time, when revoked. pub revoked_at: Option>, /// Registry acceptance time. pub accepted_at: chrono::DateTime } ``` Source line: `169`. ## api::ReportRequest [#apireportrequest] Request body for `POST /v1/report`. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ReportRequest { /// DID of the reported entry. pub entry_did: String, /// Human-readable report reason. pub reason: String, /// Optional supporting evidence. pub evidence: Option } ``` Source line: `192`. ## api::BondProvisionRequest [#apibondprovisionrequest] Admin request for provisioning a registry-local bond. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct BondProvisionRequest { pub bond_id: String, pub publisher_did: String, pub entry_did: String, pub amount: BondAmount, pub currency: String, pub status: BondStatus } ``` Source line: `205`. ## api::FederationPeerUpdateRequest [#apifederationpeerupdaterequest] Peer-controlled request for registering or changing its endpoint metadata. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct FederationPeerUpdateRequest { pub endpoint: String, pub grpc_endpoint: Option, #[serde(default)] pub agreement_ids: Vec } ``` Source line: `218`. ## api::ReportResponse [#apireportresponse] Response body for a successfully accepted report. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct ReportResponse { /// Stable acceptance state. pub status: ReportStatus, /// DID of the reported entry. pub entry_did: String } ``` Source line: `229`. ## api::ReportStatus [#apireportstatus] Closed state set for accepted reports. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub enum ReportStatus { /// The report was accepted and recorded. Reported, } ``` Source line: `240`. ## api::EntryVersionsQuery [#apientryversionsquery] Query parameters for `GET /v1/entries/{did}/versions`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] #[cfg_attr( feature = "contracts", derive(schemars::JsonSchema, utoipa::IntoParams) )] #[cfg_attr(feature = "contracts", into_params(parameter_in = Query))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct EntryVersionsQuery { /// Maximum number of versions to return. The server clamps this to its /// configured maximum page size. #[cfg_attr(feature = "contracts", schemars(range(min = 1)))] #[cfg_attr(feature = "contracts", param(minimum = 1))] pub limit: Option, /// Registry sequence of the last version returned by the preceding page. /// /// Clients must treat the value as opaque and echo it unchanged. #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^[1-9][0-9]*$")))] #[cfg_attr(feature = "contracts", param(pattern = r"^[1-9][0-9]*$"))] pub cursor: Option } ``` Source line: `253`. ## api::EntryVersionsResponse [#apientryversionsresponse] Response body for `GET /v1/entries/{did}/versions`. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct EntryVersionsResponse { /// DID shared by every returned version. pub entry_did: String, /// Entry snapshots ordered newest first. pub versions: Vec, /// Total number of stored versions for this DID. pub total_count: u64, /// Last-seen registry sequence to pass to the next request, or `null` on /// the final page. pub cursor: Option, /// Whether another page exists after this response. pub has_more: bool } ``` Source line: `271`. ## api::EntryLineageResponse [#apientrylineageresponse] Response body for `GET /v1/entries/{did}/lineage`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct EntryLineageResponse { /// DID of the resolved entry. pub entry_did: String, /// Publisher lineage summary, or `null` when the entry has no lineage. pub lineage: Option } ``` Source line: `289`. ## api::HealthResponse [#apihealthresponse] Response body for `GET /v1/health`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct HealthResponse { /// Service status. pub status: String, /// MARS protocol version. pub version: String, /// DID of the serving registry. pub registry_did: String } ``` Source line: `300`. ## api::DeepHealthResponse [#apideephealthresponse] Response body for `GET /v1/health/deep`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct DeepHealthResponse { /// Aggregate status: `ok`, `degraded`, or `down`. pub status: String, /// Stable, lexicographically keyed subsystem results. pub checks: BTreeMap } ``` Source line: `313`. ## api::ErrorResponse [#apierrorresponse] Canonical JSON error body returned by MARS HTTP endpoints. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct ErrorResponse { /// Machine-readable MARS error code such as `MARS-008`. pub error_code: String, /// Human-readable diagnostic. pub message: String, /// HTTP status echoed in the body. pub http_status: u16 } ``` Source line: `324`. ## api::SiwsChallengeRequest [#apisiwschallengerequest] Request body for `POST /v1/auth/siws/challenge`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SiwsChallengeRequest { /// Required audience shown to the signer. #[cfg_attr(feature = "contracts", schemars(length(min = 1)))] pub audience: String, /// HMR DID required to satisfy the challenge. #[cfg_attr(feature = "contracts", schemars(inner(regex(pattern = r"^did:oas:"))))] pub hmr_did: Option, /// Optional HMR, MHR, or ENR root DID. pub root_did: Option, /// Sigil chain identifier. pub chain_id: Option, /// Browser or application origin. pub origin: Option } ``` Source line: `337`. ## api::SiwsChallenge [#apisiwschallenge] SIWS challenge issued by MARS and signed by a Sigil wallet. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SiwsChallenge { /// Protocol discriminator. Current value is `sigil.signin`. #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^sigil\.signin$")))] pub kind: String, /// SIWS wire version. Current value is `1`. #[cfg_attr(feature = "contracts", schemars(range(min = 1, max = 1)))] pub version: u8, /// Request origin. pub origin: String, /// Sign-in audience. pub audience: String, /// Sigil chain identifier. pub chain_id: String, /// Single-use challenge nonce. pub nonce: String, /// Single-use request identifier. pub request_id: String, /// HMR DID expected to sign. #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^did:oas:")))] pub hmr_did: String, /// Optional authorizing HMR, MHR, or ENR root DID. #[serde(skip_serializing_if = "Option::is_none")] pub root_did: Option, /// Challenge issue time in Unix milliseconds. pub issued_at_ms: i64, /// Challenge expiry time in Unix milliseconds. pub expires_at_ms: i64 } ``` Source line: `356`. ## api::SiwsChallengeResponse [#apisiwschallengeresponse] Response body for `POST /v1/auth/siws/challenge`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SiwsChallengeResponse { /// Challenge that must be echoed during verification. pub challenge: SiwsChallenge } ``` Source line: `389`. ## api::SiwsSignedResponse [#apisiwssignedresponse] Signed SIWS response produced by a Sigil wallet. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SiwsSignedResponse { /// Response discriminator. Current value is `message`. #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^message$")))] pub kind: String, /// Origin copied from the challenge. pub origin: String, /// Chain identifier copied from the challenge. pub chain_id: String, /// DID of the HMR signer. #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^did:oas:")))] pub signer_did: String, /// Canonical SIWS message. pub message: String, /// Hex-encoded Ed25519 signature. pub signature: String, /// Hex-encoded Ed25519 public key. pub signer_public_key: String, /// Hex-encoded BLAKE3 transcript digest. pub digest: String, /// Canonical transcript signed by the wallet. pub transcript: String } ``` Source line: `398`. ## api::SiwsVerifyRequest [#apisiwsverifyrequest] Request body for `POST /v1/auth/siws/verify`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SiwsVerifyRequest { /// Originally issued challenge. pub challenge: SiwsChallenge, /// Wallet-signed response. pub response: SiwsSignedResponse, /// Expected audience; must equal the challenge audience. pub audience: String } ``` Source line: `425`. ## api::SiwsVerifyResponse [#apisiwsverifyresponse] Response body for a successful SIWS verification. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SiwsVerifyResponse { pub hmr_did: String, pub root_did: String, pub root_kind: String, pub signer_public_key: String, pub expires_at_ms: i64, pub session_token: String, pub session_expires_at_ms: i64 } ``` Source line: `438`. ## api::SiwsSessionResponse [#apisiwssessionresponse] Response body for `GET /v1/auth/session`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SiwsSessionResponse { pub hmr_did: String, pub root_did: String, pub root_kind: String, pub expires_at_ms: i64 } ``` Source line: `452`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/api.rs` · SHA-256 `b60a5e1d511b3d6f4ed513601d45c699a842160a170ca6f3cee225814617b5a4`. [Package overview](/libraries/mars-protocol). # mars-protocol · bonds URL: https://docs.mars.glass/libraries/mars-protocol/bonds Markdown: https://docs.mars.glass/libraries/mars-protocol/bonds.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::bonds. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `bonds` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## bonds::BOND\_CURRENCY [#bondsbond_currency] Canonical currency unit for MARS bonds on Sigil. Sigil is the chain; MINTS is the monetary unit used for publisher bonds, slashing, rewards, and shard-operator stakes. ```rust pub const BOND_CURRENCY: &str; ``` Source line: `17`. ## bonds::BondAmount [#bondsbondamount] Exact, non-negative decimal amount used by every bond money field. The wire form is always a JSON string in canonical plain-decimal notation. Values are constrained to PostgreSQL `NUMERIC(38,18)`: at most 20 integer digits and 18 fractional digits, with no sign or exponent. This keeps signature bytes, threshold checks, and database values identical. ```rust #[derive(Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[cfg_attr(feature = "contracts", schemars(transparent))] #[cfg_attr( feature = "contracts", schemars(extend( "pattern" = r"^(0|[1-9][0-9]{0,19})(\.[0-9]{1,18})?$" )) )] #[cfg_attr( feature = "contracts", schema( value_type = String, pattern = r"^(0|[1-9][0-9]{0,19})(\.[0-9]{1,18})?$", example = "100.5" ) )] pub struct BondAmount(String); ``` Source line: `42`. ## bonds::BondAmountError [#bondsbondamounterror] Invalid exact bond amount. ```rust #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum BondAmountError { /// The value is empty or uses unsupported notation. #[error("bond amount must use unsigned plain-decimal notation")] InvalidNotation, /// The value exceeds the fixed database precision or scale. #[error("bond amount exceeds NUMERIC(38,18) precision")] Overprecision, } ``` Source line: `46`. ## bonds::BondAmount::SCALE [#bondsbondamountscale] Maximum fractional scale accepted by the wire and database contract. ```rust pub const SCALE: usize; ``` Source line: `57`. ## bonds::BondAmount::INTEGER\_DIGITS [#bondsbondamountinteger_digits] Maximum number of digits before the decimal point. ```rust pub const INTEGER_DIGITS: usize; ``` Source line: `59`. ## bonds::BondAmount::from\_integer [#bondsbondamountfrom_integer] Build an exact whole-unit amount. ```rust #[must_use] pub fn from_integer(value: u64) -> Self; ``` Source line: `63`. ## bonds::BondAmount::as\_str [#bondsbondamountas_str] Canonical plain-decimal representation. ```rust #[must_use] pub fn as_str(&self) -> &str; ``` Source line: `69`. ## bonds::BondAmount::is\_zero [#bondsbondamountis_zero] Whether the amount is exactly zero. ```rust #[must_use] pub fn is_zero(&self) -> bool; ``` Source line: `75`. ## bonds::BondAmount::to\_ranking\_f64 [#bondsbondamountto_ranking_f64] Convert only for non-monetary ranking calculations. All validation and threshold decisions use \[`Ord`], never this presentation-only approximation. ```rust #[must_use] pub fn to_ranking_f64(&self) -> f64; ``` Source line: `84`. ## bonds::BondReference [#bondsbondreference] A reference to a bond stored in a MARS entry. Per MARS Specification Section 7.2. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct BondReference { /// Unique bond identifier. pub bond_id: String, /// Amount staked in MINTS. pub amount: BondAmount, /// Currency — always "MINTS". pub currency: String, /// Current bond status. pub status: BondStatus } ``` Source line: `302`. ## bonds::Bond [#bondsbond] Full bond record (server-side). Per MARS Specification Section 7.2. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct Bond { /// Unique bond identifier. pub bond_id: String, /// DID of the publisher who posted the bond. pub publisher_did: String, /// DID of the entry this bond covers. pub entry_did: String, /// DID of the registry holding the bond. pub registry_did: String, /// Amount staked in MINTS. pub amount: BondAmount, /// Currency — always "MINTS". pub currency: String, /// When the bond was created. pub created_at: chrono::DateTime, /// Current status. pub status: BondStatus, /// History of slashing events. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub slash_history: Vec } ``` Source line: `318`. ## bonds::BondStatus [#bondsbondstatus] Status of a publisher bond. Per MARS Specification Appendix A (bondReference schema). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "snake_case")] pub enum BondStatus { /// Bond is active and fully collateralized. Active, /// Bond has been partially slashed but still covers minimum. PartiallySlashed, /// Bond has been fully slashed — entry should be revoked. FullySlashed, /// Bond has been released back to the publisher. Released, } ``` Source line: `345`. ## bonds::BondStatus::as\_str [#bondsbondstatusas_str] ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `357`. ## bonds::SlashEvent [#bondsslashevent] A slashing event recorded against a bond. Per MARS Specification Section 7.4. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SlashEvent { /// When the slash occurred. pub timestamp: chrono::DateTime, /// Amount slashed in MINTS. pub amount: BondAmount, /// Reason for the slash. pub reason: String, /// DID of the reporter who triggered the slash. pub reporter_did: String, /// Distribution of slashed funds. pub distribution: SlashDistribution } ``` Source line: `378`. ## bonds::SlashDistribution [#bondsslashdistribution] Distribution of slashed bond funds. Per MARS Specification Section 7.4: 30% reporter, 40% harmed parties, 30% network treasury. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SlashDistribution { /// Amount going to the reporter (30%). pub reporter_share: BondAmount, /// Amount going to harmed parties (40%). pub harmed_parties_share: BondAmount, /// Amount going to network treasury (30%). pub treasury_share: BondAmount } ``` Source line: `397`. ## bonds::SlashDistribution::standard\_split [#bondsslashdistributionstandard_split] Compute a deterministic 30/40/30 split. Reporter and harmed-party shares round down at the 18-decimal database quantum; the treasury receives the exact remainder, so no money is created or lost. ```rust #[must_use] pub fn standard_split(total: &BondAmount) -> Self; ``` Source line: `413`. ## bonds::BondRequirements [#bondsbondrequirements] Minimum bond requirements by entry type. Per MARS Specification Section 7.3. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct BondRequirements { /// Whether a bond is required. pub required: bool, /// Minimum bond amount in MINTS. pub minimum_amount: BondAmount } ``` Source line: `432`. ## bonds::BondRequirements::for\_entry\_type [#bondsbondrequirementsfor_entry_type] Get the minimum bond requirement for an entry type. Per MARS Specification Section 7.3. ```rust pub fn for_entry_type(entry_type: &EntryType) -> Self; ``` Source line: `442`. ## bonds::MarsAnchor [#bondsmarsanchor] On-chain anchor record for a MARS entry. Per MARS Specification Appendix B. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct MarsAnchor { /// Always "MarsAnchor". #[serde(rename = "type")] pub anchor_type_name: String, /// DID of the anchored entry. pub entry_did: String, /// SHA-256 hash of canonicalized itemData. pub item_data_hash: String, /// DID of the publisher. pub publisher_did: String, /// SemVer version string. pub version: String, /// Timestamp of anchoring. pub timestamp: chrono::DateTime, /// Type of anchor operation. pub anchor_type: AnchorType, /// Bond ID (if applicable). #[serde(skip_serializing_if = "Option::is_none")] pub bond_id: Option, /// Hash of the previous anchor (chain linking). #[serde(skip_serializing_if = "Option::is_none")] pub previous_anchor_hash: Option } ``` Source line: `477`. ## bonds::AnchorType [#bondsanchortype] Anchor operation type. Per MARS Specification Section 10.1. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub enum AnchorType { Register, Update, Revoke, Transfer, Attest, } ``` Source line: `506`. ## bonds::AnchorType::as\_str [#bondsanchortypeas_str] ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `515`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/bonds.rs` · SHA-256 `19c8245fa2e672674e9bed3b464541c71f056caf48a6e8b26888c5fa9d188e52`. [Package overview](/libraries/mars-protocol). # mars-protocol · contract URL: https://docs.mars.glass/libraries/mars-protocol/contract Markdown: https://docs.mars.glass/libraries/mars-protocol/contract.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::contract. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `contract` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## Module condition [#module-condition] ```rust #[cfg(feature = "contracts")] ``` ## contract::SchemaArtifact [#contractschemaartifact] One generated JSON Schema artifact. ```rust #[cfg(feature = "contracts")] #[derive(Debug, Clone, PartialEq)] pub struct SchemaArtifact { /// Repository-relative file name beneath `schemas/v1`. pub file_name: &'static str, /// Draft 2020-12 schema document. pub document: serde_json::Value } ``` Source line: `7`. ## contract::schema\_artifacts [#contractschema_artifacts] Generate every frozen MARS v1 JSON Schema from its Rust source type. The returned order is stable by file name. Callers are responsible for canonical key ordering and filesystem writes. ```rust #[cfg(feature = "contracts")] pub fn schema_artifacts() -> Result, serde_json::Error>; ``` Source line: `18`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/contract.rs` · SHA-256 `039c9d796cda5405d12218d5eb6f74aee844e92d1cf51216f448fdf66302ea88`. [Package overview](/libraries/mars-protocol). # mars-protocol · entry URL: https://docs.mars.glass/libraries/mars-protocol/entry Markdown: https://docs.mars.glass/libraries/mars-protocol/entry.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::entry. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `entry` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## entry::EntryType [#entryentrytype] The 10 OAS-aligned entry types plus 4 MAP plugin types (14 total). Each variant maps to an \[`oas_did::EntityKind`] value via the `oas_kind` method. # Serialization [#serialization] Variants serialize to their PascalCase name (e.g. `"AgentDefinition"`). ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] pub enum EntryType { /// A registered autonomous agent. AgentDefinition, /// A tool that agents can invoke. ToolDefinition, /// A composable skill unit. SkillDefinition, /// A multi-step workflow definition. WorkflowDefinition, /// A machine learning model with provenance. ModelDefinition, /// A dataset with verified lineage. DatasetDefinition, /// An infrastructure or API service. ServiceDefinition, /// An autonomous organization record. OrganizationDefinition, /// A single verified human root (HMR). HumanRootRecord, /// A threshold-group multi-human root (MHR). MultiHumanRootRecord, // MAP Plugin ecosystem types /// A MAP plugin definition + metadata. MapPlugin, /// A specific version binary + config for a MAP plugin. MapPluginRelease, /// A reusable integration type definition for MAP plugins. MapIntegrationSchema, /// A curated bundle of MAP plugins. MapPluginCollection, } ``` Source line: `48`. ## entry::EntryType::as\_str [#entryentrytypeas_str] Returns the canonical string name of this entry type. ``` use mars_protocol::EntryType; assert_eq!(EntryType::AgentDefinition.as_str(), "AgentDefinition"); ``` ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `87`. ## entry::EntryType::oas\_kind [#entryentrytypeoas_kind] Returns the corresponding \[`oas_did::EntityKind`] for this entry type. ``` use mars_protocol::EntryType; use oas_did::EntityKind; assert_eq!(EntryType::AgentDefinition.oas_kind(), EntityKind::Agent); assert_eq!(EntryType::HumanRootRecord.oas_kind(), EntityKind::Hmr); ``` ```rust pub fn oas_kind(&self) -> EntityKind; ``` Source line: `114`. ## entry::EntryType::all [#entryentrytypeall] Returns all 14 entry type variants. ```rust pub fn all() -> &'static [EntryType; 14]; ``` Source line: `134`. ## entry::ExtensionEntryType [#entryextensionentrytype] Extension entry types that do not correspond to an OAS entity kind. These cover governance, schema governance, ontology, auditing, evaluation, and reputation domains. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] pub enum ExtensionEntryType { /// A governance or access policy definition. Policy, /// A published JSON Schema / protocol schema. SchemaDefinition, /// An ontology or vocabulary definition. Ontology, /// An audit policy specifying compliance rules. AuditPolicy, /// A template for evaluating agents, tools, or services. EvaluationTemplate, /// A reputation data feed for an entity. ReputationFeed, } ``` Source line: `170`. ## entry::ExtensionEntryType::as\_str [#entryextensionentrytypeas_str] Returns the canonical string name of this extension type. ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `187`. ## entry::ExtensionEntryType::all [#entryextensionentrytypeall] Returns all 6 extension type variants. ```rust pub fn all() -> &'static [ExtensionEntryType; 6]; ``` Source line: `199`. ## entry::LineageReference [#entrylineagereference] A reference to the human lineage chain of a MARS entry's publisher. Every non-root entry traces back to a human root DID through a chain of delegations. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct LineageReference { /// The DID of the originating human root. #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^did:oas:")))] pub human_root_did: String, /// The generation distance from the root (0 = direct child). pub generation: u32, /// Ordered chain of DIDs from root to publisher. #[serde(default, skip_serializing_if = "Vec::is_empty")] #[cfg_attr(feature = "contracts", schemars(inner(regex(pattern = r"^did:oas:"))))] pub lineage_chain: Vec } ``` Source line: `228`. ## entry::AccessPolicy [#entryaccesspolicy] Access control policy for a MARS entry. When `public` is `true` the entry is discoverable by any resolver. When `false`, only DIDs listed in `allowed_dids` (or those presenting a required attestation type) may resolve it. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct AccessPolicy { /// Whether the entry is publicly discoverable. #[serde(default = "default_true")] pub public: bool, /// Explicit DID allow-list (relevant when `public` is `false`). #[serde(skip_serializing_if = "Option::is_none")] pub allowed_dids: Option>, /// Attestation type URIs that grant access (relevant when `public` is /// `false`). #[serde(skip_serializing_if = "Option::is_none")] pub required_attestation_types: Option> } ``` Source line: `252`. ## entry::MarsEntry [#entrymarsentry] A complete MARS registry entry (MARS Specification Section 5). This is the canonical on-wire and at-rest representation of every artifact registered in the MARS ecosystem. Required fields are always present; optional fields are omitted from JSON when `None` or empty. # Validation [#validation] Call `validate` to check structural invariants before signing or persisting. # Examples [#examples] ```rust use mars_protocol::entry::{MarsEntry, EntryType}; let entry: MarsEntry = serde_json::from_str(r#"{ ... }"#)?; entry.validate()?; # Ok::<(), Box>(()) ``` ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct MarsEntry { // ----- required fields ----- /// MARS protocol version. Must be `"1.0.0"`. #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^1\.0\.0$")))] pub mars_version: String, /// The OAS DID uniquely identifying this entry. #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^did:oas:")))] pub entry_did: String, /// The primary entry type (one of 10 OAS kinds). pub entry_type: EntryType, /// Human-readable name (max 256 characters). #[cfg_attr(feature = "contracts", schemars(length(min = 1, max = 256)))] pub name: String, /// MARS shard assignment (from gal topology map). #[serde(skip_serializing_if = "Option::is_none")] pub shard_assignment: Option, /// Semantic version of this entry. #[cfg_attr(feature = "contracts", schema(value_type = String))] pub version: semver::Version, /// DID of the publishing entity. #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^did:oas:")))] pub publisher_did: String, /// Timestamp of initial publication. pub published_at: chrono::DateTime, /// URI of the JSON Schema that `item_data` conforms to. pub item_schema_uri: String, /// The entry payload conforming to `item_schema_uri`. pub item_data: serde_json::Value, /// Content hash of `item_data` in `sha256:` format. #[cfg_attr( feature = "contracts", schemars(regex(pattern = r"^sha256:[a-f0-9]{64}$")) )] pub item_data_hash: String, /// Cryptographic signature over the canonical entry content. pub signature: EntrySignature, // ----- optional / defaulted fields ----- /// Human-readable description (max 4096 characters). #[serde(skip_serializing_if = "Option::is_none")] #[cfg_attr(feature = "contracts", schemars(length(max = 4096)))] pub description: Option, /// Discovery tags. #[serde(default, skip_serializing_if = "Vec::is_empty")] #[cfg_attr( feature = "contracts", schemars(length(max = 50), inner(length(max = 64))) )] pub tags: Vec, /// Timestamp of the most recent update. #[serde(skip_serializing_if = "Option::is_none")] pub updated_at: Option>, /// Current lifecycle status (defaults to `Active`). #[serde(default)] pub lifecycle_status: LifecycleStatus, /// Lineage chain to the originating human root. #[serde(skip_serializing_if = "Option::is_none")] pub lineage_reference: Option, /// Associated economic bond. #[serde(skip_serializing_if = "Option::is_none")] pub bond_reference: Option, /// Verifiable attestations (opaque JSON; validated at a higher layer). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub verifiable_attestations: Vec, /// Typed relationships to other entries. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub relationships: Vec, /// RDF-style semantic annotations. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub semantic_annotations: Vec, /// Access control policy. #[serde(skip_serializing_if = "Option::is_none")] pub access_policy: Option, /// Service endpoints for OpenAgent resolution. /// /// Per the MARS/OpenAgent Endpoint Contract (v1.0.0), entries MAY declare /// transport endpoints. Day-one clients consume only `https` endpoints; /// `weave` and `wss` entries are stored for forward compatibility. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub service_endpoints: Vec, /// Arbitrary extension metadata. #[serde(skip_serializing_if = "Option::is_none")] pub custom_metadata: Option>, /// Registry-managed anchor projection for the current immutable snapshot. /// /// This field is excluded from the publisher signing payload and can only /// be advanced by the registry's durable anchor outbox. #[serde(default)] pub anchor_state: AnchorState, /// Monotonically increasing counter for replay protection. #[serde(default)] pub sequence: u64 } ``` Source line: `308`. ## entry::MarsEntry::validate [#entrymarsentryvalidate] Validates structural invariants of this entry. Checks performed: * `mars_version` equals `"1.0.0"`. * `entry_did` is non-empty. * `name` is non-empty and at most \[`crate::MAX_NAME_LENGTH`] characters. * `publisher_did` is non-empty. * `item_schema_uri` is non-empty. * `item_data_hash` starts with `"sha256:"`. * `description`, if present, is at most \[`crate::MAX_DESCRIPTION_LENGTH`] characters. * Every \[`SemanticAnnotation`] passes its own `validate()`. # Errors [#errors] Returns \[`MarsError::ValidationError`] on the first violated rule. ```rust pub fn validate(&self) -> Result<(), MarsError>; ``` Source line: `443`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/entry.rs` · SHA-256 `a2b87b4e5d15c0016ee5607be42a12f0f4be0bc329b9fda994fe2b99b9e27c81`. [Package overview](/libraries/mars-protocol). # mars-protocol · errors URL: https://docs.mars.glass/libraries/mars-protocol/errors Markdown: https://docs.mars.glass/libraries/mars-protocol/errors.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::errors. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `errors` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## errors::MarsError [#errorsmarserror] Unified error type for MARS protocol operations. ```rust #[derive(Debug, Clone, thiserror::Error)] pub enum MarsError { /// A field failed validation. #[error("validation error on `{field}`: {reason}")] ValidationError { field: String, reason: String }, /// A referenced entry or resource was not found. #[error("not found: {0}")] NotFound(String), /// Signature verification failed. #[error("signature error: {0}")] SignatureError(String), /// Hash mismatch between computed and expected values. #[error("hash mismatch on `{field}`: expected {expected}, got {actual}")] HashMismatch { field: String, expected: String, actual: String, }, /// Lifecycle state transition is not permitted. #[error("invalid lifecycle transition from {from} to {to}")] InvalidLifecycleTransition { from: String, to: String }, /// Machine-readable protocol error with MARS error code. #[error("[{code}] {message}")] ProtocolError { code: MarsErrorCode, message: String, }, } ``` Source line: `11`. ## errors::MarsErrorCode [#errorsmarserrorcode] Machine-readable error codes per MARS Specification Section 12.5. Each code maps to an HTTP status code and a semantic description. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] pub enum MarsErrorCode { /// MARS-001 (400): Invalid entry schema. #[serde(rename = "MARS-001")] InvalidEntrySchema, /// MARS-002 (400): Invalid entry signature. #[serde(rename = "MARS-002")] InvalidEntrySignature, /// MARS-003 (400): Invalid publisher DID. #[serde(rename = "MARS-003")] InvalidPublisherDid, /// MARS-004 (400): Invalid lineage chain. #[serde(rename = "MARS-004")] InvalidLineageChain, /// MARS-005 (400): Hash mismatch (itemDataHash ≠ computed hash). #[serde(rename = "MARS-005")] HashMismatch, /// MARS-006 (401): Missing or invalid authentication token. #[serde(rename = "MARS-006")] MissingOrInvalidToken, /// MARS-007 (403): Insufficient permissions for operation. #[serde(rename = "MARS-007")] InsufficientPermissions, /// MARS-008 (404): Entry not found. #[serde(rename = "MARS-008")] EntryNotFound, /// MARS-009 (409): Conflict (version exists, tamper detected, or concurrent update). #[serde(rename = "MARS-009")] Conflict, /// MARS-010 (402): Insufficient bond for entry type. #[serde(rename = "MARS-010")] InsufficientBond, /// MARS-011 (410): Entry has been revoked. #[serde(rename = "MARS-011")] EntryRevoked, /// MARS-012 (422): itemData does not conform to itemSchemaUri. #[serde(rename = "MARS-012")] ItemDataSchemaViolation, /// MARS-013 (429): Rate limit exceeded. #[serde(rename = "MARS-013")] RateLimitExceeded, /// MARS-014 (503): On-chain anchoring temporarily unavailable. #[serde(rename = "MARS-014")] AnchoringUnavailable, /// MARS-015 (504): Weave DHT write timeout. #[serde(rename = "MARS-015")] DhtWriteTimeout, } ``` Source line: `49`. ## errors::MarsErrorCode::code\_string [#errorsmarserrorcodecode_string] Returns the MARS-NNN code string. ```rust pub fn code_string(&self) -> &'static str; ``` Source line: `99`. ## errors::MarsErrorCode::http\_status [#errorsmarserrorcodehttp_status] Returns the corresponding HTTP status code. ```rust pub fn http_status(&self) -> u16; ``` Source line: `120`. ## errors::MarsErrorCode::description [#errorsmarserrorcodedescription] Returns a human-readable description. ```rust pub fn description(&self) -> &'static str; ``` Source line: `141`. ## errors::MarsErrorCode::all [#errorsmarserrorcodeall] Returns all 15 error codes. ```rust pub fn all() -> &'static [Self]; ``` Source line: `162`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/errors.rs` · SHA-256 `37dc67f120a1dec75d28f2f11f48f698c4aa20c7f0c71d77106cdfb5e864a770`. [Package overview](/libraries/mars-protocol). # mars-protocol · events URL: https://docs.mars.glass/libraries/mars-protocol/events Markdown: https://docs.mars.glass/libraries/mars-protocol/events.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::events. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `events` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## events::MarsEvent [#eventsmarsevent] A notification event emitted by a MARS registry. Per MARS Specification Section 13.3. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct MarsEvent { /// The type of event. pub event_type: EventType, /// Unique event identifier. pub event_id: String, /// When the event occurred. pub timestamp: chrono::DateTime, /// DID of the registry that emitted the event. pub registry_did: String, /// Event-specific payload. pub payload: EventPayload } ``` Source line: `12`. ## events::EventType [#eventseventtype] The kind of event that occurred. Per MARS Specification Section 13.1. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] pub enum EventType { /// New entry registered. #[serde(rename = "entry.created")] EntryCreated, /// Entry version updated. #[serde(rename = "entry.updated")] EntryUpdated, /// Entry revoked. #[serde(rename = "entry.revoked")] EntryRevoked, /// Ownership transferred. #[serde(rename = "entry.transferred")] EntryTransferred, /// New attestation attached. #[serde(rename = "entry.attested")] EntryAttested, /// Malicious report filed. #[serde(rename = "entry.reported")] EntryReported, /// Bond slashed. #[serde(rename = "bond.slashed")] BondSlashed, /// Federation sync completed. #[serde(rename = "federation.sync")] FederationSync, } ``` Source line: `29`. ## events::EventType::as\_str [#eventseventtypeas_str] Returns the dot-notation event name string. ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `58`. ## events::EventType::all [#eventseventtypeall] Returns all 8 event types. ```rust pub fn all() -> &'static [Self]; ``` Source line: `72`. ## events::EventPayload [#eventseventpayload] Event-specific payload. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct EventPayload { /// DID of the affected entry. pub entry_did: String, /// Entry type (when applicable). #[serde(skip_serializing_if = "Option::is_none")] pub entry_type: Option, /// Version (when applicable). #[serde(skip_serializing_if = "Option::is_none")] pub version: Option, /// Publisher DID. #[serde(skip_serializing_if = "Option::is_none")] pub publisher_did: Option, /// Additional event-specific data. #[serde(skip_serializing_if = "Option::is_none")] pub detail: Option } ``` Source line: `96`. ## events::SubscriptionFilter [#eventssubscriptionfilter] WebSocket subscription filter. Per MARS Specification Section 12.4. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SubscriptionFilter { /// Filter by entry types. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub entry_types: Vec, /// Filter by namespaces. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub namespaces: Vec, /// Filter by event types. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec, /// Filter by specific entry DIDs. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub entry_dids: Vec } ``` Source line: `118`. ## events::SubscriptionMessage [#eventssubscriptionmessage] WebSocket subscription message. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SubscriptionMessage { /// Action: "subscribe" or "unsubscribe". pub action: String, /// Subscription filters. pub filters: SubscriptionFilter } ``` Source line: `137`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/events.rs` · SHA-256 `4c066acceaf55cd4a0d7eb5efb701f9e9f1fe389e41320747c8e5fce6c25d7d2`. [Package overview](/libraries/mars-protocol). # mars-protocol · federation URL: https://docs.mars.glass/libraries/mars-protocol/federation Markdown: https://docs.mars.glass/libraries/mars-protocol/federation.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::federation. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `federation` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## federation::FEDERATION\_ENVELOPE\_VERSION [#federationfederation_envelope_version] Signed-envelope wire version for registry-to-registry traffic. ```rust pub const FEDERATION_ENVELOPE_VERSION: &str; ``` Source line: `9`. ## federation::FederationMessageKind [#federationfederationmessagekind] Closed message discriminator covered by every federation signature. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "snake_case")] pub enum FederationMessageKind { /// Pull-based entry synchronization request. SyncRequest, /// Pull-based entry synchronization response. SyncResponse, /// Typed MARS-QL discovery request. DiscoveryRequest, /// Typed MARS-QL discovery response. DiscoveryResponse, } ``` Source line: `15`. ## federation::SignedFederationEnvelope [#federationsignedfederationenvelope] JCS-canonical, detached Ed25519 envelope used for federation traffic. The signature covers every field except `signature`, including the sender, recipient, key controller, timestamp, nonce, request digest, and payload. Request digests bind responses to the exact request they answer. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct SignedFederationEnvelope { /// Stable signing profile. pub version: String, /// Message type covered by the signature. pub kind: FederationMessageKind, /// Canonical OAS service DID of the sending registry. pub sender_did: String, /// Canonical OAS service DID of the intended registry. pub recipient_did: String, /// Sender-controlled OAS DID URL used to verify the signature. pub key_id: String, /// Signature algorithm. MARS federation v1 permits only `Ed25519`. pub algorithm: String, /// Envelope creation time. pub timestamp: chrono::DateTime, /// 32 random bytes encoded as 64 lowercase hexadecimal characters. pub nonce: String, /// `sha256:` digest of the request payload, or of the request envelope for /// a response. pub request_digest: String, /// Typed federation payload. pub payload: T, /// Raw Ed25519 signature encoded as canonical unpadded base64url. pub signature: String } ``` Source line: `34`. ## federation::FederatedDiscoveryRequest [#federationfederateddiscoveryrequest] Typed query transported between federation peers. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct FederatedDiscoveryRequest { /// The exact MARS-QL v1 AST used for local discovery. pub query: crate::marsql::ast::MarsQuery } ``` Source line: `64`. ## federation::FederatedDiscoveryResponse [#federationfederateddiscoveryresponse] Typed peer response transported in a signed federation envelope. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct FederatedDiscoveryResponse { /// The peer's bounded MARS-QL result page. pub result: crate::marsql::evaluator::MarsQueryResult } ``` Source line: `73`. ## federation::FederatedDiscoveryMetadata [#federationfederateddiscoverymetadata] Public, non-sensitive metadata for a federated discovery page. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct FederatedDiscoveryMetadata { /// Whether federation was attempted for this page. pub federated: bool, /// Whether one or more peers failed, timed out, or returned invalid data. pub partial: bool, /// Number of peers selected after the configured fanout bound. pub peers_attempted: u32, /// Number of peers whose signed response was accepted. pub peers_succeeded: u32, /// Number of peers omitted because of timeout, transport, or trust failure. pub peers_failed: u32 } ``` Source line: `82`. ## federation::FederatedDiscoveryResult [#federationfederateddiscoveryresult] Deterministically merged local and peer discovery result. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct FederatedDiscoveryResult { /// Deduplicated, locally policy-checked entries. pub entries: Vec, /// Number of unique entries in the bounded merged window. pub total_count: u64, /// Registry-signed cursor for the next merged page. #[serde(skip_serializing_if = "Option::is_none")] pub cursor: Option, /// Whether another merged page is available. pub has_more: bool, /// Bounded partial-result metadata with no endpoints or internal errors. pub federation: FederatedDiscoveryMetadata } ``` Source line: `99`. ## federation::FederationAgreement [#federationfederationagreement] A federation agreement between two MARS registries. Per MARS Specification Section 11.5. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct FederationAgreement { /// Unique federation agreement identifier. pub federation_id: String, /// DID of registry A. pub registry_a: String, /// DID of registry B. pub registry_b: String, /// Entry types to synchronize. pub entry_types: Vec, /// Namespaces to synchronize. pub namespaces: Vec, /// Synchronization direction. pub sync_direction: SyncDirection, /// Sync interval (e.g. "30s"). pub sync_interval: String, /// When the agreement takes effect. pub effective_date: chrono::DateTime } ``` Source line: `118`. ## federation::SyncDirection [#federationsyncdirection] Synchronization direction for a federation agreement. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub enum SyncDirection { /// Both registries sync entries. Bidirectional, /// Only registry A pulls from registry B. AFromB, /// Only registry B pulls from registry A. BFromA, } ``` Source line: `141`. ## federation::FederationPeer [#federationfederationpeer] A peer node in the MARS federation. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct FederationPeer { /// DID of the peer registry. pub peer_did: String, /// REST API endpoint. pub endpoint: String, /// gRPC endpoint (if available). #[serde(skip_serializing_if = "Option::is_none")] pub grpc_endpoint: Option, /// When this peer was last seen. #[serde(skip_serializing_if = "Option::is_none")] pub last_seen: Option>, /// Active federation agreements with this peer. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub agreement_ids: Vec } ``` Source line: `154`. ## federation::SyncRequest [#federationsyncrequest] Pull-based sync request sent between federation peers. Per MARS Specification Section 11.3. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SyncRequest { /// Start from this sequence number (exclusive). pub from_sequence: u64, /// Maximum entries to return in this batch. #[cfg_attr(feature = "contracts", schemars(range(min = 1)))] pub max_entries: u32, /// Filter by entry types (empty = all). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub entry_types: Vec, /// Filter by namespaces (empty = all). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub namespaces: Vec } ``` Source line: `175`. ## federation::SyncResponse [#federationsyncresponse] Sync response returned by a federation peer. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SyncResponse { /// Entries returned in this batch. pub entries: Vec, /// Next sequence number to continue from. pub next_sequence: u64, /// Whether more entries are available. pub has_more: bool } ``` Source line: `193`. ## federation::ConflictResolution [#federationconflictresolution] Conflict resolution outcome per MARS Specification Section 11.4. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub enum ConflictResolution { /// On-chain anchor hash matches — this version is authoritative. OnChainAnchorWins, /// Higher OAS document sequence number wins. HigherSequenceWins, /// Valid publisher signature wins. ValidSignatureWins, } ``` Source line: `206`. ## federation::FederationBreakerState [#federationfederationbreakerstate] Persisted circuit-breaker state exposed by protected peer status APIs. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "snake_case")] pub enum FederationBreakerState { /// Requests may be attempted. Closed, /// Requests are blocked until the durable cooldown elapses. Open, /// One probe may run after the cooldown. HalfOpen, /// Operator quarantine blocks all traffic. Quarantined, } ``` Source line: `219`. ## federation::FederationPeerStatus [#federationfederationpeerstatus] Protected, secret-free operational status for one peer. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct FederationPeerStatus { /// Canonical OAS service DID. pub peer_did: String, /// Durable synchronization cursor. pub cursor: u64, /// Current circuit-breaker state. pub breaker_state: FederationBreakerState, /// Consecutive failed synchronization attempts. pub consecutive_failures: u32, /// Last successful observed latency in milliseconds. pub latency_ms: Option, /// Peer-reported sequence lag from the persisted cursor. pub lag: u64, /// Number of quarantined payloads attributed to this peer. pub quarantines: u64, /// Last successful contact. pub last_success_at: Option>, /// Earliest next permitted attempt. pub next_attempt_at: chrono::DateTime } ``` Source line: `234`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/federation.rs` · SHA-256 `2bfb4089211189784f3a9857cf90367cadb77477dbb058507af450ceae84edd0`. [Package overview](/libraries/mars-protocol). # mars-protocol · hash URL: https://docs.mars.glass/libraries/mars-protocol/hash Markdown: https://docs.mars.glass/libraries/mars-protocol/hash.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::hash. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `hash` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## hash::compute\_item\_data\_hash [#hashcompute_item_data_hash] Compute the `sha256:<hex>` hash of `item_data` in canonical (JCS) form. # Errors [#errors] Returns \[`crate::errors::MarsError::ValidationError`] if JCS serialization fails. ```rust pub fn compute_item_data_hash( item_data: &serde_json::Value, ) -> Result; ``` Source line: `13`. ## hash::verify\_item\_data\_hash [#hashverify_item_data_hash] Verify that `expected_hash` matches the hash of `item_data`. # Errors [#errors-1] Returns \[`crate::errors::MarsError::HashMismatch`] on mismatch. ```rust pub fn verify_item_data_hash( item_data: &serde_json::Value, expected_hash: &str, ) -> Result<(), crate::errors::MarsError>; ``` Source line: `32`. ## hash::hex::encode [#hashhexencode] ```rust pub fn encode(bytes: impl AsRef<[u8]>) -> String; ``` Source line: `50`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/hash.rs` · SHA-256 `8b7e3e5b2756b7b0ba1b48089d8efccb54a5bc08c781fd96bfdecaaa1e0eaaf5`. [Package overview](/libraries/mars-protocol). # mars-protocol URL: https://docs.mars.glass/libraries/mars-protocol Markdown: https://docs.mars.glass/libraries/mars-protocol.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Wire contracts, publisher signing, hashing, lifecycle, query AST, federation, and event types. Wire contracts, publisher signing, hashing, lifecycle, query AST, federation, and event types. Use this crate to serialize exact registry contracts and perform local cryptographic preparation. Runtime authorization and operator trust are enforced by the server separately. ## Package contract [#package-contract] Workspace version: **0.1.0**. Rust edition **2021**, minimum declared toolchain **1.81**, Apache-2.0 license. Protocol wire version stays **1.0.0**. Use the source checkout as the installation authority; package registry publication is not verified by this documentation build. In a consumer Cargo manifest, use an explicit path dependency to your checked-out crate. ```toml [dependencies] mars-protocol = { path = "../mars/mars-protocol" } ``` ## Feature flags [#feature-flags] | Feature | Enables | | ------------- | ---------------------------- | | `default` | Marker feature | | `contracts` | `dep:schemars`, `dep:utoipa` | | `sharding` | Marker feature | | `sigil` | `dep:async-trait` | | `mock-anchor` | `sigil` | | `prod` | Marker feature | ## Public root modules [#public-root-modules] `anchoring`, `api`, `bonds`, `contract`, `entry`, `errors`, `events`, `federation`, `hash`, `lifecycle`, `marsql`, `relationships`, `signature`, `types`, `anchor`. Conditional availability follows the source attributes. ## Public module reference [#public-module-reference] | Module | Source | | -------------------------------------------------------------- | --------------------------------------- | | [crate](/libraries/mars-protocol/root) | `mars-protocol/src/lib.rs` | | [anchoring](/libraries/mars-protocol/anchoring) | `mars-protocol/src/anchoring.rs` | | [api](/libraries/mars-protocol/api) | `mars-protocol/src/api.rs` | | [bonds](/libraries/mars-protocol/bonds) | `mars-protocol/src/bonds.rs` | | [contract](/libraries/mars-protocol/contract) | `mars-protocol/src/contract.rs` | | [entry](/libraries/mars-protocol/entry) | `mars-protocol/src/entry.rs` | | [errors](/libraries/mars-protocol/errors) | `mars-protocol/src/errors.rs` | | [events](/libraries/mars-protocol/events) | `mars-protocol/src/events.rs` | | [federation](/libraries/mars-protocol/federation) | `mars-protocol/src/federation.rs` | | [hash](/libraries/mars-protocol/hash) | `mars-protocol/src/hash.rs` | | [lifecycle](/libraries/mars-protocol/lifecycle) | `mars-protocol/src/lifecycle.rs` | | [marsql](/libraries/mars-protocol/marsql) | `mars-protocol/src/marsql/mod.rs` | | [marsql::ast](/libraries/mars-protocol/marsql/ast) | `mars-protocol/src/marsql/ast.rs` | | [marsql::evaluator](/libraries/mars-protocol/marsql/evaluator) | `mars-protocol/src/marsql/evaluator.rs` | | [marsql::parser](/libraries/mars-protocol/marsql/parser) | `mars-protocol/src/marsql/parser.rs` | | [relationships](/libraries/mars-protocol/relationships) | `mars-protocol/src/relationships.rs` | | [signature](/libraries/mars-protocol/signature) | `mars-protocol/src/signature.rs` | | [types](/libraries/mars-protocol/types) | `mars-protocol/src/types.rs` | | [anchor](/libraries/mars-protocol/anchor) | `mars-protocol/src/anchor.rs` | ## API documentation boundary [#api-documentation-boundary] The linked pages contain syntax-derived public declarations, method signatures, and documentation comments. They omit function bodies and constant values, and skip test-only modules. Compiler-resolved re-exports, trait resolution, and target availability require Rustdoc with the selected feature profile; no backend build or conformance tests ran here. # mars-protocol · lifecycle URL: https://docs.mars.glass/libraries/mars-protocol/lifecycle Markdown: https://docs.mars.glass/libraries/mars-protocol/lifecycle.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::lifecycle. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `lifecycle` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## lifecycle::LifecycleStatus [#lifecyclelifecyclestatus] The lifecycle status of a MARS registry entry. ```rust #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub enum LifecycleStatus { /// Entry submitted but not yet bonded/anchored. Draft, /// Entry bonded, anchored, and serving. #[default] Active, /// Superseded by newer version; still resolvable. Deprecated, /// No longer actively served; preserved for history. Archived, /// Permanently deactivated; irreversible. Revoked, /// Published for testing; lower bond requirements. Experimental, } ``` Source line: `17`. ## lifecycle::LifecycleStatus::as\_str [#lifecyclelifecyclestatusas_str] Returns the lowercase string representation. ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `35`. ## lifecycle::LifecycleStatus::can\_transition\_to [#lifecyclelifecyclestatuscan_transition_to] Check whether transitioning from `self` to `target` is valid. ```rust pub fn can_transition_to(&self, target: Self) -> bool; ``` Source line: `47`. ## lifecycle::LifecycleStatus::is\_resolvable [#lifecyclelifecyclestatusis_resolvable] Returns true if the entry is resolvable (can be read). ```rust pub fn is_resolvable(&self) -> bool; ``` Source line: `66`. ## lifecycle::LifecycleStatus::allows\_updates [#lifecyclelifecyclestatusallows_updates] Returns true if write operations are permitted. ```rust pub fn allows_updates(&self) -> bool; ``` Source line: `74`. ## lifecycle::RevocationReason [#lifecyclerevocationreason] Reason for revoking an entry. Per MARS Specification Section 6.5. ```rust #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub enum RevocationReason { KeyCompromise, MaliciousBehavior, Voluntary, Superseded, ParentRevocation, HumanRootRevocation, } ``` Source line: `92`. ## lifecycle::RevocationReason::as\_str [#lifecyclerevocationreasonas_str] ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `102`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/lifecycle.rs` · SHA-256 `ffb40f6801609359728e88717eaf29b6373b53b2ce7e1b9c42a0679e821f2b2c`. [Package overview](/libraries/mars-protocol). # mars-protocol · marsql URL: https://docs.mars.glass/libraries/mars-protocol/marsql Markdown: https://docs.mars.glass/libraries/mars-protocol/marsql.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::marsql. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `marsql` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## marsql::ast [#marsqlast] MARS-QL — the query language for the MARS registry. This module provides a complete MARS-QL implementation: * \[`ast`] — Abstract Syntax Tree types for parsed queries. * \[`parser`] — Recursive-descent parser (`parse(input) -> MarsQuery`). * \[`evaluator`] — Evaluate conditions against `MarsEntry` instances. # Quick Start [#quick-start] ``` use mars_protocol::marsql::{parse, MarsQuery, MarsQueryResult}; use mars_protocol::marsql::evaluator::matches_query; let query = parse(r#"DISCOVER AgentDefinition WHERE tags CONTAINS "ml" LIMIT 10"#) .expect("valid MARS-QL"); assert_eq!(query.limit, Some(10)); ``` ```rust pub mod ast; ``` Source line: `20`. ## marsql::evaluator [#marsqlevaluator] ```rust pub mod evaluator; ``` Source line: `21`. ## marsql::parser [#marsqlparser] ```rust pub mod parser; ``` Source line: `22`. ## pub use ast::MarsQuery; [#pub-use-astmarsquery] ```rust pub use ast::MarsQuery; ``` Source line: `25`. ## pub use evaluator::MarsQueryResult; [#pub-use-evaluatormarsqueryresult] ```rust pub use evaluator::MarsQueryResult; ``` Source line: `26`. ## pub use parser::parse; [#pub-use-parserparse] ```rust pub use parser::parse; ``` Source line: `27`. ## pub use ast::\{ShardHint, ShardedQuery}; [#pub-use-astshardhint-shardedquery] ```rust #[cfg(feature = "sharding")] pub use ast::{ShardHint, ShardedQuery}; ``` Source line: `30`. ## pub use parser::parse\_sharded; [#pub-use-parserparse_sharded] ```rust #[cfg(feature = "sharding")] pub use parser::parse_sharded; ``` Source line: `32`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/marsql/mod.rs` · SHA-256 `9513fa32e8d504c2587483fcf07328b68e072fbf8c1b0ba6c63836f1969df748`. [Package overview](/libraries/mars-protocol). # mars-protocol · relationships URL: https://docs.mars.glass/libraries/mars-protocol/relationships Markdown: https://docs.mars.glass/libraries/mars-protocol/relationships.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::relationships. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `relationships` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## relationships::Relationship [#relationshipsrelationship] A typed directional relationship between two MARS entries. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct Relationship { /// The kind of relationship. pub relationship_type: RelationshipType, /// The DID of the target entry. pub target_did: String, /// Optional human-readable label for the relationship. #[serde(skip_serializing_if = "Option::is_none")] pub label: Option } ``` Source line: `14`. ## relationships::RelationshipType [#relationshipsrelationshiptype] Supported relationship types between MARS entries. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub enum RelationshipType { /// The source entry depends on the target entry. DependsOn, /// The source entry composes (includes) the target entry. Composes, /// The source entry extends the target entry. Extends, /// The source entry replaces the target entry. Replaces, /// The source entry is an instance of the target entry. InstanceOf, /// The source entry is published by the target organization/human. PublishedBy, /// The source entry is related to the target entry (generic). RelatedTo, } ``` Source line: `28`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/relationships.rs` · SHA-256 `64bffdc5b8fae2a5b92f2550cba5950869643a9441aae965090b951df6d66475`. [Package overview](/libraries/mars-protocol). # mars-protocol · crate URL: https://docs.mars.glass/libraries/mars-protocol/root Markdown: https://docs.mars.glass/libraries/mars-protocol/root.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Wire contracts, publisher signing, hashing, lifecycle, query AST, federation, and event types. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `crate` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## anchoring [#anchoring] ```rust pub mod anchoring; ``` Source line: `13`. ## api [#api] ```rust pub mod api; ``` Source line: `14`. ## bonds [#bonds] ```rust pub mod bonds; ``` Source line: `15`. ## contract [#contract] ```rust #[cfg(feature = "contracts")] pub mod contract; ``` Source line: `17`. ## entry [#entry] ```rust pub mod entry; ``` Source line: `18`. ## errors [#errors] ```rust pub mod errors; ``` Source line: `19`. ## events [#events] ```rust pub mod events; ``` Source line: `20`. ## federation [#federation] ```rust pub mod federation; ``` Source line: `21`. ## hash [#hash] ```rust pub mod hash; ``` Source line: `22`. ## lifecycle [#lifecycle] ```rust pub mod lifecycle; ``` Source line: `23`. ## marsql [#marsql] ```rust pub mod marsql; ``` Source line: `24`. ## relationships [#relationships] ```rust pub mod relationships; ``` Source line: `25`. ## signature [#signature] ```rust pub mod signature; ``` Source line: `26`. ## types [#types] ```rust pub mod types; ``` Source line: `27`. ## anchor [#anchor] ```rust #[cfg(feature = "sigil")] pub mod anchor; ``` Source line: `30`. ## pub use anchoring::\{ [#pub-use-anchoring] AnchorControlResponse, AnchorListQuery, AnchorListResponse, AnchorOperation, AnchorOutboxState, AnchorReceiptRecord, AnchorReceiptState, AnchorState, AnchorStatusRecord, }; ```rust pub use anchoring::{ AnchorControlResponse, AnchorListQuery, AnchorListResponse, AnchorOperation, AnchorOutboxState, AnchorReceiptRecord, AnchorReceiptState, AnchorState, AnchorStatusRecord, }; ``` Source line: `33`. ## pub use api::\{ [#pub-use-api] AttestationQuery, AttestationRequest, BondProvisionRequest, DeepHealthResponse, DiscoverCondition, DiscoverRequest, EntryLineageResponse, EntryVersionsQuery, EntryVersionsResponse, ErrorResponse, FederationPeerUpdateRequest, HealthResponse, MarsQlRequest, ReportRequest, ReportResponse, ReportStatus, SiwsChallenge, SiwsChallengeRequest, SiwsChallengeResponse, SiwsSessionResponse, SiwsSignedResponse, SiwsVerifyRequest, SiwsVerifyResponse, TransferAcceptRequest, TransferDeclineRequest, TransferOffer, TransferOfferRequest, TransferOfferStatus, TransferRequest, VerifiableAttestationRecord, }; ```rust pub use api::{ AttestationQuery, AttestationRequest, BondProvisionRequest, DeepHealthResponse, DiscoverCondition, DiscoverRequest, EntryLineageResponse, EntryVersionsQuery, EntryVersionsResponse, ErrorResponse, FederationPeerUpdateRequest, HealthResponse, MarsQlRequest, ReportRequest, ReportResponse, ReportStatus, SiwsChallenge, SiwsChallengeRequest, SiwsChallengeResponse, SiwsSessionResponse, SiwsSignedResponse, SiwsVerifyRequest, SiwsVerifyResponse, TransferAcceptRequest, TransferDeclineRequest, TransferOffer, TransferOfferRequest, TransferOfferStatus, TransferRequest, VerifiableAttestationRecord, }; ``` Source line: `37`. ## pub use entry::\{AccessPolicy, EntryType, ExtensionEntryType, LineageReference, MarsEntry}; [#pub-use-entryaccesspolicy-entrytype-extensionentrytype-lineagereference-marsentry] ```rust pub use entry::{AccessPolicy, EntryType, ExtensionEntryType, LineageReference, MarsEntry}; ``` Source line: `49`. ## pub use lifecycle::\{LifecycleStatus, RevocationReason}; [#pub-use-lifecyclelifecyclestatus-revocationreason] ```rust pub use lifecycle::{LifecycleStatus, RevocationReason}; ``` Source line: `50`. ## pub use relationships::\{Relationship, RelationshipType}; [#pub-use-relationshipsrelationship-relationshiptype] ```rust pub use relationships::{Relationship, RelationshipType}; ``` Source line: `51`. ## pub use types::SemanticAnnotation; [#pub-use-typessemanticannotation] ```rust pub use types::SemanticAnnotation; ``` Source line: `52`. ## pub use hash::\{compute\_item\_data\_hash, verify\_item\_data\_hash}; [#pub-use-hashcompute_item_data_hash-verify_item_data_hash] ```rust pub use hash::{compute_item_data_hash, verify_item_data_hash}; ``` Source line: `55`. ## pub use bonds::\{ [#pub-use-bonds] AnchorType, Bond, BondAmount, BondAmountError, BondReference, BondRequirements, BondStatus, MarsAnchor, }; ```rust pub use bonds::{ AnchorType, Bond, BondAmount, BondAmountError, BondReference, BondRequirements, BondStatus, MarsAnchor, }; ``` Source line: `58`. ## pub use bonds::\{SlashDistribution, SlashEvent}; [#pub-use-bondsslashdistribution-slashevent] ```rust pub use bonds::{SlashDistribution, SlashEvent}; ``` Source line: `62`. ## pub use signature::\{ [#pub-use-signature] canonical\_signing\_bytes, controller\_did\_from\_key\_id, sign\_entry, verify\_entry\_signature, EntrySignature, PUBLISHER\_SIGNING\_PROFILE, REGISTRY\_MANAGED\_TOP\_LEVEL\_FIELDS, }; ```rust pub use signature::{ canonical_signing_bytes, controller_did_from_key_id, sign_entry, verify_entry_signature, EntrySignature, PUBLISHER_SIGNING_PROFILE, REGISTRY_MANAGED_TOP_LEVEL_FIELDS, }; ``` Source line: `65`. ## pub use errors::\{MarsError, MarsErrorCode}; [#pub-use-errorsmarserror-marserrorcode] ```rust pub use errors::{MarsError, MarsErrorCode}; ``` Source line: `71`. ## pub use federation::\{ [#pub-use-federation] FederatedDiscoveryMetadata, FederatedDiscoveryRequest, FederatedDiscoveryResponse, FederatedDiscoveryResult, FederationAgreement, FederationBreakerState, FederationMessageKind, FederationPeer, FederationPeerStatus, SignedFederationEnvelope, SyncDirection, SyncRequest, SyncResponse, FEDERATION\_ENVELOPE\_VERSION, }; ```rust pub use federation::{ FederatedDiscoveryMetadata, FederatedDiscoveryRequest, FederatedDiscoveryResponse, FederatedDiscoveryResult, FederationAgreement, FederationBreakerState, FederationMessageKind, FederationPeer, FederationPeerStatus, SignedFederationEnvelope, SyncDirection, SyncRequest, SyncResponse, FEDERATION_ENVELOPE_VERSION, }; ``` Source line: `74`. ## pub use events::\{EventPayload, EventType, MarsEvent, SubscriptionFilter, SubscriptionMessage}; [#pub-use-eventseventpayload-eventtype-marsevent-subscriptionfilter-subscriptionmessage] ```rust pub use events::{EventPayload, EventType, MarsEvent, SubscriptionFilter, SubscriptionMessage}; ``` Source line: `82`. ## pub use anchor::MockSigilAnchorClient; [#pub-use-anchormocksigilanchorclient] ```rust #[cfg(feature = "mock-anchor")] pub use anchor::MockSigilAnchorClient; ``` Source line: `86`. ## pub use anchor::\{ [#pub-use-anchor] verify\_merkle\_proof, AnchorError, AnchorRecord, AnchorRequest, AnchorResponse, AnchorStatus, Direction, MerkleProof, ProofNode, SigilAnchorClient, }; ```rust #[cfg(feature = "sigil")] pub use anchor::{ verify_merkle_proof, AnchorError, AnchorRecord, AnchorRequest, AnchorResponse, AnchorStatus, Direction, MerkleProof, ProofNode, SigilAnchorClient, }; ``` Source line: `88`. ## pub use marsql::parser::parse as parse\_marsql; [#pub-use-marsqlparserparse-as-parse_marsql] ```rust pub use marsql::parser::parse as parse_marsql; ``` Source line: `94`. ## pub use marsql::\{MarsQuery, MarsQueryResult}; [#pub-use-marsqlmarsquery-marsqueryresult] ```rust pub use marsql::{MarsQuery, MarsQueryResult}; ``` Source line: `95`. ## ::MARS\_VERSION [#mars_version] MARS protocol version. ```rust pub const MARS_VERSION: &str; ``` Source line: `98`. ## ::MAX\_NAME\_LENGTH [#max_name_length] Maximum entry name length. ```rust pub const MAX_NAME_LENGTH: usize; ``` Source line: `101`. ## ::MAX\_DESCRIPTION\_LENGTH [#max_description_length] Maximum description length. ```rust pub const MAX_DESCRIPTION_LENGTH: usize; ``` Source line: `104`. ## ::MAX\_TAGS [#max_tags] Maximum tags per entry. ```rust pub const MAX_TAGS: usize; ``` Source line: `107`. ## ::MAX\_TAG\_LENGTH [#max_tag_length] Maximum tag length. ```rust pub const MAX_TAG_LENGTH: usize; ``` Source line: `110`. ## ::MAX\_ITEM\_DATA\_BYTES [#max_item_data_bytes] Maximum `item_data` size in bytes (1 MiB canonical JSON). ```rust pub const MAX_ITEM_DATA_BYTES: usize; ``` Source line: `113`. ## ::MAX\_MARSQL\_LENGTH [#max_marsql_length] Maximum MARS-QL query string length in bytes. ```rust pub const MAX_MARSQL_LENGTH: usize; ``` Source line: `116`. ## ::MAX\_MARSQL\_CONDITIONS [#max_marsql_conditions] Maximum number of conditions in a single MARS-QL WHERE clause. ```rust pub const MAX_MARSQL_CONDITIONS: usize; ``` Source line: `119`. ## ::MAX\_MARSQL\_FIELD\_DEPTH [#max_marsql_field_depth] Maximum field-path depth in a MARS-QL condition (segments separated by `.`). ```rust pub const MAX_MARSQL_FIELD_DEPTH: usize; ``` Source line: `122`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/lib.rs` · SHA-256 `32a534f8962fffe78e24579ebf221c7efc35b1313ddd08e9535b20750b9ff42b`. [Package overview](/libraries/mars-protocol). # mars-protocol · signature URL: https://docs.mars.glass/libraries/mars-protocol/signature Markdown: https://docs.mars.glass/libraries/mars-protocol/signature.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::signature. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `signature` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## signature::PUBLISHER\_SIGNING\_PROFILE [#signaturepublisher_signing_profile] Stable identifier for the MARS v1 publisher-signing erratum profile. ```rust pub const PUBLISHER_SIGNING_PROFILE: &str; ``` Source line: `30`. ## signature::REGISTRY\_MANAGED\_TOP\_LEVEL\_FIELDS [#signatureregistry_managed_top_level_fields] Top-level fields managed by a registry and excluded from publisher signatures. This is the sole public exclusion list for \[`PUBLISHER_SIGNING_PROFILE`]. Implementations MUST NOT maintain parallel active/reserved lists, exclude fields by prefix, or use an open-ended rule: every unlisted field is publisher-authored and remains tamper-evident. `anchorProjection`, `anchorTxHash`, `anchorBlockHeight`, and `anchorProof` remain reserved for future registry projections and do not activate a ledger adapter. ```rust pub const REGISTRY_MANAGED_TOP_LEVEL_FIELDS: &[&str]; ``` Source line: `41`. ## signature::EntrySignature [#signatureentrysignature] Cryptographic signature over a MARS entry's canonical content. The signature uses `MARS-PUBLISHER-SIGNING-V1`: JCS (RFC 8785) over publisher-authored fields after removing only `signature`, `sequence`, `updatedAt`, `lifecycleStatus`, `verifiableAttestations`, `shardAssignment`, `anchorProjection`, `anchorState`, `anchorTxHash`, `anchorBlockHeight`, and `anchorProof`. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct EntrySignature { /// Signature algorithm. Always "Ed25519". #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^Ed25519$")))] pub algorithm: String, /// DID URL of the signing key (e.g. `"did:oas:l1fe:ao:org#key-1"`). #[cfg_attr(feature = "contracts", schemars(regex(pattern = r"^did:oas:.+#.+$")))] pub key_id: String, /// Strict URL-safe, unpadded base64url signature bytes. /// /// Standard-base64 characters (`+`, `/`) and `=` padding are rejected. pub value: String, /// ISO 8601 timestamp of when the signature was created. #[serde(skip_serializing_if = "Option::is_none")] pub created: Option } ``` Source line: `65`. ## signature::sign\_entry [#signaturesign_entry] Sign an entry payload and produce an \[`EntrySignature`]. # Arguments [#arguments] * `canonical_bytes` — Output from \[`canonical_signing_bytes`]. * `key_id` — DID URL of the signing key (e.g. `"did:oas:ns:kind:id#key-1"`). * `signing_key` — Ed25519 signing key. * `created` — Optional ISO 8601 timestamp. # Errors [#errors] Returns \[`crate::errors::MarsError::SignatureError`] if signing fails. ```rust pub fn sign_entry( canonical_bytes: &[u8], key_id: &str, signing_key: &ed25519_dalek::SigningKey, created: Option<&str>, ) -> Result; ``` Source line: `95`. ## signature::verify\_entry\_signature [#signatureverify_entry_signature] Verify an \[`EntrySignature`] against canonical bytes and the signer's public key. # Errors [#errors-1] Returns \[`crate::errors::MarsError::SignatureError`] on any verification failure. ```rust pub fn verify_entry_signature( canonical_bytes: &[u8], signature: &EntrySignature, public_key: &ed25519_dalek::VerifyingKey, ) -> Result<(), crate::errors::MarsError>; ``` Source line: `118`. ## signature::canonical\_signing\_bytes [#signaturecanonical_signing_bytes] Produce the canonical MARS v1 publisher-signing payload. Serializes `entry` to JSON, removes every field in \[`REGISTRY_MANAGED_TOP_LEVEL_FIELDS`] from the top-level object, and JCS-canonicalizes the result. Every other field, including `publisherDid`, `itemData`, and `bondReference`, remains signed. # Errors [#errors-2] Returns \[`MarsError::SerializationError`] if `entry` cannot be serialized or canonicalized. ```rust pub fn canonical_signing_bytes(entry: &T) -> Result, MarsError>; ``` Source line: `160`. ## signature::controller\_did\_from\_key\_id [#signaturecontroller_did_from_key_id] Extract the controller DID portion of a `key_id` of the form `"did:oas:...#fragment"`. Returns the substring before `#`, or the whole string if no `#` is present. Used to enforce that a signing key's controller DID matches the entry's `publisher_did`. ```rust pub fn controller_did_from_key_id(key_id: &str) -> &str; ``` Source line: `179`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/signature.rs` · SHA-256 `790b011341b155624a89698aa9059a5a81e083b1dc8128e04ef7ca29450c37e5`. [Package overview](/libraries/mars-protocol). # mars-protocol · types URL: https://docs.mars.glass/libraries/mars-protocol/types Markdown: https://docs.mars.glass/libraries/mars-protocol/types.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::types. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `types` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## types::SemanticAnnotation [#typessemanticannotation] RDF-style semantic annotation attached to a MARS entry. Annotations express facts about an entry in predicate-object form. At least one of `object_literal` or `object_uri` must be provided; supplying both is valid and indicates the literal is a label/display form of the referenced resource. # Serialization [#serialization] All fields use camelCase when serialized to JSON. # Examples [#examples] ``` use mars_protocol::types::SemanticAnnotation; let ann = SemanticAnnotation { predicate_uri: "https://schema.org/author".into(), object_literal: Some("Ada Lovelace".into()), object_uri: Some("did:oas:hmr:abc123".into()), }; assert!(ann.validate().is_ok()); ``` ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct SemanticAnnotation { /// The predicate URI identifying the relationship (e.g. `https://schema.org/author`). pub predicate_uri: String, /// A literal value for the object (plain text, number-as-string, etc.). #[serde(skip_serializing_if = "Option::is_none")] pub object_literal: Option, /// A URI reference for the object (another DID, schema URL, etc.). #[serde(skip_serializing_if = "Option::is_none")] pub object_uri: Option } ``` Source line: `43`. ## types::SemanticAnnotation::validate [#typessemanticannotationvalidate] Validates the annotation. # Rules [#rules] 1. `predicate_uri` must be non-empty. 2. At least one of `object_literal` or `object_uri` must be `Some`. 3. If `object_literal` is `Some`, it must be non-empty. 4. If `object_uri` is `Some`, it must be non-empty. # Errors [#errors] Returns \[`MarsError::ValidationError`] describing the first violated rule. ```rust pub fn validate(&self) -> Result<(), MarsError>; ``` Source line: `69`. ## types::ServiceEndpoint [#typesserviceendpoint] A service endpoint declared in a MARS entry. Per the MARS/OpenAgent Endpoint Contract (v1.0.0), each endpoint declares a transport type, a URL, and a selection priority. Day-one only `https` endpoints are consumed; `weave` and `wss` endpoints are stored for forward compatibility. # Forward Compatibility [#forward-compatibility] Clients MUST ignore endpoint types they do not support. The `properties` field provides a transport-specific extension point so future metadata does not require schema-level changes. # Serialization [#serialization-1] All fields use camelCase. `properties` is omitted when empty/None. # Examples [#examples-1] ``` use mars_protocol::types::ServiceEndpoint; let ep = ServiceEndpoint { id: "primary-https".into(), endpoint_type: "https".into(), url: "https://api.example.com".into(), priority: 0, properties: None, }; assert!(ep.validate().is_ok()); ``` ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct ServiceEndpoint { /// Unique identifier within a DID's endpoint set. pub id: String, /// Transport type: `"https"` (day-one), `"weave"`, `"wss"` (phase-2). #[serde(rename = "type")] pub endpoint_type: String, /// Transport-specific address (URL, peer ID, etc.). pub url: String, /// Selection priority. 0 = highest. Lower values preferred. pub priority: u32, /// Transport-specific metadata (extensible, optional). #[serde(skip_serializing_if = "Option::is_none")] pub properties: Option> } ``` Source line: `141`. ## types::ServiceEndpoint::validate [#typesserviceendpointvalidate] Validates the endpoint. # Rules [#rules-1] 1. `id` must be non-empty. 2. `endpoint_type` must be non-empty. 3. `url` must be non-empty. 4. Unknown `endpoint_type` values are accepted (forward compat) but known types are validated for URL scheme consistency. ```rust pub fn validate(&self) -> Result<(), MarsError>; ``` Source line: `173`. ## types::ServiceEndpoint::is\_known\_type [#typesserviceendpointis_known_type] Returns whether this endpoint type is a known transport. ```rust pub fn is_known_type(&self) -> bool; ``` Source line: `224`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/types.rs` · SHA-256 `72218f99cce9b23c9f242c86610a92ccbba2b529825cd7cd713e344d8445f858`. [Package overview](/libraries/mars-protocol). # mars-server · anchor URL: https://docs.mars.glass/libraries/mars-server/anchor Markdown: https://docs.mars.glass/libraries/mars-server/anchor.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::anchor. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `anchor` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## anchor::config [#anchorconfig] Provider-neutral durable anchor outbox execution. The worker owns no Sigil types and never holds a database transaction while invoking \[`AnchorPort`]. Production uses the Sigil SDK adapter; deterministic adapters remain explicitly test-gated. ```rust pub mod config; ``` Source line: `7`. ## anchor::sigil [#anchorsigil] ```rust #[cfg(feature = "sigil")] pub mod sigil; ``` Source line: `9`. ## anchor::test\_adapter [#anchortest_adapter] ```rust #[cfg(any(test, feature = "test-anchor"))] pub mod test_adapter; ``` Source line: `11`. ## pub use config::AnchorWorkerConfig; [#pub-use-configanchorworkerconfig] ```rust pub use config::AnchorWorkerConfig; ``` Source line: `23`. ## anchor::AnchorSubmission [#anchoranchorsubmission] Complete MARS-owned payload handed to an external ledger adapter. ```rust #[derive(Debug, Clone, PartialEq)] pub struct AnchorSubmission { pub intent_id: String, pub entry_did: String, pub sequence: u64, pub operation: AnchorOperation, pub payload: serde_json::Value, pub created_at: DateTime } ``` Source line: `27`. ## anchor::AnchorPortReceipt [#anchoranchorportreceipt] Provider-neutral submitted or confirmed observation. ```rust #[derive(Debug, Clone, PartialEq)] pub struct AnchorPortReceipt { pub receipt_key: String, pub transaction_id: String, pub state: AnchorReceiptState, pub block_height: Option, pub proof: Option, pub observed_at: DateTime } ``` Source line: `51`. ## anchor::AnchorPortReceipt::submitted [#anchoranchorportreceiptsubmitted] ```rust #[must_use] pub fn submitted( receipt_key: impl Into, transaction_id: impl Into, observed_at: DateTime, ) -> Self; ``` Source line: `62`. ## anchor::AnchorPortReceipt::confirmed [#anchoranchorportreceiptconfirmed] ```rust #[must_use] pub fn confirmed( receipt_key: impl Into, transaction_id: impl Into, block_height: u64, observed_at: DateTime, ) -> Self; ``` Source line: `78`. ## anchor::AnchorPortError [#anchoranchorporterror] Explicitly classified adapter failure. ```rust #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum AnchorPortError { #[error("retryable anchor adapter failure: {0}")] Retryable(String), #[error("permanent anchor adapter failure: {0}")] Permanent(String), } ``` Source line: `137`. ## anchor::AnchorPortError::retryable [#anchoranchorporterrorretryable] ```rust #[must_use] pub fn retryable(message: impl Into) -> Self; ``` Source line: `146`. ## anchor::AnchorPortError::permanent [#anchoranchorporterrorpermanent] ```rust #[must_use] pub fn permanent(message: impl Into) -> Self; ``` Source line: `151`. ## anchor::AnchorPort [#anchoranchorport] Ledger adapter boundary owned by MARS. Implementations must honor `submission.intent_id` as the idempotency key. `submit` may therefore be called again after an expired lease when a worker crashed after the external side effect but before receipt persistence. ```rust #[async_trait] pub trait AnchorPort: Send + Sync { /// Emergency backpressure gate checked before the worker leases any row. fn submissions_paused(&self) -> bool ; async fn submit( &self, submission: &AnchorSubmission, ) -> Result; async fn observe( &self, submission: &AnchorSubmission, receipt: &AnchorPortReceipt, ) -> Result; } ``` Source line: `166`. ## anchor::AnchorReadinessPort [#anchoranchorreadinessport] Provider-neutral deep-readiness probe retained by protected health checks. ```rust #[async_trait] pub trait AnchorReadinessPort: Send + Sync { async fn check(&self) -> Result; } ``` Source line: `186`. ## anchor::WorkerRunState [#anchorworkerrunstate] Why one worker pass did or did not execute. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WorkerRunState { Disabled, AdapterUnregistered, SubmissionPaused, Executed, } ``` Source line: `192`. ## anchor::AnchorWorkerRun [#anchoranchorworkerrun] Outcomes from one bounded worker pass. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct AnchorWorkerRun { pub state: WorkerRunState, pub claimed: u64, pub submitted: u64, pub confirmed: u64, pub failed: u64, pub abandoned: u64, pub infrastructure_failures: u64 } ``` Source line: `201`. ## anchor::AnchorWorkerHealthSnapshot [#anchoranchorworkerhealthsnapshot] Operator-visible snapshot of the anchor supervisor's process-local health. ```rust #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct AnchorWorkerHealthSnapshot { pub degraded: bool, pub consecutive_failures: u32, pub last_error: Option, pub last_success_at: Option> } ``` Source line: `227`. ## anchor::AnchorWorkerHealth [#anchoranchorworkerhealth] Shared health handle retained by both the worker and HTTP diagnostics. ```rust #[derive(Debug, Clone, Default)] pub struct AnchorWorkerHealth { } ``` Source line: `236`. ## anchor::AnchorWorkerHealth::snapshot [#anchoranchorworkerhealthsnapshot-1] ```rust #[must_use] pub fn snapshot(&self) -> AnchorWorkerHealthSnapshot; ``` Source line: `242`. ## anchor::AnchorWorker [#anchoranchorworker] One multi-replica-safe anchor outbox worker. ```rust pub struct AnchorWorker { } ``` Source line: `269`. ## anchor::AnchorWorker::new [#anchoranchorworkernew] ```rust pub fn new( worker_id: impl Into, store: Arc, port: Option>, config: AnchorWorkerConfig, ) -> Result; ``` Source line: `278`. ## anchor::AnchorWorker::health [#anchoranchorworkerhealth-1] Clone the supervisor health handle for protected diagnostics. ```rust #[must_use] pub fn health(&self) -> AnchorWorkerHealth; ``` Source line: `302`. ## anchor::AnchorWorker::run\_once [#anchoranchorworkerrun_once] Execute at most one configured batch. Claiming and durable transitions happen in short store transactions. Adapter calls occur strictly between those transactions. ```rust pub async fn run_once(&self, now: DateTime) -> Result; ``` Source line: `310`. ## anchor::AnchorWorker::run\_until\_shutdown [#anchoranchorworkerrun_until_shutdown] Run bounded passes until the process shutdown signal changes. Production wiring calls this only after registering a reviewed adapter. Enabling the loop without one is an explicit configuration error rather than a silent no-op. ```rust pub async fn run_until_shutdown( &self, mut shutdown: tokio::sync::watch::Receiver, ) -> Result<(), ServerError>; ``` Source line: `401`. ## Source provenance [#source-provenance] Source: `mars-server/src/anchor/mod.rs` · SHA-256 `582898e6ac798e1dd75a7d62c5f2a5be8d0182dd7f37a7d32b0b6162962284df`. [Package overview](/libraries/mars-server). # mars-server · api URL: https://docs.mars.glass/libraries/mars-server/api Markdown: https://docs.mars.glass/libraries/mars-server/api.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::api. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `api` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## api::rest [#apirest] Router assembly and shared application state. This module wires together all REST and WebSocket handlers into a single \[`axum::Router`] and defines the \[`AppState`] shared across all handlers. ```rust pub mod rest; ``` Source line: `6`. ## api::websocket [#apiwebsocket] ```rust pub mod websocket; ``` Source line: `7`. ## api::MAX\_QUERY\_BODY\_BYTES [#apimax_query_body_bytes] Maximum buffered JSON body accepted by every public query endpoint. This accommodates the protocol's maximum structured query while bounding allocation before deserialization or any federated fanout. ```rust pub const MAX_QUERY_BODY_BYTES: usize; ``` Source line: `27`. ## api::AppState [#apiappstate] Application state shared across all handlers. Stored in an \[`Arc`] and injected into handlers via axum's `State` extractor. ```rust pub struct AppState { /// Storage backend for entries, bonds, events, and peers. pub store: Arc, /// Server configuration. pub config: ServerConfig, /// Validation pipeline for incoming entries. pub validation: ValidationPipeline, /// Provider-neutral bond lookup/provisioning port. pub bond_port: Arc, /// Discovery engine for MARS-QL queries. pub discovery: Arc, /// Signed inbound federation service, present only when federation is /// fully configured. pub federation_service: Option>, /// Optional bounded local-plus-peer discovery coordinator. pub federated_discovery: Option>, /// Rate limiter for read endpoints. pub read_limiter: RateLimiter, /// Rate limiter for write endpoints. pub write_limiter: RateLimiter, /// Rate limiter for query/discovery endpoints. pub query_limiter: RateLimiter, /// Rate limiter for authentication bootstrap and session endpoints. pub auth_limiter: RateLimiter, /// Rate limiter for WebSocket upgrade admission. pub websocket_limiter: RateLimiter, /// Whether a concrete [`crate::anchor::AnchorPort`] is registered. /// /// Production wires the Sigil SDK adapter only after authenticated deep /// readiness succeeds. pub anchor_adapter_registered: bool, /// Process-local anchor worker supervisor health. pub anchor_worker_health: crate::anchor::AnchorWorkerHealth, /// Bounded live dependency probe for Sigil GAL and anchor RPC readiness. pub anchor_readiness: Option>, /// SIWS authentication state — challenge store, session store, and /// registered provider adapters. The domain and capability middleware are /// always available; concrete SIWS verification is feature-gated. pub auth: Arc } ``` Source line: `32`. ## api::build\_router [#apibuild_router] Build the complete axum Router with all REST and WebSocket endpoints. Mounts all endpoints under `/v1/` per MARS Specification Appendix D. Mutation routes and federated discovery declare their required MARS capability and resolve a provider-neutral Principal before invoking handlers. Public reads, local queries, authentication, and WebSocket admission use separate per-client buckets; deep health additionally requires operator capability. ```rust pub fn build_router(state: Arc) -> Router; ``` Source line: `109`. ## Source provenance [#source-provenance] Source: `mars-server/src/api/mod.rs` · SHA-256 `28838016278b0fd7a926ef006bea8e975c2d71861fdfb6b4d054ee037bbf6b3b`. [Package overview](/libraries/mars-server). # mars-server · auth URL: https://docs.mars.glass/libraries/mars-server/auth Markdown: https://docs.mars.glass/libraries/mars-server/auth.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::auth. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `auth` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## auth::adapters [#authadapters] Provider-neutral authentication and capability authorization for MARS. The always-on domain consists of \[`Principal`], \[`Capability`], durable session/challenge ports, and \[`AuthProfileRegistry`]. Provider integrations are adapters; the only concrete adapter in this release is SIWS and it is compiled behind the optional `sigil` feature. ```rust pub mod adapters; ``` Source line: `8`. ## auth::challenge\_store [#authchallenge_store] ```rust pub mod challenge_store; ``` Source line: `9`. ## auth::handlers [#authhandlers] ```rust pub mod handlers; ``` Source line: `10`. ## auth::principal [#authprincipal] ```rust pub mod principal; ``` Source line: `11`. ## auth::registry [#authregistry] ```rust pub mod registry; ``` Source line: `12`. ## auth::session\_store [#authsession_store] ```rust pub mod session_store; ``` Source line: `13`. ## pub use challenge\_store::PostgresChallengeStore; [#pub-use-challenge_storepostgreschallengestore] ```rust #[cfg(feature = "postgres")] pub use challenge_store::PostgresChallengeStore; ``` Source line: `19`. ## pub use challenge\_store::\{AuthChallengeStore, ChallengeRecord, InMemoryChallengeStore}; [#pub-use-challenge_storeauthchallengestore-challengerecord-inmemorychallengestore] ```rust pub use challenge_store::{AuthChallengeStore, ChallengeRecord, InMemoryChallengeStore}; ``` Source line: `20`. ## pub use principal::\{AuthError, AuthProfile, Capability, CapabilitySet, Credential, Principal}; [#pub-use-principalautherror-authprofile-capability-capabilityset-credential-principal] ```rust pub use principal::{AuthError, AuthProfile, Capability, CapabilitySet, Credential, Principal}; ``` Source line: `21`. ## pub use registry::\{AuthProfileAdapter, AuthProfileRegistry}; [#pub-use-registryauthprofileadapter-authprofileregistry] ```rust pub use registry::{AuthProfileAdapter, AuthProfileRegistry}; ``` Source line: `22`. ## pub use session\_store::PostgresSessionStore; [#pub-use-session_storepostgressessionstore] ```rust #[cfg(feature = "postgres")] pub use session_store::PostgresSessionStore; ``` Source line: `24`. ## pub use session\_store::\{InMemorySessionStore, IssuedSession, SessionStore}; [#pub-use-session_storeinmemorysessionstore-issuedsession-sessionstore] ```rust pub use session_store::{InMemorySessionStore, IssuedSession, SessionStore}; ``` Source line: `25`. ## auth::DEFAULT\_SESSION\_TTL\_MS [#authdefault_session_ttl_ms] Default session TTL (7 days, expressed in milliseconds). ```rust pub const DEFAULT_SESSION_TTL_MS: i64; ``` Source line: `28`. ## auth::MAX\_SESSION\_TTL\_MS [#authmax_session_ttl_ms] Maximum session TTL (90 days, expressed in milliseconds). Every authentication profile must enforce this server-owned ceiling so an operator unit error cannot silently create effectively permanent sessions. ```rust pub const MAX_SESSION_TTL_MS: i64; ``` Source line: `34`. ## auth::DEFAULT\_CHALLENGE\_TTL\_MS [#authdefault_challenge_ttl_ms] Default challenge TTL (5 minutes, expressed in milliseconds). Matches `sigil_sdk::DEFAULT_MAX_SIGN_IN_CHALLENGE_TTL_MS` so the verifier does not reject our challenges as too long-lived. ```rust pub const DEFAULT_CHALLENGE_TTL_MS: i64; ``` Source line: `40`. ## auth::DEFAULT\_MAX\_CLOCK\_SKEW\_MS [#authdefault_max_clock_skew_ms] Maximum clock skew the verifier tolerates (5 minutes). ```rust pub const DEFAULT_MAX_CLOCK_SKEW_MS: i64; ``` Source line: `43`. ## auth::ServerClock [#authserverclock] Server-controlled time source used by issuance, lookup, and verification. ```rust pub trait ServerClock: Send + Sync { /// Current Unix timestamp in milliseconds. fn now_ms(&self) -> i64; } ``` Source line: `46`. ## auth::SystemClock [#authsystemclock] Production wall-clock implementation. ```rust #[derive(Debug, Default)] pub struct SystemClock; ``` Source line: `53`. ## auth::AuthState [#authauthstate] Authentication state plumbed into \[`crate::api::AppState`]. ```rust pub struct AuthState { /// Provider-neutral pending challenge persistence. pub challenges: Arc, /// Provider-neutral active session persistence. pub sessions: Arc, /// Default session TTL in milliseconds. pub session_ttl_ms: i64, /// Default challenge TTL in milliseconds. pub challenge_ttl_ms: i64 } ``` Source line: `62`. ## auth::AuthState::from\_parts [#authauthstatefrom_parts] Build auth state from explicit provider-neutral stores and adapters. ```rust pub fn from_parts( sessions: Arc, challenges: Arc, registry: AuthProfileRegistry, enabled_profiles: BTreeSet, clock: Arc, session_ttl_ms: i64, challenge_ttl_ms: i64, ) -> Result; ``` Source line: `80`. ## auth::AuthState::in\_memory [#authauthstatein_memory] Process-local auth state with no credential adapters. Intended for tests and explicit development mode where sessions are seeded directly. ```rust pub fn in_memory() -> Self; ``` Source line: `122`. ## auth::AuthState::authenticate [#authauthstateauthenticate] Authenticate through a configured concrete adapter. ```rust pub async fn authenticate(&self, credential: &Credential) -> Result; ``` Source line: `135`. ## auth::AuthState::registered\_profiles [#authauthstateregistered_profiles] Profiles backed by concrete adapters in this process. ```rust pub fn registered_profiles(&self) -> BTreeSet; ``` Source line: `149`. ## auth::AuthState::registry [#authauthstateregistry] Borrow the concrete adapter registry for startup validation. ```rust pub fn registry(&self) -> &AuthProfileRegistry; ``` Source line: `154`. ## auth::AuthState::enabled\_profiles [#authauthstateenabled_profiles] Profiles enabled by operator configuration. ```rust pub fn enabled_profiles(&self) -> &BTreeSet; ``` Source line: `159`. ## auth::AuthState::has\_durable\_storage [#authauthstatehas_durable_storage] Whether both authentication stores survive process restart. ```rust pub fn has_durable_storage(&self) -> bool; ``` Source line: `164`. ## auth::AuthState::now\_ms [#authauthstatenow_ms] Trusted current time for middleware and handlers. ```rust pub fn now_ms(&self) -> i64; ``` Source line: `169`. ## auth::AuthState::new [#authauthstatenew] Build process-local SIWS auth for tests and development. ```rust #[cfg(feature = "sigil")] pub fn new( anchor_client: Arc, ) -> Result; ``` Source line: `175`. ## auth::AuthState::with\_clock [#authauthstatewith_clock] Build process-local SIWS auth with a deterministic server clock. ```rust #[cfg(feature = "sigil")] pub fn with_clock( anchor_client: Arc, clock: Arc, ) -> Result; ``` Source line: `183`. ## auth::AuthState::with\_siws\_stores [#authauthstatewith_siws_stores] Build SIWS auth with explicit durable or process-local stores. ```rust #[cfg(feature = "sigil")] pub fn with_siws_stores( anchor_client: Arc, sessions: Arc, challenges: Arc, clock: Arc, session_ttl_ms: i64, challenge_ttl_ms: i64, enabled_profiles: BTreeSet, ) -> Result; ``` Source line: `200`. ## Source provenance [#source-provenance] Source: `mars-server/src/auth/mod.rs` · SHA-256 `43b2f659f5dbebdeb628cf7a2029788b2422f4bff73ee022c24938d8d84284a4`. [Package overview](/libraries/mars-server). # mars-server · bond URL: https://docs.mars.glass/libraries/mars-server/bond Markdown: https://docs.mars.glass/libraries/mars-server/bond.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::bond. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `bond` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## bond::BondPortError [#bondbondporterror] Fail-closed bond dependency errors. ```rust #[derive(Debug, thiserror::Error)] pub enum BondPortError { #[error("bond `{0}` is unknown")] Unknown(String), #[error("bond dependency failed: {0}")] Transport(String), } ``` Source line: `16`. ## bond::BondPort [#bondbondport] Provider-neutral bond lookup and registry-local provisioning seam. ```rust #[async_trait] pub trait BondPort: Send + Sync { /// Resolve a bond from locally available state. async fn resolve(&self, bond_id: &str) -> Result; /// Atomically provision registry-local bond metadata with its audit and /// idempotency response. async fn provision( &self, command: BondCommitCommand, ) -> Result; } ``` Source line: `25`. ## bond::UnavailableBondPort [#bondunavailablebondport] Fail-closed port used when callers construct a pipeline without a store. ```rust pub struct UnavailableBondPort; ``` Source line: `38`. ## bond::RegistryLocalBondPort [#bondregistrylocalbondport] Concrete bond port backed by the active MARS registry store. ```rust pub struct RegistryLocalBondPort { } ``` Source line: `57`. ## bond::RegistryLocalBondPort::new [#bondregistrylocalbondportnew] ```rust #[must_use] pub fn new(store: Arc) -> Self; ``` Source line: `63`. ## Source provenance [#source-provenance] Source: `mars-server/src/bond.rs` · SHA-256 `61d06ad91ea0fda2d5cd3a15ab901930a74a2fae9dc783076c00519848d4d26a`. [Package overview](/libraries/mars-server). # mars-server · config URL: https://docs.mars.glass/libraries/mars-server/config Markdown: https://docs.mars.glass/libraries/mars-server/config.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::config. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `config` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## config::DeploymentEnv [#configdeploymentenv] Deployment environment for the MARS registry server. Parsed from the `MARS_ENV` environment variable. Controls fail-fast production safety checks (see `validate_production_config` in `main.rs`). * `Development` (default) — relaxed checks, localhost defaults allowed. * `Staging` — relaxed checks; primarily used for tagging deployments. * `Production` — strict checks; refuses to start with localhost defaults for Sigil RPC or federation peer URLs. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum DeploymentEnv { #[default] Development, Staging, Production, } ``` Source line: `22`. ## config::DeploymentEnv::parse [#configdeploymentenvparse] Parse a \[`DeploymentEnv`] from a string, case-insensitively. Recognized values: * `"development"` / `"dev"` -> \[`DeploymentEnv::Development`] * `"staging"` / `"stage"` -> \[`DeploymentEnv::Staging`] * `"production"` / `"prod"` -> \[`DeploymentEnv::Production`] Anything else (including the empty string) returns \[`DeploymentEnv::Development`] so misconfiguration cannot silently upgrade a deployment to production. ```rust pub fn parse(raw: &str) -> Self; ``` Source line: `40`. ## config::DeploymentEnv::from\_env [#configdeploymentenvfrom_env] Read \[`DeploymentEnv`] from the `MARS_ENV` environment variable. Returns \[`DeploymentEnv::Development`] when the variable is unset. ```rust pub fn from_env() -> Self; ``` Source line: `51`. ## config::DeploymentEnv::as\_str [#configdeploymentenvas_str] Human-readable label for logs. ```rust pub fn as_str(&self) -> &'static str; ``` Source line: `59`. ## config::TrustKeyAlgorithm [#configtrustkeyalgorithm] Supported algorithms for operator-pinned trust keys. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum TrustKeyAlgorithm { /// Ed25519 verification key encoded as 32-byte hexadecimal. Ed25519, } ``` Source line: `70`. ## config::PinnedPublisherKey [#configpinnedpublisherkey] An operator-pinned publisher verification key. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PinnedPublisherKey { /// Publisher DID controlled by this key. pub publisher_did: String, /// Full DID URL, including key fragment. pub key_id: String, /// Signature algorithm. pub algorithm: TrustKeyAlgorithm, /// Lower- or uppercase hexadecimal encoding of the 32-byte public key. pub public_key_hex: String } ``` Source line: `78`. ## config::PinnedPeerKey [#configpinnedpeerkey] An operator-pinned federation peer verification key. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PinnedPeerKey { /// Registry DID controlled by this key. pub peer_did: String, /// Full DID URL, including key fragment. pub key_id: String, /// Signature algorithm. pub algorithm: TrustKeyAlgorithm, /// Lower- or uppercase hexadecimal encoding of the 32-byte public key. pub public_key_hex: String } ``` Source line: `92`. ## config::TrustConfig [#configtrustconfig] Operator trust roots and bootstrap policy. Optional policy flags have environment-aware defaults: production requires publisher pins and disables self-signed HMR/MHR bootstrap, while local development preserves the explicit bootstrap workflow. ```rust #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TrustConfig { /// Override whether at least one publisher pin is required. #[serde(default, skip_serializing_if = "Option::is_none")] pub require_pinned_publishers: Option, /// Override whether peer pins are required when federation is enabled. #[serde(default, skip_serializing_if = "Option::is_none")] pub require_pinned_peers: Option, /// Override whether a new HMR/MHR may bootstrap from its embedded key. #[serde(default, skip_serializing_if = "Option::is_none")] pub allow_self_signed_bootstrap: Option, /// Trusted publisher keys, resolved before registry-stored keys. #[serde(default)] pub publisher_keys: Vec, /// Trusted federation peer keys, resolved before registry-stored keys. #[serde(default)] pub peer_keys: Vec } ``` Source line: `110`. ## config::TrustConfig::requires\_pinned\_publishers [#configtrustconfigrequires_pinned_publishers] Whether publisher pins are required after environment defaults. ```rust pub fn requires_pinned_publishers(&self, env: DeploymentEnv) -> bool; ``` Source line: `130`. ## config::TrustConfig::requires\_pinned\_peers [#configtrustconfigrequires_pinned_peers] Whether peer pins are required after environment defaults. ```rust pub fn requires_pinned_peers(&self, env: DeploymentEnv, federation_enabled: bool) -> bool; ``` Source line: `136`. ## config::TrustConfig::allows\_self\_signed\_bootstrap [#configtrustconfigallows_self_signed_bootstrap] Whether self-signed root bootstrap is allowed after environment defaults. ```rust pub fn allows_self_signed_bootstrap(&self, env: DeploymentEnv) -> bool; ``` Source line: `142`. ## config::AuthConfig [#configauthconfig] Authentication profiles and server-controlled expiry policy. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthConfig { /// Profiles accepted by the credential registry. #[serde(default = "default_enabled_auth_profiles")] pub enabled_profiles: Vec, /// Session lifetime in milliseconds. #[serde(default = "default_session_ttl_ms")] pub session_ttl_ms: i64, /// Challenge lifetime in milliseconds. #[serde(default = "default_challenge_ttl_ms")] pub challenge_ttl_ms: i64, /// Server-pinned SIWS origin. Client requests may omit it or repeat this /// exact value, but cannot select a different signing origin. #[serde(default = "default_siws_origin")] pub expected_siws_origin: String } ``` Source line: `151`. ## config::AuthConfig::validate [#configauthconfigvalidate] Validate server-controlled authentication lifetimes. ```rust pub fn validate(&self) -> Result<(), crate::ServerError>; ``` Source line: `180`. ## config::DatabaseConfig [#configdatabaseconfig] PostgreSQL pool, connection, session, and maintenance bounds. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DatabaseConfig { /// Minimum warm connections retained by the pool. #[serde(default = "default_min_db_connections")] pub min_connections: u32, /// Maximum connections retained by the pool. #[serde(default = "default_max_db_connections")] pub max_connections: u32, /// Maximum wait for a pooled connection. #[serde(default = "default_db_acquire_timeout_ms")] pub acquire_timeout_ms: u64, /// Maximum wait for initial pool establishment. #[serde(default = "default_db_connect_timeout_ms")] pub connect_timeout_ms: u64, /// Maximum idle lifetime for connections above the minimum. #[serde(default = "default_db_idle_timeout_ms")] pub idle_timeout_ms: u64, /// Maximum lifetime for one physical database connection. #[serde(default = "default_db_max_lifetime_ms")] pub max_lifetime_ms: u64, /// PostgreSQL statement timeout installed on every connection. #[serde(default = "default_db_statement_timeout_ms")] pub statement_timeout_ms: u64, /// PostgreSQL lock wait timeout installed on every connection. #[serde(default = "default_db_lock_timeout_ms")] pub lock_timeout_ms: u64, /// PostgreSQL idle-in-transaction timeout installed on every connection. #[serde(default = "default_db_idle_in_transaction_timeout_ms")] pub idle_in_transaction_session_timeout_ms: u64, /// Interval between out-of-band retention cleanup passes. #[serde(default = "default_db_maintenance_interval_ms")] pub maintenance_interval_ms: u64 } ``` Source line: `236`. ## config::DatabaseConfig::validate [#configdatabaseconfigvalidate] Validate all bounds before opening a connection or binding a listener. ```rust pub fn validate(&self) -> Result<(), crate::ServerError>; ``` Source line: `271`. ## config::SearchConfig [#configsearchconfig] Search pagination integrity and expiry policy. HMAC key fields may be deserialized from a protected config source, but serialization and debug formatting never expose key material. Environment variables override file values during server startup. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SearchConfig { /// Maximum lifetime of an issued pagination chain. #[serde(default = "default_search_cursor_max_age_seconds")] pub cursor_max_age_seconds: u64, /// Opt in to the deterministic development/test key. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub use_insecure_test_cursor_key: bool } ``` Source line: `385`. ## config::SearchConfig::with\_cursor\_keys [#configsearchconfigwith_cursor_keys] Construct typed search configuration from already validated key types. ```rust pub fn with_cursor_keys( active_cursor_hmac_key: crate::search::SearchCursorKey, previous_cursor_hmac_key: Option, cursor_max_age_seconds: u64, ) -> Self; ``` Source line: `417`. ## config::SearchConfig::apply\_environment [#configsearchconfigapply_environment] Apply secret and lifetime overrides from the process environment. Supported variables are `MARS_SEARCH_CURSOR_HMAC_KEY`, `MARS_SEARCH_CURSOR_PREVIOUS_HMAC_KEY`, `MARS_SEARCH_CURSOR_PREVIOUS_HMAC_KEY_EXPIRES_AT`, `MARS_SEARCH_CURSOR_MAX_AGE_SECONDS`, and `MARS_SEARCH_USE_INSECURE_TEST_CURSOR_KEY`. ```rust pub fn apply_environment(&mut self) -> Result<(), crate::ServerError>; ``` Source line: `443`. ## config::SearchConfig::cursor\_codec [#configsearchconfigcursor_codec] Build the runtime codec after enforcing environment-specific policy. ```rust pub fn cursor_codec( &self, env: DeploymentEnv, ) -> Result; ``` Source line: `489`. ## config::SearchConfig::clear\_cursor\_hmac\_keys [#configsearchconfigclear_cursor_hmac_keys] Remove key copies once the runtime codec has been assembled. ```rust pub fn clear_cursor_hmac_keys(&mut self); ``` Source line: `558`. ## config::ServerConfig [#configserverconfig] Top-level configuration for the MARS registry server. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ServerConfig { /// Deployment environment. Not part of the on-disk config — parsed at /// startup from the `MARS_ENV` environment variable. #[serde(skip)] pub env: DeploymentEnv, /// Address to bind the HTTP server. pub listen_addr: SocketAddr, /// Registry DID (e.g. `"did:oas:registry:mars-1"`). pub registry_did: String, /// Maximum entries per discovery query page. pub max_page_size: u64, /// Default page size for discovery queries. pub default_page_size: u64, /// Search cursor integrity, rotation, and expiry policy. #[serde(default)] pub search: SearchConfig, /// Retention window for authenticated mutation idempotency responses. #[serde(default = "default_idempotency_ttl_seconds")] pub idempotency_ttl_seconds: u64, /// Rate limit configuration. pub rate_limits: RateLimitConfig, /// Federation configuration. pub federation: FederationConfig, /// Operator trust roots and root-record bootstrap policy. #[serde(default)] pub trust: TrustConfig, /// Authentication adapters and expiry policy. #[serde(default)] pub auth: AuthConfig, /// PostgreSQL connection URL for durable storage. /// /// **Required in production.** The server refuses to start without this /// unless `MARS_ALLOW_MEMORY_STORE=1` is set (development/CI only). /// /// Example: `"postgres://mars:mars@localhost/mars"` #[serde(skip_serializing_if = "Option::is_none")] pub database_url: Option, /// PostgreSQL resource and timeout policy. #[serde(default)] pub database: DatabaseConfig, /// Anchor configuration for on-chain Sigil anchoring. #[serde(default)] pub anchor: AnchorServerConfig, /// Logging level (e.g. `"info"`, `"debug"`, `"warn"`). #[serde(default = "default_log_level")] pub log_level: String } ``` Source line: `585`. ## config::ServerConfig::env [#configserverconfigenv] Return the deployment environment for this config. ```rust pub fn env(&self) -> DeploymentEnv; ``` Source line: `679`. ## config::SigilSubmissionMode [#configsigilsubmissionmode] Whether MARS only validates would-submit payloads or may submit them. ```rust #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SigilSubmissionMode { /// Call Sigil's no-authority simulation endpoint and retain submitted /// evidence without broadcasting a transaction. #[default] Shadow, /// Broadcast signed transactions when the emergency switch is enabled. Live, } ``` Source line: `687`. ## config::SigilAnchorConfig [#configsigilanchorconfig] Live Sigil RPC and signing policy for GAL reads and anchor submissions. Secret values are never serialized into this structure. The configured fields name environment variables loaded into zeroizing runtime buffers. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SigilAnchorConfig { /// Credential-free JSON-RPC endpoint. #[serde(default, skip_serializing_if = "Option::is_none")] pub rpc_url: Option, #[serde(default = "default_sigil_chain_id")] pub chain_id: String, /// OAS DID whose registered key authorizes signed anchor transactions. #[serde(default, skip_serializing_if = "Option::is_none")] pub sender_did: Option, /// Environment variable containing the RPC bearer token. #[serde(default, skip_serializing_if = "Option::is_none")] pub rpc_token_env: Option, /// Environment variable containing a 32-byte Ed25519 key in base64url or hex. #[serde(default, skip_serializing_if = "Option::is_none")] pub signing_key_env: Option, #[serde(default = "default_sigil_request_timeout_ms")] pub request_timeout_ms: u64, #[serde(default = "default_sigil_connect_timeout_ms")] pub connect_timeout_ms: u64, #[serde(default = "default_sigil_finality_timeout_ms")] pub finality_timeout_ms: u64, #[serde(default = "default_sigil_max_response_bytes")] pub max_response_bytes: usize, #[serde(default = "default_sigil_gas_limit")] pub gas_limit: u64, #[serde(default = "default_sigil_gas_price")] pub gas_price: u64, #[serde(default)] pub mode: SigilSubmissionMode, /// Emergency switch. `false` prevents new live broadcasts while GAL reads, /// shadow validation, and durable outbox records remain available. #[serde(default)] pub submissions_enabled: bool } ``` Source line: `702`. ## config::SigilAnchorConfig::validate\_for [#configsigilanchorconfigvalidate_for] ```rust pub fn validate_for( &self, env: DeploymentEnv, anchoring_enabled: bool, ) -> Result<(), crate::ServerError>; ``` Source line: `758`. ## config::AnchorServerConfig [#configanchorserverconfig] Provider-neutral anchor policy and worker configuration. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AnchorServerConfig { /// Whether mutations enqueue anchor intents and a registered worker runs. pub enabled: bool, /// Whether public discovery requires a confirmed current anchor. #[serde(default)] pub required: bool, #[serde(default = "default_anchor_batch_size")] pub batch_size: u32, #[serde(default = "default_anchor_lease_ms")] pub lease_ms: u64, #[serde(default = "default_anchor_max_attempts", alias = "retryAttempts")] pub max_attempts: u32, #[serde(default = "default_anchor_retry_base_ms")] pub retry_base_ms: u64, #[serde(default = "default_anchor_retry_max_ms")] pub retry_max_ms: u64, #[serde(default = "default_anchor_jitter_bps")] pub jitter_bps: u16, #[serde(default = "default_anchor_confirmation_poll_ms")] pub confirmation_poll_ms: u64, /// Time confirmed/abandoned intents remain in the hot outbox before /// archival. Historical records and receipts remain queryable. #[serde(default = "default_anchor_terminal_retention_ms")] pub terminal_retention_ms: u64, /// Maximum terminal intents moved by one maintenance transaction. #[serde(default = "default_anchor_terminal_archive_batch_size")] pub terminal_archive_batch_size: u32, /// Concrete Sigil integration configuration. #[serde(default)] pub sigil: SigilAnchorConfig } ``` Source line: `886`. ## config::AnchorServerConfig::validate [#configanchorserverconfigvalidate] Validate worker and terminal-retention bounds before startup. ```rust pub fn validate(&self, env: DeploymentEnv) -> Result<(), crate::ServerError>; ``` Source line: `939`. ## config::AnchorServerConfig::terminal\_retention [#configanchorserverconfigterminal_retention] Validated terminal-retention duration. ```rust pub fn terminal_retention(&self) -> Result; ``` Source line: `962`. ## config::AnchorServerConfig::worker\_config [#configanchorserverconfigworker_config] Convert wire/config milliseconds into the worker's validated durations. ```rust pub fn worker_config(&self) -> Result; ``` Source line: `972`. ## config::RateLimitConfig [#configratelimitconfig] Rate limit configuration per client. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RateLimitConfig { /// Max write operations per minute per client. pub writes_per_minute: u32, /// Max read operations per minute per client. pub reads_per_minute: u32, /// Max discovery queries per minute per client. pub queries_per_minute: u32, /// Max authentication operations per minute per network client. #[serde(default = "default_auth_per_minute")] pub auth_per_minute: u32, /// Max WebSocket upgrade attempts per minute per network client. #[serde(default = "default_websocket_per_minute")] pub websocket_per_minute: u32, /// Hard cap on resident client buckets in each limiter. #[serde(default = "default_max_client_buckets")] pub max_client_buckets: u32, /// Inactivity TTL for each client bucket. #[serde(default = "default_bucket_ttl_seconds")] pub bucket_ttl_seconds: u64, /// Proxy networks allowed to supply `Forwarded` or `X-Forwarded-For`. /// /// Forwarding headers from every other direct peer are ignored. #[serde(default)] pub trusted_proxy_cidrs: Vec } ``` Source line: `1046`. ## config::RateLimitConfig::validate [#configratelimitconfigvalidate] Validate the hard memory and lifetime bounds shared by all limiters. ```rust pub fn validate(&self) -> Result<(), crate::ServerError>; ``` Source line: `1096`. ## config::MtlsConfig [#configmtlsconfig] Optional mutual-TLS material for one federation peer. Secret-bearing paths are accepted from protected runtime configuration but are deliberately omitted from serialization and debug output. ```rust #[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MtlsConfig { /// Require a client certificate and private trust root for this peer. #[serde(default)] pub enabled: bool, /// PEM client certificate chain. #[serde(default, skip_serializing)] pub certificate_path: Option, /// PKCS#8 PEM private key. The loader rejects symlinks and permissive Unix /// file modes. #[serde(default, skip_serializing)] pub private_key_path: Option, /// PEM CA certificate used to authenticate the peer. #[serde(default, skip_serializing)] pub ca_certificate_path: Option } ``` Source line: `1133`. ## config::MtlsConfig::validate [#configmtlsconfigvalidate] Validate the all-or-nothing mTLS contract before any network request. ```rust pub fn validate(&self) -> Result<(), crate::ServerError>; ``` Source line: `1163`. ## config::FederationPeerConfig [#configfederationpeerconfig] One identity-bound outbound federation peer. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct FederationPeerConfig { /// Canonical OAS `service` DID expected in signed responses. pub peer_did: String, /// HTTPS base URL. pub endpoint: String, /// Narrow CIDRs permitted to resolve to non-public addresses. #[serde(default)] pub allow_private_cidrs: Vec, /// Persisted agreements that authorize traffic with this peer. #[serde(default)] pub agreement_ids: Vec, /// Optional fail-closed client certificate configuration. #[serde(default)] pub mtls: MtlsConfig } ``` Source line: `1203`. ## config::FederationPeerConfig::new [#configfederationpeerconfignew] ```rust #[must_use] pub fn new(peer_did: impl Into, endpoint: impl Into) -> Self; ``` Source line: `1221`. ## config::MAX\_FEDERATION\_DISCOVERY\_PEERS [#configmax_federation_discovery_peers] Absolute peer fanout bound accepted by federation configuration. ```rust pub const MAX_FEDERATION_DISCOVERY_PEERS: u32; ``` Source line: `1233`. ## config::MAX\_FEDERATION\_DISCOVERY\_COST [#configmax_federation_discovery_cost] Absolute remote result-slot budget accepted by federation configuration. ```rust pub const MAX_FEDERATION_DISCOVERY_COST: u64; ``` Source line: `1235`. ## config::FederationConfig [#configfederationconfig] Federation configuration for registry peering, synchronization, and optional distributed discovery. ```rust #[derive(Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FederationConfig { /// Whether federation is enabled. pub enabled: bool, /// Sync interval in seconds. pub sync_interval_secs: u64, /// Maximum entries per sync batch. pub max_sync_batch: u32, /// Identity-bound peers contacted by workers and discovery fanout. #[serde(default)] pub peers: Vec, /// Durable bilateral agreement documents. #[serde(default)] pub agreements: Vec, /// Maximum peers synchronized concurrently. #[serde(default = "default_federation_max_concurrency")] pub max_concurrency: u32, /// End-to-end request timeout. #[serde(default = "default_federation_request_timeout_ms")] pub request_timeout_ms: u64, /// TCP/TLS establishment timeout. #[serde(default = "default_federation_connect_timeout_ms")] pub connect_timeout_ms: u64, /// Maximum accepted envelope clock difference. #[serde(default = "default_federation_clock_skew_seconds")] pub clock_skew_seconds: u64, /// Durable replay nonce retention. #[serde(default = "default_federation_nonce_ttl_seconds")] pub nonce_ttl_seconds: u64, /// Failed attempts before a peer's breaker opens. #[serde(default = "default_federation_breaker_threshold")] pub breaker_failure_threshold: u32, /// Breaker cooldown before one half-open probe. #[serde(default = "default_federation_breaker_cooldown_ms")] pub breaker_cooldown_ms: u64, /// Initial exponential retry delay. #[serde(default = "default_federation_retry_base_ms")] pub retry_base_ms: u64, /// Maximum exponential retry delay. #[serde(default = "default_federation_retry_max_ms")] pub retry_max_ms: u64, /// Symmetric retry jitter in basis points. #[serde(default = "default_federation_jitter_bps")] pub jitter_bps: u16, /// Enable bounded peer discovery fanout. #[serde(default)] pub discovery_enabled: bool, /// Maximum peers queried for one federated discovery request. #[serde(default = "default_federation_discovery_fanout")] pub discovery_fanout: u32, /// Per-peer discovery deadline. #[serde(default = "default_federation_discovery_timeout_ms")] pub discovery_timeout_ms: u64, /// Maximum results requested from each peer before local merge. #[serde(default = "default_federation_discovery_results")] pub discovery_max_results_per_peer: u32, /// Maximum remote result slots consumed by one federated discovery call. /// /// Cost is computed before fanout as selected peers multiplied by /// `discoveryMaxResultsPerPeer`. #[serde(default = "default_federation_discovery_max_cost")] pub discovery_max_cost: u64, /// Sender key DID URL. Public metadata, safe to serialize. #[serde(default, skip_serializing_if = "Option::is_none")] pub signing_key_id: Option, /// Protected path containing exactly one 32-byte seed, encoded as /// canonical unpadded base64url. Never serialized. #[serde(default, skip_serializing)] pub signing_key_path: Option, /// Environment variable holding the same canonical secret. Never /// serialized. Exactly one path/environment source may be selected. #[serde(default, skip_serializing)] pub signing_key_env: Option } ``` Source line: `1242`. ## config::FederationConfig::validate [#configfederationconfigvalidate] Validate bounded worker/discovery policy and secret-source selection. ```rust pub fn validate(&self) -> Result<(), crate::ServerError>; ``` Source line: `1386`. ## Source provenance [#source-provenance] Source: `mars-server/src/config.rs` · SHA-256 `de9705a79c897fbac6d8bfe433db96ee8c530f4c7044d0c8ab7b36590ad1b78b`. [Package overview](/libraries/mars-server). # mars-server · contracts URL: https://docs.mars.glass/libraries/mars-server/contracts Markdown: https://docs.mars.glass/libraries/mars-server/contracts.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::contracts. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `contracts` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## Module condition [#module-condition] ```rust #[cfg(feature = "contracts")] ``` ## contracts::GeneratedArtifact [#contractsgeneratedartifact] A generated contract file and its canonical contents. ```rust #[cfg(feature = "contracts")] #[derive(Debug, Clone, PartialEq, Eq)] pub struct GeneratedArtifact { /// Repository-relative output path. pub relative_path: String, /// UTF-8 JSON content with stable key ordering and a trailing newline. pub contents: String } ``` Source line: `31`. ## contracts::ContractGenerationError [#contractscontractgenerationerror] Contract generation failures. ```rust #[cfg(feature = "contracts")] #[derive(Debug, thiserror::Error)] pub enum ContractGenerationError { /// A Rust-derived schema or OpenAPI value could not be serialized. #[error("contract serialization failed: {0}")] Serialization(#[from] serde_json::Error), } ``` Source line: `40`. ## contracts::generated\_artifacts [#contractsgenerated_artifacts] Generate the complete frozen contract set from Rust source types. ```rust #[cfg(feature = "contracts")] pub fn generated_artifacts() -> Result, ContractGenerationError>; ``` Source line: `193`. ## Source provenance [#source-provenance] Source: `mars-server/src/contracts.rs` · SHA-256 `6381de51d0be15e114686dfc9230ff7cf5c434bfafba7da8ca44e68c728920cd`. [Package overview](/libraries/mars-server). # mars-server · discovery URL: https://docs.mars.glass/libraries/mars-server/discovery Markdown: https://docs.mars.glass/libraries/mars-server/discovery.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::discovery. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `discovery` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## discovery::DiscoveryEngine [#discoverydiscoveryengine] Discovery engine that executes MARS-QL queries against a store. ```rust pub struct DiscoveryEngine { } ``` Source line: `45`. ## discovery::DiscoveryEngine::new [#discoverydiscoveryenginenew] Create a new discovery engine backed by the given store. ```rust pub fn new( store: Arc, default_page_size: u64, max_page_size: u64, cursor_codec: SearchCursorCodec, ) -> Self; ``` Source line: `56`. ## discovery::DiscoveryEngine::with\_anchor\_policy [#discoverydiscoveryenginewith_anchor_policy] Create a discovery engine with the registry's anchoring visibility policy. ```rust pub fn with_anchor_policy( store: Arc, default_page_size: u64, max_page_size: u64, anchoring_required: bool, cursor_codec: SearchCursorCodec, ) -> Self; ``` Source line: `74`. ## discovery::DiscoveryEngine::with\_semantic\_search\_port [#discoverydiscoveryenginewith_semantic_search_port] Register a MARS-owned semantic adapter without coupling MARS to a concrete cognitive engine. ```rust #[must_use] pub fn with_semantic_search_port(mut self, port: Arc) -> Self; ``` Source line: `94`. ## discovery::DiscoveryEngine::execute [#discoverydiscoveryengineexecute] Execute a MARS-QL query and return matching entries. ```rust pub async fn execute(&self, query: &MarsQuery) -> Result; ``` Source line: `100`. ## discovery::DiscoveryEngine::execute\_semantic [#discoverydiscoveryengineexecute_semantic] Execute semantic discovery when an adapter has been explicitly registered. The default is a fail-closed disabled result. ```rust pub async fn execute_semantic( &self, request: &SemanticSearchRequest, ) -> Result, SemanticSearchError>; ``` Source line: `114`. ## discovery::execute\_query [#discoveryexecute_query] Execute a MARS-QL query against a store (stateless entry point). This function performs the full query pipeline: filtering, sorting (or ranking if no explicit ordering), and pagination. It is the canonical implementation used by both the struct-based \[`DiscoveryEngine`] and the REST/WebSocket API handlers. ```rust pub async fn execute_query( store: &dyn EntryStore, query: &MarsQuery, default_limit: u64, max_limit: u64, cursor_codec: &SearchCursorCodec, ) -> Result; ``` Source line: `135`. ## discovery::compute\_ranking\_score [#discoverycompute_ranking_score] Compute the 5-component composite ranking score for an entry. Each component is normalized to `[0, 1]` and multiplied by its weight. The result is in `[0, 1]`. ```rust pub fn compute_ranking_score(entry: &MarsEntry, query: &MarsQuery) -> f64; ``` Source line: `187`. ## discovery::execute\_sharded\_query [#discoveryexecute_sharded_query] Execute a sharded MARS-QL query using scatter-gather. When the `sharding` feature is enabled, this function: 1. Extracts shard hints from the \[`ShardedQuery`] to determine target shards. 2. Scatter-queries only the relevant shards (or all if no hints). 3. Gathers results, applies sorting/ranking, and paginates. ```rust #[cfg(feature = "sharding")] pub async fn execute_sharded_query( sharded_store: &dyn crate::store::ShardedStore, sharded_query: &mars_protocol::marsql::ShardedQuery, default_limit: u64, max_limit: u64, cursor_codec: &SearchCursorCodec, ) -> Result; ``` Source line: `275`. ## Source provenance [#source-provenance] Source: `mars-server/src/discovery/mod.rs` · SHA-256 `417462ed94da91b0ef8180bbfd24c01c63a6aa490b53fc6c6df472c6f35cb8c9`. [Package overview](/libraries/mars-server). # mars-server · error URL: https://docs.mars.glass/libraries/mars-server/error Markdown: https://docs.mars.glass/libraries/mars-server/error.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::error. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `error` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## pub use mars\_protocol::api::ErrorResponse; [#pub-use-mars_protocolapierrorresponse] ```rust pub use mars_protocol::api::ErrorResponse; ``` Source line: `5`. ## error::ServerError [#errorservererror] Unified error type for MARS server operations. ```rust #[derive(Debug, thiserror::Error)] pub enum ServerError { /// An error originating from the MARS protocol layer. #[error(transparent)] Protocol(#[from] MarsError), /// A storage backend error. #[error("store error: {0}")] Store(String), /// A request-level validation error. #[error("validation failed: {0}")] Validation(String), /// Client has exceeded the configured rate limit. #[error("rate limited")] RateLimited, /// Request body exceeded the route's explicit admission bound. #[error("request body too large")] PayloadTooLarge, /// A federation or inter-registry communication error. #[error("federation error: {0}")] Federation(String), /// An unexpected internal server error. #[error("internal error: {0}")] Internal(String), } ``` Source line: `10`. ## Source provenance [#source-provenance] Source: `mars-server/src/error.rs` · SHA-256 `badb879bf4d9bfbd35f9c8a15f3ccada675cd828823a8d8feeae868053701cba`. [Package overview](/libraries/mars-server). # mars-server · federation URL: https://docs.mars.glass/libraries/mars-server/federation Markdown: https://docs.mars.glass/libraries/mars-server/federation.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::federation. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `federation` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## pub use discovery::\{FederatedDiscoveryConfig, FederatedDiscoveryCoordinator}; [#pub-use-discoveryfederateddiscoveryconfig-federateddiscoverycoordinator] ```rust pub use discovery::{FederatedDiscoveryConfig, FederatedDiscoveryCoordinator}; ``` Source line: `16`. ## pub use envelope::\{ [#pub-use-envelope] canonical\_digest, envelope\_digest, FederationEnvelopeError, FederationEnvelopeVerifier, FederationSigner, VerifiedFederationMessage, }; ```rust pub use envelope::{ canonical_digest, envelope_digest, FederationEnvelopeError, FederationEnvelopeVerifier, FederationSigner, VerifiedFederationMessage, }; ``` Source line: `17`. ## pub use policy::\{ [#pub-use-policy] resolve\_peer\_endpoint, resolve\_verified\_conflict, validate\_peer\_url\_and\_addresses, ConflictResolutionError, ConflictWinner, PeerNetworkError, VersionTrust, }; ```rust pub use policy::{ resolve_peer_endpoint, resolve_verified_conflict, validate_peer_url_and_addresses, ConflictResolutionError, ConflictWinner, PeerNetworkError, VersionTrust, }; ``` Source line: `21`. ## pub use service::FederationService; [#pub-use-servicefederationservice] ```rust pub use service::FederationService; ``` Source line: `25`. ## pub use transport::\{ [#pub-use-transport] FederationTransport, FederationTransportError, FederationTransportRegistry, ReqwestFederationTransport, }; ```rust pub use transport::{ FederationTransport, FederationTransportError, FederationTransportRegistry, ReqwestFederationTransport, }; ``` Source line: `26`. ## pub use worker::\{ [#pub-use-worker] FederationRunSummary, FederationSyncWorker, FederationWorkerConfig, FederationWorkerError, }; ```rust pub use worker::{ FederationRunSummary, FederationSyncWorker, FederationWorkerConfig, FederationWorkerError, }; ``` Source line: `30`. ## federation::FederationManager [#federationfederationmanager] Manages federation sync operations between MARS registries. ```rust pub struct FederationManager { } ``` Source line: `54`. ## federation::FederationManager::new [#federationfederationmanagernew] Create a new federation manager. ```rust pub fn new(config: FederationConfig, store: Arc) -> Self; ``` Source line: `63`. ## federation::FederationManager::handle\_sync [#federationfederationmanagerhandle_sync] Handle an incoming sync request from a peer. Returns a \[`SyncResponse`] containing entries whose sequence number is greater than `req.from_sequence`, up to `req.max_entries`. ```rust pub async fn handle_sync(&self, req: &SyncRequest) -> Result; ``` Source line: `71`. ## federation::FederationManager::is\_enabled [#federationfederationmanageris_enabled] Returns whether federation is enabled. ```rust pub fn is_enabled(&self) -> bool; ``` Source line: `108`. ## federation::FederationManager::sync\_interval\_secs [#federationfederationmanagersync_interval_secs] Returns the configured sync interval in seconds. ```rust pub fn sync_interval_secs(&self) -> u64; ``` Source line: `113`. ## federation::ShardedFederationManager [#federationshardedfederationmanager] Shard-aware federation manager extension. When the `sharding` feature is enabled, this adds shard metadata to sync responses so that receiving peers can place entries in the correct shard. ```rust #[cfg(feature = "sharding")] pub struct ShardedFederationManager { /// Base federation manager. pub inner: FederationManager } ``` Source line: `127`. ## federation::ShardedFederationManager::new [#federationshardedfederationmanagernew] Create a new shard-aware federation manager. ```rust #[cfg(feature = "sharding")] pub fn new( config: FederationConfig, store: Arc, sharded_store: Arc, ) -> Self; ``` Source line: `137`. ## federation::ShardedFederationManager::handle\_sharded\_sync [#federationshardedfederationmanagerhandle_sharded_sync] Handle a sync request, annotating entries with their shard assignments. ```rust #[cfg(feature = "sharding")] pub async fn handle_sharded_sync( &self, req: &mars_protocol::federation::SyncRequest, ) -> Result; ``` Source line: `149`. ## federation::ShardedSyncResponse [#federationshardedsyncresponse] A sync response extended with shard placement metadata. ```rust #[cfg(feature = "sharding")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ShardedSyncResponse { /// The base sync response. #[serde(flatten)] pub base: mars_protocol::federation::SyncResponse, /// Entry DID -> shard ID assignments for each synced entry. pub shard_assignments: Vec<(String, String)>, /// All shard IDs known to the source registry. pub shard_ids: Vec } ``` Source line: `179`. ## federation::verify\_anchor\_for\_conflict [#federationverify_anchor_for_conflict] Verify that a conflict entry has a genuine on-chain anchor, not just metadata. This verifies only the persisted receipt material. Live provider queries belong behind the MARS-owned anchor worker port and never run during federation conflict resolution. Returns `true` if the entry has a verified on-chain anchor. # Errors [#errors] ```rust #[cfg(feature = "sigil")] pub fn verify_anchor_for_conflict( entry: &MarsEntry, anchor: &mars_protocol::anchor::AnchorRecord, ) -> bool; ``` Source line: `205`. ## Source provenance [#source-provenance] Source: `mars-server/src/federation/mod.rs` · SHA-256 `c9af129e4e0a7761a81dd78d2f22610e29ffb14b9b7ae4ee0685f84bbd653870`. [Package overview](/libraries/mars-server). # mars-server URL: https://docs.mars.glass/libraries/mars-server Markdown: https://docs.mars.glass/libraries/mars-server.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Registry HTTP server, authorization, durable storage, query planning, federation, and anchor outbox. Registry HTTP server, authorization, durable storage, query planning, federation, and anchor outbox. Use this crate to operate or embed the reference registry. The public router and store interfaces are implementation APIs, not guarantees of an already available hosted service. ## Package contract [#package-contract] Workspace version: **0.1.0**. Rust edition **2021**, minimum declared toolchain **1.81**, Apache-2.0 license. Protocol wire version stays **1.0.0**. Use the source checkout as the installation authority; package registry publication is not verified by this documentation build. In a consumer Cargo manifest, use an explicit path dependency to your checked-out crate. ```toml [dependencies] mars-server = { path = "../mars/mars-server" } ``` ## Feature flags [#feature-flags] | Feature | Enables | | ------------- | -------------------------------------------------------------- | | `default` | `postgres`, `sigil` | | `contracts` | `mars-protocol/contracts`, `mars-protocol/sigil`, `dep:utoipa` | | `sigil` | `mars-protocol/sigil`, `dep:sigil-sdk` | | `sharding` | `dep:mars-shard`, `mars-protocol/sharding` | | `postgres` | `dep:sqlx-core`, `dep:sqlx-postgres` | | `prod` | `mars-protocol/prod` | | `test-anchor` | Marker feature | ## Public root modules [#public-root-modules] `anchor`, `api`, `auth`, `bond`, `config`, `contracts`, `discovery`, `error`, `federation`, `middleware`, `observability`, `production`, `search`, `store`, `validation`. Conditional availability follows the source attributes. ## Public module reference [#public-module-reference] | Module | Source | | --------------------------------------------------------------------- | ----------------------------------------- | | [crate](/libraries/mars-server/root) | `mars-server/src/lib.rs` | | [anchor](/libraries/mars-server/anchor) | `mars-server/src/anchor/mod.rs` | | [anchor::config](/libraries/mars-server/anchor/config) | `mars-server/src/anchor/config.rs` | | [anchor::sigil](/libraries/mars-server/anchor/sigil) | `mars-server/src/anchor/sigil.rs` | | [anchor::test\_adapter](/libraries/mars-server/anchor/test_adapter) | `mars-server/src/anchor/test_adapter.rs` | | [api](/libraries/mars-server/api) | `mars-server/src/api/mod.rs` | | [api::rest](/libraries/mars-server/api/rest) | `mars-server/src/api/rest.rs` | | [api::websocket](/libraries/mars-server/api/websocket) | `mars-server/src/api/websocket.rs` | | [auth](/libraries/mars-server/auth) | `mars-server/src/auth/mod.rs` | | [auth::adapters](/libraries/mars-server/auth/adapters) | `mars-server/src/auth/adapters/mod.rs` | | [auth::adapters::siws](/libraries/mars-server/auth/adapters/siws) | `mars-server/src/auth/adapters/siws.rs` | | [auth::challenge\_store](/libraries/mars-server/auth/challenge_store) | `mars-server/src/auth/challenge_store.rs` | | [auth::handlers](/libraries/mars-server/auth/handlers) | `mars-server/src/auth/handlers.rs` | | [auth::principal](/libraries/mars-server/auth/principal) | `mars-server/src/auth/principal.rs` | | [auth::registry](/libraries/mars-server/auth/registry) | `mars-server/src/auth/registry.rs` | | [auth::session\_store](/libraries/mars-server/auth/session_store) | `mars-server/src/auth/session_store.rs` | | [bond](/libraries/mars-server/bond) | `mars-server/src/bond.rs` | | [config](/libraries/mars-server/config) | `mars-server/src/config.rs` | | [contracts](/libraries/mars-server/contracts) | `mars-server/src/contracts.rs` | | [discovery](/libraries/mars-server/discovery) | `mars-server/src/discovery/mod.rs` | | [error](/libraries/mars-server/error) | `mars-server/src/error.rs` | | [federation](/libraries/mars-server/federation) | `mars-server/src/federation/mod.rs` | | [federation::discovery](/libraries/mars-server/federation/discovery) | `mars-server/src/federation/discovery.rs` | | [federation::envelope](/libraries/mars-server/federation/envelope) | `mars-server/src/federation/envelope.rs` | | [federation::policy](/libraries/mars-server/federation/policy) | `mars-server/src/federation/policy.rs` | | [federation::service](/libraries/mars-server/federation/service) | `mars-server/src/federation/service.rs` | | [federation::transport](/libraries/mars-server/federation/transport) | `mars-server/src/federation/transport.rs` | | [federation::worker](/libraries/mars-server/federation/worker) | `mars-server/src/federation/worker.rs` | | [middleware](/libraries/mars-server/middleware) | `mars-server/src/middleware/mod.rs` | | [middleware::auth](/libraries/mars-server/middleware/auth) | `mars-server/src/middleware/auth.rs` | | [observability](/libraries/mars-server/observability) | `mars-server/src/observability/mod.rs` | | [production](/libraries/mars-server/production) | `mars-server/src/production.rs` | | [search](/libraries/mars-server/search) | `mars-server/src/search.rs` | | [store](/libraries/mars-server/store) | `mars-server/src/store/mod.rs` | | [store::memory](/libraries/mars-server/store/memory) | `mars-server/src/store/memory.rs` | | [store::postgres](/libraries/mars-server/store/postgres) | `mars-server/src/store/postgres.rs` | | [store::sharded\_memory](/libraries/mars-server/store/sharded_memory) | `mars-server/src/store/sharded_memory.rs` | | [validation](/libraries/mars-server/validation) | `mars-server/src/validation/mod.rs` | | [validation::resolver](/libraries/mars-server/validation/resolver) | `mars-server/src/validation/resolver.rs` | ## API documentation boundary [#api-documentation-boundary] The linked pages contain syntax-derived public declarations, method signatures, and documentation comments. They omit function bodies and constant values, and skip test-only modules. Compiler-resolved re-exports, trait resolution, and target availability require Rustdoc with the selected feature profile; no backend build or conformance tests ran here. [Three actual binaries](/cli/overview) cover server startup, contract generation/checks, and ledger verification. Production rejects mock/test anchor combinations. # mars-server · middleware URL: https://docs.mars.glass/libraries/mars-server/middleware Markdown: https://docs.mars.glass/libraries/mars-server/middleware.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::middleware. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `middleware` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## middleware::auth [#middlewareauth] Middleware for the MARS registry server. Currently provides: * A bounded token-bucket \[`RateLimiter`] keyed by fixed-size client hashes. * Trusted-proxy-aware transport identity and route admission middleware. * \[`auth::require_capability`] — provider-neutral session and capability authorization for mutation endpoints. ```rust pub mod auth; ``` Source line: `9`. ## middleware::RateLimiter [#middlewareratelimiter] Token-bucket rate limiter. Each client key maps to a bucket containing a remaining token count and the last refill timestamp. When a request arrives, the bucket is refilled based on elapsed time, then one token is consumed. If no tokens remain the request is rejected. The bucket map is hard-capped, stale buckets expire, and new keys evict the least-recently-seen bucket with a lexical hashed-key tie-breaker. This keeps memory bounded and makes eviction deterministic across replicas receiving the same request order. ```rust pub struct RateLimiter { } ``` Source line: `55`. ## middleware::RateLimiter::new [#middlewareratelimiternew] Create a new rate limiter. `max_per_minute` sets both the bucket capacity and defines the refill interval as 60 seconds (one minute). ```rust pub fn new(max_per_minute: u32) -> Self; ``` Source line: `68`. ## middleware::RateLimiter::with\_policy [#middlewareratelimiterwith_policy] Create a limiter with explicit, validated memory bounds. ```rust pub fn with_policy( max_per_minute: u32, max_buckets: usize, bucket_ttl: Duration, ) -> Result; ``` Source line: `78`. ## middleware::RateLimiter::check [#middlewareratelimitercheck] Check if a request from `client_key` is allowed. Returns `true` if the request should proceed, `false` if rate-limited. Calling this method consumes one token from the client's bucket. ```rust pub fn check(&self, client_key: &str) -> bool; ``` Source line: `105`. ## middleware::ClientIdentity [#middlewareclientidentity] Stable, privacy-minimal identity used only for in-process admission policy. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClientIdentity(Arc); ``` Source line: `191`. ## middleware::ClientIdentity::as\_key [#middlewareclientidentityas_key] Canonical rate-limit key. ```rust pub fn as_key(&self) -> &str; ``` Source line: `203`. ## middleware::ClientIdentity::audit\_actor [#middlewareclientidentityaudit_actor] Pseudonymous actor identifier for pre-authentication audit records. ```rust pub fn audit_actor(&self) -> String; ``` Source line: `208`. ## middleware::ClientIdentityResolver [#middlewareclientidentityresolver] Resolve a client from the direct transport peer and explicitly trusted proxy networks. Forwarding headers are ignored unless the direct peer is in one of the configured CIDRs. ```rust #[derive(Debug, Clone)] pub struct ClientIdentityResolver { } ``` Source line: `219`. ## middleware::ClientIdentityResolver::new [#middlewareclientidentityresolvernew] ```rust pub fn new(trusted_proxies: Vec) -> Self; ``` Source line: `224`. ## middleware::ClientIdentityResolver::resolve [#middlewareclientidentityresolverresolve] ```rust pub fn resolve(&self, headers: &HeaderMap, direct_peer: Option) -> ClientIdentity; ``` Source line: `230`. ## middleware::attach\_client\_identity [#middlewareattach_client_identity] Attach one trusted client identity before admission middleware executes. ```rust pub async fn attach_client_identity( State(resolver): State, mut request: Request, next: Next, ) -> Response; ``` Source line: `367`. ## middleware::RateLimitRequirement [#middlewareratelimitrequirement] Route-level rate-limit policy. ```rust #[derive(Clone)] pub struct RateLimitRequirement { } ``` Source line: `383`. ## middleware::RateLimitRequirement::new [#middlewareratelimitrequirementnew] ```rust pub fn new(app: Arc, bucket: RateLimitBucket) -> Self; ``` Source line: `389`. ## middleware::enforce\_rate\_limit [#middlewareenforce_rate_limit] Enforce a route's per-client admission limit. ```rust pub async fn enforce_rate_limit( State(requirement): State, request: Request, next: Next, ) -> Response; ``` Source line: `395`. ## Source provenance [#source-provenance] Source: `mars-server/src/middleware/mod.rs` · SHA-256 `732e7b9b7e17859558d5273773a27ae777c1a1b668afbaaff91801af53d1e425`. [Package overview](/libraries/mars-server). # mars-server · observability URL: https://docs.mars.glass/libraries/mars-server/observability Markdown: https://docs.mars.glass/libraries/mars-server/observability.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::observability. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `observability` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## observability::HTTP\_REQUESTS\_TOTAL [#observabilityhttp_requests_total] Counter: `mars_http_requests_total{method, route, status}`. ```rust pub const HTTP_REQUESTS_TOTAL: &str; ``` Source line: `51`. ## observability::HTTP\_REQUEST\_DURATION\_SECONDS [#observabilityhttp_request_duration_seconds] Histogram: `mars_http_request_duration_seconds{method, route}`. ```rust pub const HTTP_REQUEST_DURATION_SECONDS: &str; ``` Source line: `53`. ## observability::ENTRIES\_CREATED\_TOTAL [#observabilityentries_created_total] Counter: `mars_entries_created_total{entry_type}`. ```rust pub const ENTRIES_CREATED_TOTAL: &str; ``` Source line: `56`. ## observability::ENTRIES\_UPDATED\_TOTAL [#observabilityentries_updated_total] Counter: `mars_entries_updated_total{entry_type}`. ```rust pub const ENTRIES_UPDATED_TOTAL: &str; ``` Source line: `58`. ## observability::ENTRIES\_REVOKED\_TOTAL [#observabilityentries_revoked_total] Counter: `mars_entries_revoked_total`. ```rust pub const ENTRIES_REVOKED_TOTAL: &str; ``` Source line: `60`. ## observability::VALIDATION\_REJECTIONS\_TOTAL [#observabilityvalidation_rejections_total] Counter: `mars_validation_rejections_total{reason}`. Canonical `reason` labels: `schema`, `signature`, `hash`, `bond`, `sequence`, `did_format`. ```rust pub const VALIDATION_REJECTIONS_TOTAL: &str; ``` Source line: `66`. ## observability::ANCHOR\_SUBMISSIONS\_TOTAL [#observabilityanchor_submissions_total] Counter: `mars_anchor_submissions_total{outcome}`. Canonical `outcome` labels: `submitted`, `confirmed`, `failed`. ```rust pub const ANCHOR_SUBMISSIONS_TOTAL: &str; ``` Source line: `71`. ## observability::ANCHOR\_CONFIRM\_LATENCY\_SECONDS [#observabilityanchor_confirm_latency_seconds] Histogram: `mars_anchor_confirm_latency_seconds`. ```rust pub const ANCHOR_CONFIRM_LATENCY_SECONDS: &str; ``` Source line: `74`. ## observability::ANCHOR\_OUTBOX\_BACKLOG [#observabilityanchor_outbox_backlog] Gauge: non-terminal anchor intents. ```rust pub const ANCHOR_OUTBOX_BACKLOG: &str; ``` Source line: `76`. ## observability::ANCHOR\_OUTBOX\_OLDEST\_AGE\_SECONDS [#observabilityanchor_outbox_oldest_age_seconds] Gauge: age of the oldest non-terminal anchor intent. ```rust pub const ANCHOR_OUTBOX_OLDEST_AGE_SECONDS: &str; ``` Source line: `78`. ## observability::ANCHOR\_OUTBOX\_ATTEMPTS [#observabilityanchor_outbox_attempts] Gauge: durable submission-attempt count across the outbox. ```rust pub const ANCHOR_OUTBOX_ATTEMPTS: &str; ``` Source line: `80`. ## observability::ANCHOR\_OUTBOX\_MAX\_ATTEMPTS [#observabilityanchor_outbox_max_attempts] Gauge: maximum attempts observed on one intent. ```rust pub const ANCHOR_OUTBOX_MAX_ATTEMPTS: &str; ``` Source line: `82`. ## observability::ANCHOR\_OUTBOX\_STATE [#observabilityanchor_outbox_state] Gauge: current intent count labelled by bounded outbox state. ```rust pub const ANCHOR_OUTBOX_STATE: &str; ``` Source line: `84`. ## observability::ANCHOR\_OUTBOX\_RETAINED\_TERMINAL [#observabilityanchor_outbox_retained_terminal] Gauge: confirmed/abandoned rows still retained in the hot outbox. ```rust pub const ANCHOR_OUTBOX_RETAINED_TERMINAL: &str; ``` Source line: `86`. ## observability::ANCHOR\_OUTBOX\_ARCHIVED\_TERMINAL [#observabilityanchor_outbox_archived_terminal] Gauge: cumulative archived terminal rows labelled by terminal state. ```rust pub const ANCHOR_OUTBOX_ARCHIVED_TERMINAL: &str; ``` Source line: `88`. ## observability::ANCHOR\_WORKER\_DEGRADED [#observabilityanchor_worker_degraded] Gauge: anchor worker degraded state (`1` degraded, `0` healthy). ```rust pub const ANCHOR_WORKER_DEGRADED: &str; ``` Source line: `90`. ## observability::ANCHOR\_WORKER\_CONSECUTIVE\_FAILURES [#observabilityanchor_worker_consecutive_failures] Gauge: consecutive failed anchor supervisor passes. ```rust pub const ANCHOR_WORKER_CONSECUTIVE_FAILURES: &str; ``` Source line: `92`. ## observability::ANCHOR\_WORKER\_ERRORS\_TOTAL [#observabilityanchor_worker_errors_total] Counter: bounded anchor worker infrastructure error source. ```rust pub const ANCHOR_WORKER_ERRORS_TOTAL: &str; ``` Source line: `94`. ## observability::SIGIL\_SHADOW\_PARITY\_TOTAL [#observabilitysigil_shadow_parity_total] Counter: deterministic Sigil would-submit parity checks. ```rust pub const SIGIL_SHADOW_PARITY_TOTAL: &str; ``` Source line: `96`. ## observability::LEDGER\_CHAIN\_INTEGRITY [#observabilityledger_chain_integrity] Gauge: immutable chain integrity (`1` valid, `0` invalid). ```rust pub const LEDGER_CHAIN_INTEGRITY: &str; ``` Source line: `98`. ## observability::SEARCH\_QUERIES\_TOTAL [#observabilitysearch_queries_total] Counter: completed search queries by bounded backend and plan. ```rust pub const SEARCH_QUERIES_TOTAL: &str; ``` Source line: `100`. ## observability::SEARCH\_QUERY\_DURATION\_SECONDS [#observabilitysearch_query_duration_seconds] Histogram: storage query latency by bounded backend and plan. ```rust pub const SEARCH_QUERY_DURATION_SECONDS: &str; ``` Source line: `102`. ## observability::SEARCH\_RESULTS [#observabilitysearch_results] Histogram: number of entries returned by each search page. ```rust pub const SEARCH_RESULTS: &str; ``` Source line: `104`. ## observability::SEARCH\_PARTIAL\_RESULTS\_TOTAL [#observabilitysearch_partial_results_total] Counter: search pages with another keyset page available. ```rust pub const SEARCH_PARTIAL_RESULTS_TOTAL: &str; ``` Source line: `106`. ## observability::FEDERATION\_REQUEST\_DURATION\_SECONDS [#observabilityfederation_request_duration_seconds] Histogram: signed federation request latency by bounded operation/outcome. ```rust pub const FEDERATION_REQUEST_DURATION_SECONDS: &str; ``` Source line: `108`. ## observability::FEDERATION\_ERRORS\_TOTAL [#observabilityfederation_errors_total] Counter: federation request failures by bounded operation/class. ```rust pub const FEDERATION_ERRORS_TOTAL: &str; ``` Source line: `110`. ## observability::FEDERATION\_BREAKER\_STATE [#observabilityfederation_breaker_state] Gauge: durable peer count by breaker state. ```rust pub const FEDERATION_BREAKER_STATE: &str; ``` Source line: `112`. ## observability::FEDERATION\_LAG [#observabilityfederation_lag] Gauge: aggregate durable federation sequence lag. ```rust pub const FEDERATION_LAG: &str; ``` Source line: `114`. ## observability::FEDERATION\_QUARANTINES [#observabilityfederation_quarantines] Gauge: durable quarantined payload count. ```rust pub const FEDERATION_QUARANTINES: &str; ``` Source line: `116`. ## observability::FEDERATION\_PARTIAL\_PEERS [#observabilityfederation_partial_peers] Histogram: failed/omitted peers on partial federated discovery pages. ```rust pub const FEDERATION_PARTIAL_PEERS: &str; ``` Source line: `118`. ## observability::RATE\_LIMITED\_TOTAL [#observabilityrate_limited_total] Counter: `mars_rate_limited_total{bucket}`. Canonical `bucket` labels: `read`, `write`, `query`, `auth`, `websocket`. ```rust pub const RATE_LIMITED_TOTAL: &str; ``` Source line: `123`. ## observability::AUTH\_REJECTIONS\_TOTAL [#observabilityauth_rejections_total] Counter: `mars_auth_rejections_total{reason}`. Canonical `reason` labels: * `token_missing` — the request carried neither a bearer token nor a `mars_session` cookie. * `token_invalid` — the supplied token did not resolve to an active session (expired, revoked, or never minted). * `verify_failed` — `POST /v1/auth/siws/verify` failed (bad transcript, nonce mismatch, signature error, expired challenge, etc.). * `audience_mismatch` — the verify request body's `audience` did not match the stored challenge audience. * `publisher_mismatch` — a write request was authorised, but the entry body's `publisher_did` did not equal the session's `hmr_did`. ```rust pub const AUTH_REJECTIONS_TOTAL: &str; ``` Source line: `138`. ## observability::init\_metrics [#observabilityinit_metrics] Install the Prometheus exporter on `addr` and register all metric descriptions. Builds a `PrometheusRecorder` configured to expose `/metrics` over HTTP on `addr`, installs it as the **global** `metrics` recorder for the process, and spawns the exposition listener as a background task on the current Tokio runtime. Must be called from within a running Tokio runtime. # Errors [#errors] Returns an error if the exporter cannot bind to `addr`, if the global recorder has already been installed, or if no Tokio runtime is active. ```rust pub fn init_metrics(addr: SocketAddr) -> anyhow::Result; ``` Source line: `158`. ## observability::ValidationReason [#observabilityvalidationreason] Canonical reason labels for `mars_validation_rejections_total`. Keeping these as `&'static str` keeps the metric label set bounded. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ValidationReason { Schema, Signature, Hash, Bond, Sequence, DidFormat, } ``` Source line: `326`. ## observability::ValidationReason::as\_str [#observabilityvalidationreasonas_str] The string used as the `reason` label value. ```rust pub const fn as_str(self) -> &'static str; ``` Source line: `337`. ## observability::record\_validation\_rejection [#observabilityrecord_validation_rejection] Increment the validation-rejection counter with a bounded reason label. ```rust pub fn record_validation_rejection(reason: ValidationReason); ``` Source line: `350`. ## observability::RateLimitBucket [#observabilityratelimitbucket] Canonical rate-limit buckets for `mars_rate_limited_total`. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RateLimitBucket { Read, Write, Query, Auth, WebSocket, } ``` Source line: `360`. ## observability::RateLimitBucket::as\_str [#observabilityratelimitbucketas_str] The string used as the `bucket` label value. ```rust pub const fn as_str(self) -> &'static str; ``` Source line: `370`. ## observability::record\_rate\_limited [#observabilityrecord_rate_limited] Increment the rate-limited counter for a given bucket. ```rust pub fn record_rate_limited(bucket: RateLimitBucket); ``` Source line: `382`. ## observability::AuthRejectionReason [#observabilityauthrejectionreason] Canonical reason labels for `mars_auth_rejections_total`. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AuthRejectionReason { /// Request carried no bearer header and no `mars_session` cookie. TokenMissing, /// Token was present but did not resolve to an active session. TokenInvalid, /// `POST /v1/auth/siws/verify` rejected the signed response. VerifyFailed, /// `POST /v1/auth/siws/verify` body's audience did not match the /// stored challenge audience. AudienceMismatch, /// Write request authorised, but entry `publisher_did` did not equal /// the session's `hmr_did`. PublisherMismatch, /// Session was valid but did not grant the route's required capability. CapabilityMissing, } ``` Source line: `392`. ## observability::AuthRejectionReason::as\_str [#observabilityauthrejectionreasonas_str] ```rust pub const fn as_str(self) -> &'static str; ``` Source line: `410`. ## observability::record\_auth\_rejection [#observabilityrecord_auth_rejection] Increment `mars_auth_rejections_total{reason=...}`. ```rust pub fn record_auth_rejection(reason: AuthRejectionReason); ``` Source line: `423`. ## observability::record\_anchor\_outcome [#observabilityrecord_anchor_outcome] Increment one bounded anchor worker outcome. ```rust pub fn record_anchor_outcome(outcome: &'static str); ``` Source line: `428`. ## observability::record\_anchor\_outbox\_metrics [#observabilityrecord_anchor_outbox_metrics] Publish the current durable outbox measurements. ```rust pub fn record_anchor_outbox_metrics(stats: &crate::store::AnchorOutboxMetrics); ``` Source line: `433`. ## observability::record\_anchor\_worker\_health [#observabilityrecord_anchor_worker_health] Publish process-local anchor supervisor health. ```rust pub fn record_anchor_worker_health(degraded: bool, consecutive_failures: u32); ``` Source line: `458`. ## observability::AnchorWorkerErrorSource [#observabilityanchorworkererrorsource] Bounded sources for anchor worker infrastructure errors. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AnchorWorkerErrorSource { Claim, ClaimTransition, Metrics, } ``` Source line: `465`. ## observability::record\_anchor\_worker\_error [#observabilityrecord_anchor_worker_error] Increment one bounded anchor worker infrastructure error. ```rust pub fn record_anchor_worker_error(source: AnchorWorkerErrorSource); ``` Source line: `482`. ## observability::record\_sigil\_shadow\_parity [#observabilityrecord_sigil_shadow_parity] Record one bounded deterministic payload/result parity outcome. ```rust pub fn record_sigil_shadow_parity(operation: &'static str, shadow: bool, matched: bool); ``` Source line: `487`. ## observability::record\_chain\_integrity [#observabilityrecord_chain_integrity] Publish one immutable-chain verification result. ```rust pub fn record_chain_integrity(chain: &'static str, valid: bool); ``` Source line: `498`. ## observability::record\_search\_metrics [#observabilityrecord_search_metrics] Record one completed storage-native MARS-QL execution. ```rust pub fn record_search_metrics(page: &crate::search::QueryPage, elapsed_seconds: f64); ``` Source line: `503`. ## observability::record\_federation\_peer\_request [#observabilityrecord_federation_peer_request] Record one signed peer operation with bounded labels. ```rust pub fn record_federation_peer_request( operation: &'static str, outcome: &'static str, elapsed_seconds: f64, ); ``` Source line: `535`. ## observability::record\_federation\_metrics [#observabilityrecord_federation_metrics] Publish durable aggregate peer/breaker/lag/quarantine state. ```rust pub fn record_federation_metrics(stats: &crate::store::FederationMetrics); ``` Source line: `557`. ## observability::record\_federation\_partial\_peers [#observabilityrecord_federation_partial_peers] Record one federated discovery partial-peer count. ```rust pub fn record_federation_partial_peers(failed_peers: u32); ``` Source line: `571`. ## observability::track\_http\_metrics [#observabilitytrack_http_metrics] Per-request middleware that bumps the HTTP request counter and observes the request duration. Cardinality is bounded by using the **matched route template** (e.g. `/v1/entries/{did}`) rather than the concrete request URI. When no route matches (e.g. a 404 with no path), the literal `unknown` is used. ```rust pub async fn track_http_metrics(req: Request, next: Next) -> Response; ``` Source line: `587`. ## Source provenance [#source-provenance] Source: `mars-server/src/observability/mod.rs` · SHA-256 `01e86d74dbcff6e5a79f910b7162d0f3dddf9694028a68287851102547df3ffa`. [Package overview](/libraries/mars-server). # mars-server · production URL: https://docs.mars.glass/libraries/mars-server/production Markdown: https://docs.mars.glass/libraries/mars-server/production.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::production. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `production` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## production::validate\_production\_config [#productionvalidate_production_config] Fail fast if the resolved \[`ServerConfig`] would silently break in production. Enforces production configuration invariants that can be checked before constructing runtime adapters. 1. **Cursor integrity**: an operator-provided, non-fixture HMAC key and a bounded cursor lifetime are required. 2. **Durable state**: a non-empty PostgreSQL URL, at least one auth profile, positive TTLs, and no duplicate profile names are required. 3. **Anchor worker**: required anchoring must be enabled, worker settings must be bounded, and enabled execution requires a registered live \[`crate::anchor::AnchorPort`]. 4. **Federation peer URLs**: every entry in `cfg.federation.peers` must be a non-loopback URL. 5. **SIWS live adapter** (when the `sigil` feature is compiled in): production requires credential-free HTTPS Sigil RPC configuration and protected token/signing-key environment sources. Runtime startup then proves revocation-first GAL, chain, storage, and replay-safe readiness. 6. **Operator trust**: required publisher/peer pin sets must be populated, and every configured Ed25519 key must parse before startup continues. Non-production environments always return `Ok(())`. ```rust pub fn validate_production_config(cfg: &ServerConfig) -> anyhow::Result<()>; ``` Source line: `42`. ## production::validate\_production\_anchor [#productionvalidate_production_anchor] Validate the runtime anchor adapter registration after the application has assembled provider adapters. ```rust pub fn validate_production_anchor( cfg: &ServerConfig, adapter_registered: bool, ) -> anyhow::Result<()>; ``` Source line: `269`. ## production::validate\_production\_auth [#productionvalidate_production_auth] Validate runtime authentication wiring after concrete adapters and stores have been assembled. Production requires restart-safe storage and exactly resolvable enabled profiles. OpenAgent and Arsenal remain extension seams until a concrete adapter is registered; configuring either prematurely fails startup. ```rust pub fn validate_production_auth( cfg: &ServerConfig, registry: &AuthProfileRegistry, durable_storage: bool, ) -> anyhow::Result<()>; ``` Source line: `287`. ## Source provenance [#source-provenance] Source: `mars-server/src/production.rs` · SHA-256 `83a4f86ad41c4965f609874226a8f80899f19f7bf7783644a4cafdd05c6d8e92`. [Package overview](/libraries/mars-server). # mars-server · crate URL: https://docs.mars.glass/libraries/mars-server/root Markdown: https://docs.mars.glass/libraries/mars-server/root.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Registry HTTP server, authorization, durable storage, query planning, federation, and anchor outbox. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `crate` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## anchor [#anchor] ```rust pub mod anchor; ``` Source line: `11`. ## api [#api] ```rust pub mod api; ``` Source line: `12`. ## auth [#auth] ```rust pub mod auth; ``` Source line: `13`. ## bond [#bond] ```rust pub mod bond; ``` Source line: `14`. ## config [#config] ```rust pub mod config; ``` Source line: `15`. ## contracts [#contracts] ```rust #[cfg(feature = "contracts")] pub mod contracts; ``` Source line: `17`. ## discovery [#discovery] ```rust pub mod discovery; ``` Source line: `18`. ## error [#error] ```rust pub mod error; ``` Source line: `19`. ## federation [#federation] ```rust pub mod federation; ``` Source line: `20`. ## middleware [#middleware] ```rust pub mod middleware; ``` Source line: `21`. ## observability [#observability] ```rust pub mod observability; ``` Source line: `22`. ## production [#production] ```rust pub mod production; ``` Source line: `23`. ## search [#search] ```rust pub mod search; ``` Source line: `24`. ## store [#store] ```rust pub mod store; ``` Source line: `25`. ## validation [#validation] ```rust pub mod validation; ``` Source line: `26`. ## pub use config::\{ [#pub-use-config] AnchorServerConfig, AuthConfig, DatabaseConfig, DeploymentEnv, FederationConfig, FederationPeerConfig, MtlsConfig, PinnedPeerKey, PinnedPublisherKey, SearchConfig, ServerConfig, TrustConfig, TrustKeyAlgorithm, }; ```rust pub use config::{ AnchorServerConfig, AuthConfig, DatabaseConfig, DeploymentEnv, FederationConfig, FederationPeerConfig, MtlsConfig, PinnedPeerKey, PinnedPublisherKey, SearchConfig, ServerConfig, TrustConfig, TrustKeyAlgorithm, }; ``` Source line: `28`. ## pub use error::ServerError; [#pub-use-errorservererror] ```rust pub use error::ServerError; ``` Source line: `33`. ## pub use production::\{ [#pub-use-production] validate\_production\_anchor, validate\_production\_auth, validate\_production\_config, }; ```rust pub use production::{ validate_production_anchor, validate_production_auth, validate_production_config, }; ``` Source line: `34`. ## Source provenance [#source-provenance] Source: `mars-server/src/lib.rs` · SHA-256 `ade902e10506d15ba3c50e1d45b9346a3d92eb1b044a91f4514fe823fe441774`. [Package overview](/libraries/mars-server). # mars-server · search URL: https://docs.mars.glass/libraries/mars-server/search Markdown: https://docs.mars.glass/libraries/mars-server/search.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::search. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `search` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## search::DEFAULT\_SEARCH\_CURSOR\_MAX\_AGE\_SECONDS [#searchdefault_search_cursor_max_age_seconds] ```rust pub const DEFAULT_SEARCH_CURSOR_MAX_AGE_SECONDS: u64; ``` Source line: `43`. ## search::MAX\_SEARCH\_CURSOR\_MAX\_AGE\_SECONDS [#searchmax_search_cursor_max_age_seconds] ```rust pub const MAX_SEARCH_CURSOR_MAX_AGE_SECONDS: u64; ``` Source line: `44`. ## search::SearchCursorKey [#searchsearchcursorkey] Validated secret material used to authenticate search cursors. Keys are accepted only as raw bytes or canonical unpadded base64url and are zeroized on drop. Debug formatting deliberately exposes no material. ```rust #[derive(Clone)] pub struct SearchCursorKey(Zeroizing>); ``` Source line: `69`. ## search::SearchCursorKey::from\_bytes [#searchsearchcursorkeyfrom_bytes] Validate raw HMAC key material. ```rust pub fn from_bytes(bytes: Vec) -> Result; ``` Source line: `73`. ## search::SearchCursorKey::from\_base64url [#searchsearchcursorkeyfrom_base64url] Decode canonical unpadded base64url HMAC key material. ```rust pub fn from_base64url(encoded: &str) -> Result; ``` Source line: `85`. ## search::PreviousSearchCursorKey [#searchprevioussearchcursorkey] A previous cursor HMAC key with an absolute, non-renewing acceptance deadline. The absolute timestamp prevents process restarts from extending a rotation window. \[`SearchCursorCodec`] validates the deadline against its maximum cursor age before accepting the key. ```rust #[derive(Clone)] pub struct PreviousSearchCursorKey { } ``` Source line: `145`. ## search::PreviousSearchCursorKey::new [#searchprevioussearchcursorkeynew] Pair previous key material with its operator-configured expiry. ```rust pub const fn new(key: SearchCursorKey, expires_at: DateTime) -> Self; ``` Source line: `152`. ## search::SearchCursorCodec [#searchsearchcursorcodec] HMAC-SHA256 codec for opaque, expiring, query-bound search cursors. New cursors are always signed with `active_key`. During a bounded rotation window, `previous_key` may verify existing cursors but is never used to issue new ones. ```rust #[derive(Clone)] pub struct SearchCursorCodec { } ``` Source line: `177`. ## search::SearchCursorCodec::new [#searchsearchcursorcodecnew] Construct a codec from validated key material and a bounded lifetime. ```rust pub fn new( active_key: SearchCursorKey, previous_key: Option, max_age: chrono::Duration, ) -> Result; ``` Source line: `185`. ## search::SearchCursorCodec::insecure\_test\_fixture [#searchsearchcursorcodecinsecure_test_fixture] Explicit deterministic fixture for development and tests only. Production configuration rejects this key even when its encoded bytes are supplied through an operator configuration source. ```rust pub fn insecure_test_fixture() -> Self; ``` Source line: `239`. ## search::QueryBackend [#searchquerybackend] Bounded execution backend label used by search metrics. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum QueryBackend { Memory, Postgres, } ``` Source line: `401`. ## search::QueryPlan [#searchqueryplan] Bounded query-plan label used by search metrics. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum QueryPlan { Reference, Indexed, } ``` Source line: `417`. ## search::QueryExecution [#searchqueryexecution] Validated storage-level search request. ```rust #[derive(Debug, Clone)] pub struct QueryExecution { } ``` Source line: `433`. ## search::QueryExecution::new [#searchqueryexecutionnew] Validate an AST, apply configured limits, and verify its opaque cursor. ```rust pub fn new( query: &MarsQuery, default_limit: u64, max_limit: u64, anchoring_required: bool, cursor_codec: Arc, ) -> Result; ``` Source line: `443`. ## search::QueryPage [#searchquerypage] One backend search page before conversion to the public wire result. ```rust #[derive(Debug, Clone)] pub struct QueryPage { pub entries: Vec, pub total_count: u64, pub cursor: Option, pub has_more: bool, pub backend: QueryBackend, pub plan: QueryPlan } ``` Source line: `507`. ## search::ValidatedMarsQuery [#searchvalidatedmarsquery] A query that has passed all server-side AST and cursor-safety validation. ```rust #[derive(Debug, Clone)] pub struct ValidatedMarsQuery { } ``` Source line: `518`. ## search::ValidatedCondition [#searchvalidatedcondition] One semantically validated condition. ```rust #[derive(Debug, Clone)] pub struct ValidatedCondition { } ``` Source line: `623`. ## search::ValidatedOrder [#searchvalidatedorder] One semantically validated order expression. ```rust #[derive(Debug, Clone)] pub struct ValidatedOrder { } ``` Source line: `643`. ## search::compute\_ranking\_score\_at [#searchcompute_ranking_score_at] Compute the frozen five-component default ranking at one stable instant. ```rust pub fn compute_ranking_score_at(entry: &MarsEntry, query: &MarsQuery, as_of: DateTime) -> f64; ``` Source line: `1464`. ## search::SemanticSearchRequest [#searchsemanticsearchrequest] Request accepted by a future semantic-search adapter. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct SemanticSearchRequest { pub query: String, pub entry_type: Option, pub limit: u32 } ``` Source line: `1568`. ## search::SemanticSearchHit [#searchsemanticsearchhit] One semantic adapter result, resolved through MARS by DID. ```rust #[derive(Debug, Clone, PartialEq)] pub struct SemanticSearchHit { pub entry_did: String, pub score: f64 } ``` Source line: `1576`. ## search::SemanticSearchError [#searchsemanticsearcherror] Explicit semantic-search availability failures. ```rust #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] pub enum SemanticSearchError { #[error("semantic search is disabled because no SemanticSearchPort is registered")] Disabled, #[error("semantic search adapter failed: {0}")] Adapter(String), } ``` Source line: `1583`. ## search::SemanticSearchPort [#searchsemanticsearchport] MARS-owned semantic search seam. No cognitive engine dependency is implied. ```rust #[async_trait] pub trait SemanticSearchPort: Send + Sync { async fn search( &self, request: &SemanticSearchRequest, ) -> Result, SemanticSearchError>; } ``` Source line: `1592`. ## search::DisabledSemanticSearchPort [#searchdisabledsemanticsearchport] Fail-closed implementation used when semantic search is not configured. ```rust pub struct DisabledSemanticSearchPort; ``` Source line: `1600`. ## Source provenance [#source-provenance] Source: `mars-server/src/search.rs` · SHA-256 `45a1199799596211298fdacfcb17a2cf7e3472f021fbd7b80f69535a2cf20b7d`. [Package overview](/libraries/mars-server). # mars-server · store URL: https://docs.mars.glass/libraries/mars-server/store Markdown: https://docs.mars.glass/libraries/mars-server/store.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::store. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `store` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## store::memory [#storememory] Storage backend trait and implementations. Defines the \[`EntryStore`] trait that all storage backends must implement, providing CRUD operations for entries, bonds, events, and federation peers. ```rust pub mod memory; ``` Source line: `6`. ## store::postgres [#storepostgres] ```rust #[cfg(feature = "postgres")] pub mod postgres; ``` Source line: `10`. ## store::sharded\_memory [#storesharded_memory] ```rust #[cfg(feature = "sharding")] pub mod sharded_memory; ``` Source line: `14`. ## pub use mars\_protocol::anchoring::AnchorOperation; [#pub-use-mars_protocolanchoringanchoroperation] ```rust pub use mars_protocol::anchoring::AnchorOperation; ``` Source line: `22`. ## store::EntryVersionPage [#storeentryversionpage] One bounded page from an entry's immutable version history. ```rust #[derive(Debug, Clone, PartialEq)] pub struct EntryVersionPage { /// Canonically ordered snapshots in this page. pub versions: Vec, /// Number of versions stored for the DID before pagination. pub total_count: u64, /// Last returned registry sequence when another keyset page exists. pub next_cursor: Option, /// Whether versions exist below `next_cursor`. pub has_more: bool } ``` Source line: `49`. ## store::PageRequest [#storepagerequest] Validated offset/limit primitives for every potentially multi-row read. Storage implementations must apply these bounds in the database query (or while holding the in-memory state lock), never after an unbounded fetch. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PageRequest { } ``` Source line: `65`. ## store::PageRequest::MAX\_LIMIT [#storepagerequestmax_limit] Hard storage-level allocation bound, independent of HTTP configuration. ```rust pub const MAX_LIMIT: u32; ``` Source line: `72`. ## store::PageRequest::new [#storepagerequestnew] Construct a validated page. ```rust pub fn new(offset: u64, limit: u32) -> Result; ``` Source line: `75`. ## store::PageRequest::first [#storepagerequestfirst] First page with the requested bound. ```rust pub fn first(limit: u32) -> Result; ``` Source line: `86`. ## store::PageRequest::offset [#storepagerequestoffset] Zero-based row offset. ```rust #[must_use] pub fn offset(self) -> u64; ``` Source line: `92`. ## store::PageRequest::limit [#storepagerequestlimit] Maximum rows returned by this read. ```rust #[must_use] pub fn limit(self) -> u32; ``` Source line: `98`. ## store::PageRequest::advance [#storepagerequestadvance] Advance by the number of rows actually consumed. ```rust pub fn advance(self, consumed: usize) -> Result; ``` Source line: `103`. ## store::AuditAction [#storeauditaction] Private, append-only audit action recorded with a committed mutation. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AuditAction { /// A registry entry was created. Create, /// A registry entry was updated. Update, /// A registry entry was revoked. Revoke, /// A transfer offer was created. TransferOffer, /// A transfer offer was accepted. TransferAccept, /// A transfer offer was declined. TransferDecline, /// A transfer offer expired. TransferExpire, /// A canonical attestation was accepted. Attest, /// A malicious-behaviour report was accepted. Report, /// A registry-local bond was provisioned. BondProvision, /// A federation sync request was served. FederationSync, /// A federation peer changed its metadata. PeerUpdate, /// Another event-only write was accepted. Event, /// An administrator requeued an anchor intent. AnchorRetry, /// An administrator permanently abandoned an anchor intent. AnchorAbandon, } ``` Source line: `113`. ## store::AuditOutcome [#storeauditoutcome] Outcome of an authenticated mutation attempt. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AuditOutcome { Accepted, Rejected, } ``` Source line: `172`. ## store::AuditContext [#storeauditcontext] Shared provenance for one private mutation audit row. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuditContext { pub actor_did: String, pub route: String, pub target: String, pub request_hash: String, pub response_status: u16, pub occurred_at: DateTime } ``` Source line: `180`. ## store::AuditContext::new [#storeauditcontextnew] ```rust #[must_use] pub fn new( actor_did: impl Into, route: impl Into, target: impl Into, request_hash: impl Into, response_status: u16, occurred_at: DateTime, ) -> Self; ``` Source line: `191`. ## store::AuditRecord [#storeauditrecord] MARS-owned private audit record persisted in the mutation transaction. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuditRecord { /// Globally unique audit record identifier. pub audit_id: String, /// Actor identity supplied by the authenticated boundary or caller. pub actor_did: String, /// Stable route template, never a client-supplied actor field. pub route: String, /// Operation recorded by this audit row. pub action: AuditAction, /// Accepted or rejected outcome. pub outcome: AuditOutcome, /// Entry, offer, bond, or route target affected by the operation. pub entry_did: String, /// Canonical semantic request hash. pub request_hash: String, /// HTTP status returned to the caller. pub response_status: u16, /// Rejection reason, absent for accepted mutations. pub reason: Option, /// Registry sequence assigned by the transaction. pub sequence: u64, /// Timestamp captured before the transaction starts. pub occurred_at: DateTime, /// MARS-owned contextual metadata. Never exposed by public entry APIs. pub detail: Option, /// Hash of the preceding private audit row. pub previous_hash: Option, /// SHA-256 hash of this row's canonical content and predecessor. pub record_hash: String } ``` Source line: `213`. ## store::AuditRecord::new [#storeauditrecordnew] Build a private audit record for an event. ```rust #[must_use] pub fn new(actor_did: impl Into, action: AuditAction, event: &MarsEvent) -> Self; ``` Source line: `247`. ## store::AuditRecord::accepted [#storeauditrecordaccepted] Build an accepted mutation row. ```rust #[must_use] pub fn accepted( context: AuditContext, action: AuditAction, detail: Option, ) -> Self; ``` Source line: `268`. ## store::AuditRecord::rejected [#storeauditrecordrejected] Build a rejected mutation row. The store seals it into the private hash chain before committing it. ```rust #[must_use] pub fn rejected(context: AuditContext, action: AuditAction, reason: impl Into) -> Self; ``` Source line: `294`. ## store::AuditChainVerification [#storeauditchainverification] Result of a complete private audit-chain verification pass. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct AuditChainVerification { pub record_count: u64, pub head_hash: Option } ``` Source line: `358`. ## store::EventChainVerification [#storeeventchainverification] Result of a complete public protocol-event chain verification pass. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct EventChainVerification { pub record_count: u64, pub head_hash: Option } ``` Source line: `365`. ## store::LedgerChainVerification [#storeledgerchainverification] Combined immutable-ledger verification result. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct LedgerChainVerification { pub audit: AuditChainVerification, pub events: EventChainVerification } ``` Source line: `372`. ## store::AnchorIntent [#storeanchorintent] Optional anchor work requested by a mutation. Stores persist this as an outbox row. Network adapters consume it only after the database transaction commits. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AnchorIntent { /// Stable outbox intent identifier. pub intent_id: String, /// Mutation operation that produced the intent. pub operation: AnchorOperation, /// MARS-owned payload consumed by a later adapter. pub payload: serde_json::Value, /// Intent creation timestamp. pub created_at: DateTime } ``` Source line: `395`. ## store::PersistedAnchorIntent [#storepersistedanchorintent] Persisted view of an anchor outbox row. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PersistedAnchorIntent { /// Stable outbox intent identifier. pub intent_id: String, /// Entry snapshot to anchor. pub entry_did: String, /// Registry sequence of the immutable snapshot. pub sequence: u64, /// Mutation operation that produced the intent. pub operation: AnchorOperation, /// MARS-owned adapter payload. pub payload: serde_json::Value, /// Durable worker state. pub state: AnchorOutboxState, /// Number of submission attempts started. pub attempts: u32, /// Earliest time this row may be claimed or polled. pub available_at: DateTime, /// Worker currently holding the lease. pub claimed_by: Option, /// Expiration of the current worker lease. pub lease_expires_at: Option>, /// Opaque token required to complete the current claim. pub lease_token: Option, /// Latest provider-neutral transaction identifier. pub transaction_id: Option, /// Latest bounded failure diagnostic. pub last_error: Option, /// Time the latest transaction was first accepted. pub submitted_at: Option>, /// Time the provider reported final confirmation. pub confirmed_at: Option>, /// Time processing was permanently abandoned. pub abandoned_at: Option>, /// Intent creation timestamp. pub created_at: DateTime, /// Last durable state transition. pub updated_at: DateTime, /// Immutable adapter observations, in observation order. pub receipts: Vec } ``` Source line: `409`. ## store::AnchorIntentCursor [#storeanchorintentcursor] Stable position in an entry's combined hot and archived anchor history. Ordering is lexicographic and ascending over `(sequence, created_at, intent_id)`. The encoded representation is canonical, URL-safe, and opaque to API clients. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct AnchorIntentCursor { } ``` Source line: `456`. ## store::AnchorIntentCursor::MAX\_ENCODED\_LEN [#storeanchorintentcursormax_encoded_len] Maximum accepted encoded cursor size. ```rust pub const MAX_ENCODED_LEN: usize; ``` Source line: `464`. ## store::AnchorIntentCursor::from\_intent [#storeanchorintentcursorfrom_intent] Construct the cursor representing a returned intent. ```rust #[must_use] pub fn from_intent(intent: &PersistedAnchorIntent) -> Self; ``` Source line: `468`. ## store::AnchorIntentCursor::encode [#storeanchorintentcursorencode] Encode this cursor as canonical unpadded base64url JSON. ```rust pub fn encode(&self) -> Result; ``` Source line: `477`. ## store::AnchorIntentCursor::decode [#storeanchorintentcursordecode] Decode and validate a canonical cursor received from the public API. ```rust pub fn decode(encoded: &str) -> Result; ``` Source line: `492`. ## store::AnchorIntentPage [#storeanchorintentpage] One bounded keyset page from combined hot and archived anchor history. ```rust #[derive(Debug, Clone, PartialEq)] pub struct AnchorIntentPage { /// Canonically ordered intents in this page. pub intents: Vec, /// Cursor for the last returned intent when another page exists. pub next_cursor: Option, /// Whether another intent exists after `next_cursor`. pub has_more: bool } ``` Source line: `540`. ## store::AnchorClaim [#storeanchorclaim] One exclusively leased outbox row. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AnchorClaim { pub intent: PersistedAnchorIntent, pub lease_token: String } ``` Source line: `552`. ## store::AnchorOutboxMetrics [#storeanchoroutboxmetrics] Current outbox measurements used by health checks and Prometheus gauges. ```rust #[derive(Debug, Clone, PartialEq)] pub struct AnchorOutboxMetrics { pub backlog: u64, pub oldest_age_seconds: f64, pub total_attempts: u64, pub maximum_attempts: u32, pub pending: u64, pub claimed: u64, pub submitted: u64, pub failed: u64, pub confirmed: u64, pub abandoned: u64, pub retained_terminal: u64, pub archived_confirmed: u64, pub archived_abandoned: u64 } ``` Source line: `559`. ## store::AnchorOutboxArchiveResult [#storeanchoroutboxarchiveresult] Outcome of one bounded terminal-outbox archival transaction. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct AnchorOutboxArchiveResult { pub archived: u64, pub confirmed: u64, pub abandoned: u64 } ``` Source line: `597`. ## store::AnchorAdminCommand [#storeanchoradmincommand] Idempotent administrative state transition for one anchor intent. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AnchorAdminCommand { pub intent_id: String, pub occurred_at: DateTime, pub audit: AuditRecord, pub idempotency: IdempotencyRequest } ``` Source line: `606`. ## store::StoredHttpResponse [#storestoredhttpresponse] Exact HTTP response stored for an idempotent mutation. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct StoredHttpResponse { pub status: u16, pub content_type: Option, pub body: Vec } ``` Source line: `616`. ## store::StoredHttpResponse::json [#storestoredhttpresponsejson] Construct a JSON response using the same compact serializer as Axum. ```rust pub fn json(status: u16, value: &T) -> Result; ``` Source line: `624`. ## store::StoredHttpResponse::empty [#storestoredhttpresponseempty] Construct a body-less response. ```rust #[must_use] pub fn empty(status: u16) -> Self; ``` Source line: `636`. ## store::StoredHttpResponse::into\_axum\_response [#storestoredhttpresponseinto_axum_response] Convert the persisted response into an Axum response without changing its status or body bytes. ```rust pub fn into_axum_response(self) -> Result; ``` Source line: `646`. ## store::IdempotencyRequest [#storeidempotencyrequest] Optional caller-provided idempotency reservation. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct IdempotencyRequest { /// Stable authenticated route template. pub route: String, /// Stable idempotency key. pub key: String, /// Canonical hash of the semantic request. pub request_hash: String, /// Exact response template. Entry commits replace the body after assigning /// the authoritative registry sequence. pub response: StoredHttpResponse, /// Whether the committed entry is the response body. pub response_from_entry: bool, /// Server-controlled expiry time. pub expires_at: DateTime } ``` Source line: `671`. ## store::IdempotencyRequest::for\_test\_entry\_projection [#storeidempotencyrequestfor_test_entry_projection] Construct a test reservation using internal route/status/expiry defaults and an entry-projection response. Production HTTP paths must use \[`Self::for_entry_projection`] or \[`Self::for_stored_response`] so route, response, and expiry semantics remain explicit. ```rust #[must_use] pub fn for_test_entry_projection( key: impl Into, request_hash: impl Into, ) -> Self; ``` Source line: `695`. ## store::IdempotencyRequest::for\_entry\_projection [#storeidempotencyrequestfor_entry_projection] Construct a reservation whose response body is reconstructed from the authoritative entry projection after sequence assignment. This must only be used by commands that commit a \[`MarsEntry`] and return that exact entry as the successful response body. ```rust #[must_use] pub fn for_entry_projection( route: impl Into, key: impl Into, request_hash: impl Into, status: u16, expires_at: DateTime, ) -> Self; ``` Source line: `715`. ## store::IdempotencyRequest::for\_stored\_response [#storeidempotencyrequestfor_stored_response] Construct a reservation retaining the exact serialized HTTP response. Use this for transfer offers, attestations, admin controls, reports, and every endpoint whose body is not exactly a committed entry. ```rust #[must_use] pub fn for_stored_response( route: impl Into, key: impl Into, request_hash: impl Into, response: StoredHttpResponse, expires_at: DateTime, ) -> Self; ``` Source line: `737`. ## store::MutationMetadata [#storemutationmetadata] Metadata persisted atomically beside every accepted mutation. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MutationMetadata { /// Public protocol event. pub event: MarsEvent, /// Private audit record. pub audit: AuditRecord, /// Optional idempotency reservation. pub idempotency: Option, /// Optional post-commit anchor work. pub anchor_intent: Option, /// Revalidate the referenced registry-local bond inside the mutation /// transaction to close validation/commit races. #[serde(default)] pub bond_recheck: bool } ``` Source line: `772`. ## store::CreateEntryCommand [#storecreateentrycommand] Atomic create unit of work. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CreateEntryCommand { /// Unsequenced entry supplied by the caller. pub entry: MarsEntry, /// Mutation metadata persisted in the same transaction. pub metadata: MutationMetadata } ``` Source line: `803`. ## store::CreateEntryCommand::new [#storecreateentrycommandnew] Construct an atomic create command. ```rust #[must_use] pub fn new(entry: MarsEntry, event: MarsEvent, actor_did: impl Into) -> Self; ``` Source line: `813`. ## store::CreateEntryCommand::with\_idempotency [#storecreateentrycommandwith_idempotency] Attach an idempotency reservation. ```rust #[must_use] pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self; ``` Source line: `822`. ## store::CreateEntryCommand::with\_anchor\_intent [#storecreateentrycommandwith_anchor_intent] Attach post-commit anchor work. ```rust #[must_use] pub fn with_anchor_intent(mut self, intent: AnchorIntent) -> Self; ``` Source line: `830`. ## store::CreateEntryCommand::with\_bond\_recheck [#storecreateentrycommandwith_bond_recheck] Require a same-transaction bond status/binding recheck. ```rust #[must_use] pub fn with_bond_recheck(mut self) -> Self; ``` Source line: `837`. ## store::UpdateEntryCommand [#storeupdateentrycommand] Atomic update unit of work with compare-and-set concurrency control. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct UpdateEntryCommand { /// Replacement latest entry. The store assigns its sequence. pub entry: MarsEntry, /// Latest sequence observed by the caller. pub expected_sequence: u64, /// Mutation metadata persisted in the same transaction. pub metadata: MutationMetadata } ``` Source line: `846`. ## store::UpdateEntryCommand::new [#storeupdateentrycommandnew] Construct an atomic compare-and-set update command. ```rust #[must_use] pub fn new( entry: MarsEntry, expected_sequence: u64, event: MarsEvent, actor_did: impl Into, ) -> Self; ``` Source line: `858`. ## store::UpdateEntryCommand::with\_audit\_action [#storeupdateentrycommandwith_audit_action] Override the private audit action for a specialized update. ```rust #[must_use] pub fn with_audit_action(mut self, action: AuditAction) -> Self; ``` Source line: `873`. ## store::UpdateEntryCommand::with\_idempotency [#storeupdateentrycommandwith_idempotency] Attach an idempotency reservation. ```rust #[must_use] pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self; ``` Source line: `880`. ## store::UpdateEntryCommand::with\_anchor\_intent [#storeupdateentrycommandwith_anchor_intent] Attach post-commit anchor work. ```rust #[must_use] pub fn with_anchor_intent(mut self, intent: AnchorIntent) -> Self; ``` Source line: `888`. ## store::UpdateEntryCommand::with\_bond\_recheck [#storeupdateentrycommandwith_bond_recheck] Require a same-transaction bond status/binding recheck. ```rust #[must_use] pub fn with_bond_recheck(mut self) -> Self; ``` Source line: `895`. ## store::RevokeEntryCommand [#storerevokeentrycommand] Atomic revoke unit of work with compare-and-set concurrency control. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RevokeEntryCommand { /// Entry DID to revoke. pub entry_did: String, /// Latest sequence observed by the caller. pub expected_sequence: u64, /// Mutation metadata persisted in the same transaction. pub metadata: MutationMetadata } ``` Source line: `904`. ## store::RevokeEntryCommand::new [#storerevokeentrycommandnew] Construct an atomic revoke command. ```rust #[must_use] pub fn new( entry_did: impl Into, expected_sequence: u64, event: MarsEvent, actor_did: impl Into, ) -> Self; ``` Source line: `916`. ## store::RevokeEntryCommand::with\_idempotency [#storerevokeentrycommandwith_idempotency] Attach an idempotency reservation. ```rust #[must_use] pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self; ``` Source line: `931`. ## store::RevokeEntryCommand::with\_anchor\_intent [#storerevokeentrycommandwith_anchor_intent] Attach post-commit anchor work. ```rust #[must_use] pub fn with_anchor_intent(mut self, intent: AnchorIntent) -> Self; ``` Source line: `939`. ## store::EventCommitCommand [#storeeventcommitcommand] Event-only durable write used by report and protocol-event paths. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EventCommitCommand { /// Public event to append. pub event: MarsEvent, /// Private audit record persisted with the event. pub audit: AuditRecord, /// Optional idempotency reservation and exact response. pub idempotency: Option } ``` Source line: `948`. ## store::EventCommitCommand::new [#storeeventcommitcommandnew] Construct an event and audit atomic unit. ```rust #[must_use] pub fn new(event: MarsEvent, actor_did: impl Into) -> Self; ``` Source line: `960`. ## store::EventCommitCommand::with\_audit\_action [#storeeventcommitcommandwith_audit_action] Select the domain-specific private audit action. ```rust #[must_use] pub fn with_audit_action(mut self, action: AuditAction) -> Self; ``` Source line: `971`. ## store::EventCommitCommand::with\_idempotency [#storeeventcommitcommandwith_idempotency] Persist an exact idempotent response with the event. ```rust #[must_use] pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self; ``` Source line: `978`. ## store::RejectedMutationCommand [#storerejectedmutationcommand] Atomic private audit and idempotency write for a rejected mutation. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RejectedMutationCommand { pub audit: AuditRecord, pub idempotency: Option } ``` Source line: `988`. ## store::TransferOfferCommand [#storetransferoffercommand] Atomic creation of a signed transfer offer. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransferOfferCommand { pub offer: TransferOffer, pub expected_entry_sequence: u64, pub audit: AuditRecord, pub idempotency: IdempotencyRequest } ``` Source line: `996`. ## store::TransferAcceptCommand [#storetransferacceptcommand] Atomic recipient acceptance and entry replacement. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransferAcceptCommand { pub offer_id: String, pub recipient_did: String, pub entry: MarsEntry, pub expected_entry_sequence: u64, pub accepted_at: DateTime, pub event: MarsEvent, pub audit: AuditRecord, pub idempotency: IdempotencyRequest, pub anchor_intent: Option } ``` Source line: `1006`. ## store::TransferDeclineCommand [#storetransferdeclinecommand] Atomic recipient decline. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TransferDeclineCommand { pub offer_id: String, pub recipient_did: String, pub declined_at: DateTime, pub reason: Option, pub audit: AuditRecord, pub idempotency: IdempotencyRequest } ``` Source line: `1021`. ## store::AttestationCommitCommand [#storeattestationcommitcommand] Atomic canonical-attestation, event, audit, and idempotency commit. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AttestationCommitCommand { pub attestation: VerifiableAttestationRecord, pub event: MarsEvent, pub audit: AuditRecord, pub idempotency: IdempotencyRequest, pub anchor_intent: Option } ``` Source line: `1033`. ## store::BondCommitCommand [#storebondcommitcommand] Atomic registry-local bond provisioning command. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BondCommitCommand { pub bond: Bond, pub audit: AuditRecord, pub idempotency: IdempotencyRequest } ``` Source line: `1044`. ## store::PeerCommitCommand [#storepeercommitcommand] Atomic peer metadata update command. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PeerCommitCommand { pub peer: FederationPeer, pub audit: AuditRecord, pub idempotency: IdempotencyRequest } ``` Source line: `1053`. ## store::FederationPeerState [#storefederationpeerstate] Durable synchronization, health, lease, and breaker state for one peer. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FederationPeerState { pub peer: FederationPeer, pub cursor: u64, pub remote_head: u64, pub breaker_state: mars_protocol::federation::FederationBreakerState, pub consecutive_failures: u32, pub latency_ms: Option, pub lag: u64, pub quarantines: u64, pub last_success_at: Option>, pub next_attempt_at: DateTime, pub lease_owner: Option, pub lease_token: Option, pub lease_expires_at: Option>, pub updated_at: DateTime } ``` Source line: `1062`. ## store::FederationPeerState::new [#storefederationpeerstatenew] Construct the initial restart-safe state for a configured peer. ```rust pub fn new(peer: FederationPeer, now: DateTime) -> Result; ``` Source line: `1081`. ## store::FederationPeerState::status [#storefederationpeerstatestatus] Secret-free projection returned by protected status routes. ```rust #[must_use] pub fn status(&self) -> mars_protocol::federation::FederationPeerStatus; ``` Source line: `1114`. ## store::FederationPeerClaim [#storefederationpeerclaim] Exclusively leased peer synchronization work. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FederationPeerClaim { pub state: FederationPeerState, pub lease_token: String } ``` Source line: `1132`. ## store::FederationQuarantineReason [#storefederationquarantinereason] Bounded quarantine reason persisted without exposing parser internals. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum FederationQuarantineReason { Envelope, PublisherSignature, Validation, Conflict, VisibilityPolicy, } ``` Source line: `1140`. ## store::FederationQuarantineRecord [#storefederationquarantinerecord] Durable evidence for one rejected remote payload. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FederationQuarantineRecord { pub quarantine_id: String, pub peer_did: String, pub request_digest: String, pub entry_did: Option, pub reason: FederationQuarantineReason, pub payload_digest: String, pub payload: serde_json::Value, pub observed_at: DateTime } ``` Source line: `1164`. ## store::FederationImportCommand [#storefederationimportcommand] Validated, replay-safe remote entry import. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FederationImportCommand { pub registry_did: String, pub peer_did: String, pub delivery_digest: String, pub entry: MarsEntry, pub source_sequence: u64, pub content_digest: String, pub expected_local_sequence: Option, pub local_signature_verified: bool, pub observed_at: DateTime } ``` Source line: `1178`. ## store::FederationImportOutcome [#storefederationimportoutcome] Result of one idempotent federation delivery. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum FederationImportOutcome { Imported, RetainedLocal, DuplicateDelivery, } ``` Source line: `1193`. ## store::FederationMetrics [#storefederationmetrics] Bounded federation health metrics from durable state. ```rust #[derive(Debug, Clone, Default, PartialEq)] pub struct FederationMetrics { pub peers: u64, pub closed: u64, pub open: u64, pub half_open: u64, pub quarantined: u64, pub lag: u64, pub quarantine_records: u64 } ``` Source line: `1201`. ## store::AuditedResponseCommand [#storeauditedresponsecommand] Atomic audit plus exact response for authenticated mutations with no other local state change, such as pull-based federation sync. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuditedResponseCommand { pub audit: AuditRecord, pub idempotency: IdempotencyRequest } ``` Source line: `1215`. ## store::RejectedMutationCommand::new [#storerejectedmutationcommandnew] ```rust #[must_use] pub fn new(audit: AuditRecord) -> Self; ``` Source line: `1222`. ## store::RejectedMutationCommand::with\_idempotency [#storerejectedmutationcommandwith_idempotency] ```rust #[must_use] pub fn with_idempotency(mut self, request: IdempotencyRequest) -> Self; ``` Source line: `1230`. ## store::MutationCommit [#storemutationcommit] Result returned by create, update, and revoke commits. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MutationCommit { /// Latest entry after the transaction committed. pub entry: MarsEntry, /// Event persisted by the transaction. pub event: MarsEvent, /// Whether this response came from a prior idempotent commit. pub idempotent_replay: bool, /// Exact response stored under the idempotency key. pub response: StoredHttpResponse } ``` Source line: `1240`. ## store::EntryStore [#storeentrystore] Storage backend trait for the MARS registry. Implementations must be thread-safe (`Send + Sync`). The async, object-safe interface permits PostgreSQL and in-memory stores to share one production path without runtime blocking bridges. ```rust #[async_trait] pub trait EntryStore: Send + Sync { /// Return an unexpired exact replay, reject hash reuse, or report no match. async fn lookup_idempotency( &self, actor_did: &str, route: &str, key: &str, request_hash: &str, now: DateTime, ) -> Result, ServerError>; /// Atomically append a rejected audit row and, when present, its exact /// idempotency response. async fn commit_rejection(&self, command: RejectedMutationCommand) -> Result<(), ServerError>; /// Remove expired idempotency responses. async fn cleanup_idempotency(&self, before: DateTime) -> Result; /// Verify every private audit row and the persisted chain head. async fn verify_audit_chain(&self) -> Result; /// Verify the public protocol-event chain and its persisted head. async fn verify_event_chain(&self) -> Result ; /// Verify both immutable hash chains. async fn verify_ledger_chains(&self) -> Result ; /// Atomically create one live transfer offer for an entry. async fn commit_transfer_offer( &self, command: TransferOfferCommand, ) -> Result; /// Fetch a transfer offer, projecting elapsed live offers as expired. async fn get_transfer_offer( &self, offer_id: &str, now: DateTime, ) -> Result, ServerError>; /// Atomically accept an offer and replace the entry with the fully /// recipient-signed version. async fn commit_transfer_accept( &self, command: TransferAcceptCommand, ) -> Result; /// Atomically decline a live offer. async fn commit_transfer_decline( &self, command: TransferDeclineCommand, ) -> Result; /// Atomically store a canonical attestation and its event/audit metadata. async fn commit_attestation( &self, command: AttestationCommitCommand, ) -> Result; /// List separately stored attestations, excluding expired/revoked records /// unless explicitly requested. async fn list_attestations( &self, entry_did: &str, now: DateTime, include_expired: bool, include_revoked: bool, page: PageRequest, ) -> Result, ServerError>; /// Whether a credential has a locally available revocation fact. async fn is_attestation_revoked(&self, attestation_id: &str) -> Result; /// Atomically provision bond metadata with audit/idempotency records. async fn commit_bond( &self, command: BondCommitCommand, ) -> Result; /// Atomically update self-bound peer metadata. async fn commit_peer( &self, command: PeerCommitCommand, ) -> Result; /// Atomically persist an accepted audit and exact idempotency response. async fn commit_audited_response( &self, command: AuditedResponseCommand, ) -> Result; /// Atomically commit a new entry, immutable snapshot, event, audit record, /// idempotency reservation, and optional anchor outbox row. async fn commit_create( &self, command: CreateEntryCommand, ) -> Result; /// Atomically compare-and-set an updated entry and all mutation records. async fn commit_update( &self, command: UpdateEntryCommand, ) -> Result; /// Atomically compare-and-set a revocation and all mutation records. async fn commit_revoke( &self, command: RevokeEntryCommand, ) -> Result; /// Atomically append an event and its private audit record. async fn commit_event(&self, command: EventCommitCommand) -> Result; /// Compatibility create helper. This delegates to the production commit /// path so fixtures cannot bypass event and audit persistence. async fn put_entry(&self, entry: MarsEntry) -> Result<(), ServerError> ; /// Get an entry by DID. Returns the latest version. async fn get_entry(&self, did: &str) -> Result, ServerError>; /// Get a specific version of an entry by DID and semver string. async fn get_entry_version( &self, did: &str, version: &str, ) -> Result, ServerError>; /// List a bounded page of stored versions in stable newest-first order. /// /// Implementations order by the registry-assigned sequence descending, /// then by semantic version descending as a deterministic tie-breaker. async fn list_entry_versions( &self, did: &str, before_sequence: Option, limit: u64, ) -> Result; /// Compatibility update helper using a store read followed by the same CAS /// production commit path used by HTTP mutations. async fn update_entry(&self, entry: MarsEntry) -> Result<(), ServerError> ; /// Compatibility revoke helper delegated to the production commit path. async fn delete_entry(&self, did: &str) -> Result<(), ServerError> ; /// List all entries, optionally filtered by entry type. async fn list_entries( &self, entry_type: Option<&EntryType>, page: PageRequest, ) -> Result, ServerError>; /// Execute one validated MARS-QL query through the backend's native query /// engine. Durable implementations must filter, order, and keyset-page in /// the database rather than materializing an unbounded candidate set. async fn execute_query( &self, query: &crate::search::QueryExecution, ) -> Result; /// Get the current global sequence number. async fn current_sequence(&self) -> Result; // --- Bond operations --- /// Provision a bond exactly once. /// /// Existing bond IDs are immutable. Status or amount changes require a /// separately authorized transition API; this primitive never upserts. async fn put_bond(&self, bond: Bond) -> Result<(), ServerError>; /// Get a bond by ID. async fn get_bond(&self, bond_id: &str) -> Result, ServerError>; // --- Event log --- /// Append an event to the log. async fn append_event(&self, event: MarsEvent) -> Result<(), ServerError> ; /// Read a bounded event page after an optional event cursor. /// /// `None` begins at the oldest event. A nonempty cursor must exist. /// `page.offset()` must be zero; callers advance only with event IDs. async fn event_tail( &self, after_event_id: Option<&str>, page: PageRequest, ) -> Result, ServerError>; /// List private audit records for an entry in sequence order. async fn audit_records( &self, entry_did: &str, page: PageRequest, ) -> Result, ServerError>; /// List anchor records across hot and archive storage in stable ascending /// `(sequence, created_at, intent_id)` order. /// /// `None` starts at the oldest record. A cursor must exactly identify a /// record for `entry_did`; implementations reject unknown or cross-entry /// cursors and return at most `limit` records. async fn anchor_intents( &self, entry_did: &str, after: Option<&AnchorIntentCursor>, limit: u32, ) -> Result; /// Read one anchor intent by its stable identifier. async fn anchor_intent( &self, intent_id: &str, ) -> Result, ServerError>; /// Exclusively lease available work. PostgreSQL implementations must use /// `FOR UPDATE SKIP LOCKED` so replicas never execute the same lease. async fn claim_anchor_intents( &self, worker_id: &str, now: DateTime, lease_expires_at: DateTime, limit: u32, max_attempts: u32, ) -> Result, ServerError>; /// Idempotently persist one adapter observation and release the claim. async fn persist_anchor_receipt( &self, claim: &AnchorClaim, receipt: AnchorReceiptRecord, next_available_at: DateTime, persisted_at: DateTime, ) -> Result; /// Persist one failed attempt, scheduling a retry or terminal abandonment. async fn fail_anchor_claim( &self, claim: &AnchorClaim, error: &str, retry_at: DateTime, failed_at: DateTime, abandon: bool, ) -> Result; /// Requeue a failed or abandoned intent with exact-response idempotency. async fn retry_anchor( &self, command: AnchorAdminCommand, ) -> Result; /// Permanently abandon a non-submitted intent with exact-response /// idempotency. async fn abandon_anchor( &self, command: AnchorAdminCommand, ) -> Result; /// Snapshot outbox backlog and attempt measurements. async fn anchor_outbox_metrics( &self, now: DateTime, ) -> Result; /// Move a bounded batch of retained terminal intents into durable archive /// storage while preserving their receipt history. async fn archive_terminal_anchor_intents( &self, before: DateTime, limit: u32, ) -> Result; // --- Federation peers --- /// Atomically consume one signed-envelope nonce. /// /// Returns `true` only for the first unexpired `(peer_did, nonce)` pair. /// Durable implementations must enforce uniqueness in the database so /// concurrent replicas cannot both accept the same envelope. async fn consume_federation_nonce( &self, peer_did: &str, nonce: &str, request_digest: &str, expires_at: DateTime, now: DateTime, ) -> Result; /// Insert or update durable runtime state for a configured peer. async fn put_federation_peer_state( &self, state: FederationPeerState, ) -> Result<(), ServerError>; /// Read one peer's durable runtime state. async fn get_federation_peer_state( &self, peer_did: &str, ) -> Result, ServerError>; /// List peer runtime state in stable DID order. async fn list_federation_peer_states( &self, page: PageRequest, ) -> Result, ServerError>; /// Exclusively lease peers whose retry/breaker window permits a request. async fn claim_federation_peers( &self, worker_id: &str, now: DateTime, lease_expires_at: DateTime, limit: u32, ) -> Result, ServerError>; /// Complete a peer claim and advance its cursor monotonically. async fn complete_federation_peer_claim( &self, claim: &FederationPeerClaim, next_cursor: u64, remote_head: u64, latency_ms: u64, next_attempt_at: DateTime, completed_at: DateTime, ) -> Result; /// Fail a peer claim and persist retry/circuit-breaker state. async fn fail_federation_peer_claim( &self, claim: &FederationPeerClaim, breaker_state: mars_protocol::federation::FederationBreakerState, next_attempt_at: DateTime, failed_at: DateTime, ) -> Result; /// Persist one malicious or malformed remote payload and increment the /// peer's bounded status counter. async fn quarantine_federation_payload( &self, record: FederationQuarantineRecord, ) -> Result<(), ServerError>; /// Count quarantine records, optionally scoped to one peer. async fn count_federation_quarantine(&self, peer_did: Option<&str>) -> Result; /// Idempotently apply a publisher-verified remote entry. Conflict /// selection and the delivery record commit in one transaction. async fn commit_federation_import( &self, command: FederationImportCommand, ) -> Result; /// Whether local immutable anchor evidence confirms this exact entry hash. async fn has_confirmed_anchor( &self, entry_did: &str, item_data_hash: &str, ) -> Result; /// Snapshot durable federation metrics. async fn federation_metrics(&self) -> Result; /// Persist or update a peer agreement. async fn put_federation_agreement( &self, peer_did: &str, agreement: FederationAgreement, ) -> Result<(), ServerError>; /// List active agreements for one peer in stable ID order. async fn list_federation_agreements( &self, peer_did: &str, page: PageRequest, ) -> Result, ServerError>; /// Append a signed federation request audit record. async fn commit_federation_audit(&self, audit: AuditRecord) -> Result<(), ServerError>; /// Register or update a federation peer. async fn put_peer(&self, peer: FederationPeer) -> Result<(), ServerError>; /// List a bounded page of known federation peers. async fn list_peers(&self, page: PageRequest) -> Result, ServerError>; /// Get entries changed since a given sequence number (for federation sync). /// /// Returns `(entries, next_sequence, has_more)`. async fn entries_since_sequence( &self, from_seq: u64, max: u32, ) -> Result<(Vec, u64, bool), ServerError>; /// Liveness probe for the storage backend. /// /// Default implementation always returns `Ok(())`. The PostgreSQL backend /// overrides this to execute a `SELECT 1` round-trip so the deep health /// endpoint can detect connection pool exhaustion or a downed database. async fn health_check(&self) -> Result<(), ServerError> ; } ``` Source line: `1284`. ## store::ShardedStore [#storeshardedstore] Storage backend trait for shard-aware operations. When the `sharding` feature is enabled, this trait extends the storage layer with shard routing, placement, and scatter-gather capabilities. ```rust #[cfg(feature = "sharding")] #[async_trait] pub trait ShardedStore: Send + Sync { /// Get the shard IDs managed by this store. fn shard_ids(&self) -> Vec; /// Get the store for a specific shard. fn shard_store(&self, shard_id: &str) -> Option>; /// Assign an entry to a shard based on its DID and publisher DID. fn assign_shard(&self, entry_did: &str, publisher_did: &str) -> Result; /// Execute a query against specific shards (scatter). /// /// If `shard_ids` is empty, queries all shards. async fn scatter_query( &self, shard_ids: &[String], query: &mars_protocol::marsql::ast::MarsQuery, ) -> Result, ServerError>; } ``` Source line: `1771`. ## Source provenance [#source-provenance] Source: `mars-server/src/store/mod.rs` · SHA-256 `ba6b32053130efece077c63639b344eecbb61afab1e265d1d5c675abc2f19d07`. [Package overview](/libraries/mars-server). # mars-server · validation URL: https://docs.mars.glass/libraries/mars-server/validation Markdown: https://docs.mars.glass/libraries/mars-server/validation.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::validation. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `validation` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## validation::resolver [#validationresolver] Validation pipeline for MARS registry entries. Per MARS Specification Section 12.3, the pipeline runs these checks in order: 1. **Schema check** — `entry.validate()` from `mars-protocol` 2. **DID format check** — verify `entry_did` and `publisher_did` are valid OAS DIDs. 3. **Hash verification** — recompute `item_data_hash` and compare. 4. **Signature verification** — resolve the publisher's Ed25519 public key, apply the canonical `MARS-PUBLISHER-SIGNING-V1` profile, and verify the Ed25519 signature. The signing key's controller DID must equal the entry's `publisher_did` (no impersonation across publishers). For self-signed records (`HumanRootRecord` and friends), policy may allow the resolver to extract the key from the entry's own `item_data`. 5. **Sequence check** — new entry must have `sequence > existing` (replay protection). 6. **Bond check** — if the entry type requires a bond, verify `bond_reference` is present and meets the minimum amount. ```rust pub mod resolver; ``` Source line: `20`. ## validation::ValidationPipeline [#validationvalidationpipeline] Validation pipeline that runs the MARS-spec validation steps. Holds an \[`Arc<dyn PublisherKeyResolver>`] so signature verification can resolve publisher keys from a static pin map, the entry store, or a composite resolver. Cloning a pipeline is cheap (Arc bump). ```rust #[derive(Clone)] pub struct ValidationPipeline { } ``` Source line: `59`. ## validation::ValidationPipeline::new [#validationvalidationpipelinenew] Create a fail-closed validation pipeline with the given resolver. Self-signed root bootstrap is disabled. Development or migration tools that intentionally need bootstrap must call \[`Self::new_with_bootstrap_policy`] with an explicit `true`. ```rust pub fn new(registry_did: &str, key_resolver: Arc) -> Self; ``` Source line: `88`. ## validation::ValidationPipeline::new\_with\_bootstrap\_policy [#validationvalidationpipelinenew_with_bootstrap_policy] Create a validation pipeline with an explicit root bootstrap policy. ```rust pub fn new_with_bootstrap_policy( registry_did: &str, key_resolver: Arc, allow_self_signed_bootstrap: bool, ) -> Self; ``` Source line: `98`. ## validation::ValidationPipeline::new\_with\_components [#validationvalidationpipelinenew_with_components] Construct the pipeline with explicit trust and bond ports. ```rust pub fn new_with_components( registry_did: &str, key_resolver: Arc, bond_port: Arc, allow_self_signed_bootstrap: bool, ) -> Self; ``` Source line: `112`. ## validation::ValidationPipeline::with\_static\_and\_store [#validationvalidationpipelinewith_static_and_store] Fail-closed layered constructor that tries the supplied static map first and falls back to the store. Root bootstrap is disabled unless the caller chooses it explicitly via \[`Self::with_static_and_store_and_bootstrap_policy`]. ```rust pub fn with_static_and_store( registry_did: &str, static_keys: StaticKeyResolver, store: Arc, ) -> Self; ``` Source line: `131`. ## validation::ValidationPipeline::with\_static\_and\_store\_and\_bootstrap\_policy [#validationvalidationpipelinewith_static_and_store_and_bootstrap_policy] Build the pinned-first resolver chain with an explicit bootstrap policy. ```rust pub fn with_static_and_store_and_bootstrap_policy( registry_did: &str, static_keys: StaticKeyResolver, store: Arc, allow_self_signed_bootstrap: bool, ) -> Self; ``` Source line: `140`. ## validation::ValidationPipeline::validate\_new\_entry [#validationvalidationpipelinevalidate_new_entry] Validate a new entry through the full pipeline. Runs all spec validation steps (schema, DID format, hash, signature, bond). Does not run the sequence check because this is a brand-new entry. ```rust pub async fn validate_new_entry( &self, entry: &MarsEntry, store: &dyn EntryStore, ) -> Result<(), ServerError>; ``` Source line: `163`. ## validation::ValidationPipeline::validate\_federated\_entry [#validationvalidationpipelinevalidate_federated_entry] Validate publisher-authored federation content before conflict resolution or import. Bond availability and registry sequence are local state concerns and are deliberately not treated as substitutes for publisher provenance. The import path verifies structure, OAS identity, item hash, and the controller-bound Ed25519 signature, then applies local anchor and visibility policy separately. ```rust pub async fn validate_federated_entry( &self, entry: &MarsEntry, store: &dyn EntryStore, ) -> Result<(), ServerError>; ``` Source line: `187`. ## validation::ValidationPipeline::validate\_update [#validationvalidationpipelinevalidate_update] Validate an entry update through the full pipeline. Runs all spec validation steps plus sequence replay protection. ```rust pub async fn validate_update( &self, entry: &MarsEntry, store: &dyn EntryStore, ) -> Result<(), ServerError>; ``` Source line: `204`. ## validation::ValidationPipeline::resolve\_trusted\_key [#validationvalidationpipelineresolve_trusted_key] Resolve a trusted Ed25519 key without performing external IO. ```rust pub async fn resolve_trusted_key( &self, key_id: &str, ) -> Result; ``` Source line: `225`. ## validation::ValidationPipeline::verify\_detached\_signature [#validationvalidationpipelineverify_detached_signature] Verify an Ed25519 signature over a detached JCS-canonical payload. ```rust pub async fn verify_detached_signature( &self, expected_controller: &str, payload: &T, signature: &mars_protocol::signature::EntrySignature, ) -> Result<(), ServerError>; ``` Source line: `242`. ## validation::ValidationPipeline::verify\_oas\_attestation [#validationvalidationpipelineverify_oas_attestation] Verify a canonical OAS Verifiable Credential using only local trust and revocation inputs. The authenticated principal must equal `credential.issuer`, the credential subject must equal the target entry, the proof verification method controller must equal that issuer, and the proof must verify against a locally resolved trusted key. Issuance/expiry checks run only after those signature bindings succeed. ```rust pub async fn verify_oas_attestation( &self, credential: &oas_attestation::credential::OasCredential, authenticated_issuer: &str, entry_did: &str, now: chrono::DateTime, ) -> Result<(), ServerError>; ``` Source line: `272`. ## Source provenance [#source-provenance] Source: `mars-server/src/validation/mod.rs` · SHA-256 `7b4e9292d622b0eaf4dfd166aae0d1aea9e661613f4dad5cdcc73239bdb56bec`. [Package overview](/libraries/mars-server). # mars-server · api::rest URL: https://docs.mars.glass/libraries/mars-server/api/rest Markdown: https://docs.mars.glass/libraries/mars-server/api/rest.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::api::rest. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `api::rest` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## api::rest::create\_entry [#apirestcreate_entry] `POST /v1/entries` -- Create a new registry entry. This handler runs behind capability-aware auth middleware. The middleware resolves the caller's session into a \[`Principal`] and inserts it as a request extension. The handler then: 1. **Rate-limits per publisher**, keying \[`crate::middleware::RateLimiter`] on `principal.publisher_did`. 2. **Runs the full validation pipeline first** (schema → DID → hash → signature → bond) so the caller can't probe whether an unauthorised `publisher_did` would have validated. 3. **Enforces the publisher binding** — entries whose `publisher_did` differs from the session's HMR are rejected with MARS-007 (InsufficientPermissions). No proxy publishing. ```rust pub async fn create_entry( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Json(mut entry): Json, ) -> Result; ``` Source line: `192`. ## api::rest::get\_entry [#apirestget_entry] `GET /v1/entries/:did` -- Get the latest version of an entry by DID. ```rust pub async fn get_entry( State(state): State>, Path(did): Path, ) -> Result; ``` Source line: `258`. ## api::rest::get\_entry\_version [#apirestget_entry_version] `GET /v1/entries/:did/versions/:version` -- Get a specific version. ```rust pub async fn get_entry_version( State(state): State>, Path((did, version)): Path<(String, String)>, ) -> Result; ``` Source line: `271`. ## api::rest::list\_entry\_versions [#apirestlist_entry_versions] `GET /v1/entries/:did/versions` -- List a bounded version page, newest first. ```rust pub async fn list_entry_versions( State(state): State>, Path(did): Path, Query(query): Query, ) -> Result; ``` Source line: `284`. ## api::rest::get\_entry\_lineage [#apirestget_entry_lineage] `GET /v1/entries/:did/lineage` -- Get an entry's canonical lineage summary. ```rust pub async fn get_entry_lineage( State(state): State>, Path(did): Path, ) -> Result; ``` Source line: `323`. ## api::rest::update\_entry [#apirestupdate_entry] `PUT /v1/entries/:did` -- Update an existing entry. Requires `Capability::UpdateEntry`. The principal publisher must match `entry.publisher_did` — no proxy updates. ```rust pub async fn update_entry( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Path(did): Path, Json(mut entry): Json, ) -> Result; ``` Source line: `343`. ## api::rest::delete\_entry [#apirestdelete_entry] `DELETE /v1/entries/:did` -- Revoke an entry. Requires `Capability::RevokeEntry`. The principal publisher must match the existing entry's `publisher_did`; only the owner can revoke the entry. ```rust pub async fn delete_entry( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Path(did): Path, ) -> Result; ``` Source line: `446`. ## api::rest::discover [#apirestdiscover] `POST /v1/discover` -- Discover entries via structured JSON query. ```rust pub async fn discover( State(state): State>, Json(req): Json, ) -> Result; ``` Source line: `499`. ## api::rest::discover\_marsql [#apirestdiscover_marsql] `POST /v1/discover/marsql` -- Discover entries via MARS-QL query string. ```rust pub async fn discover_marsql( State(state): State>, Json(req): Json, ) -> Result; ``` Source line: `701`. ## api::rest::discover\_federated [#apirestdiscover_federated] `POST /v1/discover/federated` -- Optional bounded local-plus-peer query. ```rust pub async fn discover_federated( State(state): State>, Extension(_principal): Extension, Json(query): Json, ) -> Result; ``` Source line: `712`. ## api::rest::create\_transfer\_offer [#apirestcreate_transfer_offer] Create a signed, expiring transfer offer. This never changes ownership. ```rust pub async fn create_transfer_offer( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Path(did): Path, Json(req): Json, ) -> Result; ``` Source line: `735`. ## api::rest::get\_transfer\_offer [#apirestget_transfer_offer] Read one transfer offer. Elapsed live offers are projected as expired. ```rust pub async fn get_transfer_offer( State(state): State>, Path(offer_id): Path, ) -> Result; ``` Source line: `823`. ## api::rest::accept\_transfer\_offer [#apirestaccept_transfer_offer] Accept a transfer with a complete entry re-signed by the recipient. ```rust pub async fn accept_transfer_offer( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Path(offer_id): Path, Json(mut req): Json, ) -> Result; ``` Source line: `867`. ## api::rest::decline\_transfer\_offer [#apirestdecline_transfer_offer] Decline a transfer offer. The recipient identity comes only from Principal. ```rust pub async fn decline_transfer_offer( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Path(offer_id): Path, Json(req): Json, ) -> Result; ``` Source line: `995`. ## api::rest::create\_attestation [#apirestcreate_attestation] Store and verify a canonical OAS Verifiable Credential separately. ```rust pub async fn create_attestation( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Json(req): Json, ) -> Result; ``` Source line: `1057`. ## api::rest::get\_attestations [#apirestget_attestations] Read canonical attestations, filtering expired and revoked records by default. ```rust pub async fn get_attestations( State(state): State>, Path(did): Path, Query(query): Query, ) -> Result; ``` Source line: `1169`. ## api::rest::create\_report [#apirestcreate_report] `POST /v1/report` -- File a malicious-behaviour report against an entry. ```rust pub async fn create_report( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Json(req): Json, ) -> Result; ``` Source line: `1194`. ## api::rest::get\_anchors [#apirestget_anchors] `GET /v1/anchors/:did` -- Get persisted anchor intents and receipts. ```rust pub async fn get_anchors( State(state): State>, Path(did): Path, Query(query): Query, ) -> Result; ``` Source line: `1248`. ## api::rest::retry\_anchor [#apirestretry_anchor] Requeue a failed or abandoned anchor intent. ```rust pub async fn retry_anchor( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Path(intent_id): Path, ) -> Result; ``` Source line: `1306`. ## api::rest::abandon\_anchor [#apirestabandon_anchor] Permanently abandon a pending, expired-claim, or failed anchor intent. ```rust pub async fn abandon_anchor( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Path(intent_id): Path, ) -> Result; ``` Source line: `1349`. ## api::rest::get\_bond [#apirestget_bond] `GET /v1/bonds/:bond_id` -- Get a bond by ID. ```rust pub async fn get_bond( State(state): State>, Path(bond_id): Path, ) -> Result; ``` Source line: `1392`. ## api::rest::provision\_bond [#apirestprovision_bond] Admin-scoped provisioning of registry-local bond metadata. ```rust pub async fn provision_bond( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Json(request): Json, ) -> Result; ``` Source line: `1405`. ## api::rest::health\_check [#apiresthealth_check] `GET /v1/health` -- Health check endpoint (no rate limit). ```rust pub async fn health_check(State(state): State>) -> impl IntoResponse; ``` Source line: `1465`. ## api::rest::health\_check\_deep [#apiresthealth_check_deep] `GET /v1/health/deep` -- Operator-only, rate-limited deep health check. Runs storage, durable anchor-outbox, adapter registration, and immutable ledger-chain checks. Returns HTTP 200 so load balancers can inspect the body. Aggregate status semantics: * `"ok"` — every subsystem reported `ok`. * `"degraded"` — at least one subsystem was `skipped` but none failed. * `"down"` — at least one subsystem failed. ```rust pub async fn health_check_deep(State(state): State>) -> impl IntoResponse; ``` Source line: `1482`. ## api::rest::list\_federation\_peers [#apirestlist_federation_peers] `GET /v1/federation/peers` -- List known federation peers. ```rust pub async fn list_federation_peers( State(state): State>, ) -> Result; ``` Source line: `1654`. ## api::rest::federation\_peer\_status [#apirestfederation_peer_status] Protected operational status for configured federation peers. ```rust pub async fn federation_peer_status( State(state): State>, ) -> Result; ``` Source line: `1665`. ## api::rest::update\_federation\_peer [#apirestupdate_federation_peer] Register or change the authenticated peer's own endpoint metadata. ```rust pub async fn update_federation_peer( State(state): State>, Extension(principal): Extension, Extension(context): Extension, Json(request): Json, ) -> Result; ``` Source line: `1680`. ## api::rest::federation\_sync [#apirestfederation_sync] `POST /v1/federation/sync` -- Handle incoming federation sync request. ```rust pub async fn federation_sync( State(state): State>, Json(envelope): Json>, ) -> Result; ``` Source line: `1760`. ## api::rest::federation\_discover [#apirestfederation_discover] Signed peer-side MARS-QL discovery. ```rust pub async fn federation_discover( State(state): State>, Json(envelope): Json>, ) -> Result; ``` Source line: `1777`. ## Source provenance [#source-provenance] Source: `mars-server/src/api/rest.rs` · SHA-256 `31bb320dc19cafc960d4e359be9f971959046d4a0a27fce443fcc7806a417aa6`. [Package overview](/libraries/mars-server). # mars-server · api::websocket URL: https://docs.mars.glass/libraries/mars-server/api/websocket Markdown: https://docs.mars.glass/libraries/mars-server/api/websocket.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::api::websocket. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `api::websocket` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## api::websocket::ws\_handler [#apiwebsocketws_handler] WebSocket upgrade handler for `/v1/ws`. ```rust pub async fn ws_handler( ws: WebSocketUpgrade, State(state): State>, ) -> impl IntoResponse; ``` Source line: `19`. ## Source provenance [#source-provenance] Source: `mars-server/src/api/websocket.rs` · SHA-256 `7b54b888a149dec0ab5312a022ce26834752b82c7a28281888c83ac201f322d3`. [Package overview](/libraries/mars-server). # mars-server · federation::discovery URL: https://docs.mars.glass/libraries/mars-server/federation/discovery Markdown: https://docs.mars.glass/libraries/mars-server/federation/discovery.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::federation::discovery. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `federation::discovery` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## federation::discovery::FederatedDiscoveryConfig [#federationdiscoveryfederateddiscoveryconfig] Federated query fanout, policy, and cursor bounds. ```rust #[derive(Debug, Clone)] pub struct FederatedDiscoveryConfig { pub enabled: bool, pub fanout: u32, pub peer_timeout: StdDuration, pub max_results_per_peer: u32, /// Maximum remote result slots (`selected peers * per-peer result cap`) /// consumed by one request. pub max_cost: u64, pub default_page_size: u64, pub max_page_size: u64, pub anchoring_required: bool, pub cursor_ttl: Duration } ``` Source line: `39`. ## federation::discovery::FederatedDiscoveryCoordinator [#federationdiscoveryfederateddiscoverycoordinator] Optional fanout coordinator. Remote entries are treated as untrusted until envelope, publisher, query, visibility, and local anchor checks complete. ```rust #[derive(Clone)] pub struct FederatedDiscoveryCoordinator { } ``` Source line: `80`. ## federation::discovery::FederatedDiscoveryCoordinator::new [#federationdiscoveryfederateddiscoverycoordinatornew] ```rust #[allow(clippy::too_many_arguments)] pub fn new( local: Arc, store: Arc, transport: Arc, signer: FederationSigner, verifier: FederationEnvelopeVerifier, validation: ValidationPipeline, config: FederatedDiscoveryConfig, ) -> Result; ``` Source line: `92`. ## federation::discovery::FederatedDiscoveryCoordinator::execute [#federationdiscoveryfederateddiscoverycoordinatorexecute] Execute using the server clock. ```rust pub async fn execute( &self, query: &MarsQuery, ) -> Result; ``` Source line: `114`. ## federation::discovery::FederatedDiscoveryCoordinator::execute\_at [#federationdiscoveryfederateddiscoverycoordinatorexecute_at] Deterministic clock entry point used by tests and replay tooling. ```rust pub async fn execute_at( &self, query: &MarsQuery, now: DateTime, ) -> Result; ``` Source line: `122`. ## Source provenance [#source-provenance] Source: `mars-server/src/federation/discovery.rs` · SHA-256 `9f0ea2708dfe0a6e84c362c799bce0584f51c1188dcb0fec58bd2c6dc71b7051`. [Package overview](/libraries/mars-server). # mars-server · federation::envelope URL: https://docs.mars.glass/libraries/mars-server/federation/envelope Markdown: https://docs.mars.glass/libraries/mars-server/federation/envelope.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::federation::envelope. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `federation::envelope` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## federation::envelope::FederationEnvelopeError [#federationenvelopefederationenvelopeerror] Federation authentication or envelope validation failure. ```rust #[derive(Debug, thiserror::Error)] pub enum FederationEnvelopeError { #[error("federation identity is invalid")] InvalidIdentity, #[error("federation key controller does not match its sender")] ControllerMismatch, #[error("federation envelope type or version is invalid")] InvalidEnvelope, #[error("federation envelope request digest is invalid")] RequestDigestMismatch, #[error("federation envelope clock is outside the accepted window")] ClockSkew, #[error("federation envelope signature is invalid")] InvalidSignature, #[error("federation envelope replay detected")] Replay, #[error("federation trust dependency failed")] TrustDependency, #[error("federation replay storage failed")] ReplayStorage, } ``` Source line: `29`. ## federation::envelope::VerifiedFederationMessage [#federationenvelopeverifiedfederationmessage] A verified payload and the MARS-owned principal derived from it. ```rust #[derive(Debug, Clone)] pub struct VerifiedFederationMessage { pub payload: T, pub principal: Principal, pub envelope_digest: String } ``` Source line: `52`. ## federation::envelope::FederationSigner [#federationenvelopefederationsigner] Registry signing identity. Private key bytes are zeroized by `OasKeyPair` and redacted from debug output. ```rust #[derive(Clone)] pub struct FederationSigner { } ``` Source line: `61`. ## federation::envelope::FederationSigner::new [#federationenvelopefederationsignernew] Construct a signer bound to one canonical OAS service DID. ```rust pub fn new( registry_did: impl Into, key_id: impl Into, keypair: OasKeyPair, ) -> Result; ``` Source line: `80`. ## federation::envelope::FederationSigner::load\_from\_config [#federationenvelopefederationsignerload_from_config] Load a 32-byte Ed25519 seed from exactly one protected path or environment variable. Input buffers are zeroized after construction. ```rust pub fn load_from_config( registry_did: &str, config: &FederationConfig, ) -> Result; ``` Source line: `98`. ## federation::envelope::FederationSigner::registry\_did [#federationenvelopefederationsignerregistry_did] Canonical sender DID. ```rust pub fn registry_did(&self) -> &str; ``` Source line: `141`. ## federation::envelope::FederationSigner::public\_key\_base64url [#federationenvelopefederationsignerpublic_key_base64url] Canonical unpadded base64url public key used by the frozen OpenAgent `Authorization: OpenAgent <sig>.<pubkey>` transport header. ```rust pub fn public_key_base64url(&self) -> String; ``` Source line: `147`. ## federation::envelope::FederationSigner::sign\_request [#federationenvelopefederationsignersign_request] Sign a request whose digest is derived from its exact typed payload. ```rust pub fn sign_request( &self, kind: FederationMessageKind, recipient_did: impl Into, payload: T, timestamp: DateTime, ) -> Result, FederationEnvelopeError> where T: Serialize,; ``` Source line: `181`. ## federation::envelope::FederationSigner::sign\_response [#federationenvelopefederationsignersign_response] Sign a response and bind it to the full request envelope. ```rust pub fn sign_response( &self, kind: FederationMessageKind, request: &SignedFederationEnvelope, payload: T, timestamp: DateTime, ) -> Result, FederationEnvelopeError> where T: Serialize, R: Serialize,; ``` Source line: `208`. ## federation::envelope::FederationEnvelopeVerifier [#federationenvelopefederationenvelopeverifier] Verifies peer envelopes, consumes durable nonces, and derives a scoped federation principal only after every binding succeeds. ```rust #[derive(Clone)] pub struct FederationEnvelopeVerifier { } ``` Source line: `271`. ## federation::envelope::FederationEnvelopeVerifier::new [#federationenvelopefederationenvelopeverifiernew] ```rust pub fn new( local_registry_did: impl Into, keys: Arc, store: Arc, max_clock_skew: Duration, nonce_ttl: Duration, ) -> Result; ``` Source line: `281`. ## federation::envelope::FederationEnvelopeVerifier::with\_expected\_peer [#federationenvelopefederationenvelopeverifierwith_expected_peer] Pin this verifier to one configured peer identity. ```rust #[must_use] pub fn with_expected_peer(mut self, peer_did: impl Into) -> Self; ``` Source line: `308`. ## federation::envelope::FederationEnvelopeVerifier::verify\_request [#federationenvelopefederationenvelopeverifierverify_request] Verify a signed request and atomically consume its nonce. ```rust pub async fn verify_request( &self, envelope: &SignedFederationEnvelope, expected_kind: FederationMessageKind, now: DateTime, ) -> Result, FederationEnvelopeError> where T: Serialize + Clone + Sync,; ``` Source line: `314`. ## federation::envelope::FederationEnvelopeVerifier::verify\_response [#federationenvelopefederationenvelopeverifierverify_response] Verify a signed response and bind it to the request envelope. ```rust pub async fn verify_response( &self, envelope: &SignedFederationEnvelope, expected_kind: FederationMessageKind, request: &SignedFederationEnvelope, now: DateTime, ) -> Result, FederationEnvelopeError> where T: Serialize + Clone + Sync, R: Serialize,; ``` Source line: `334`. ## federation::envelope::canonical\_digest [#federationenvelopecanonical_digest] SHA-256 digest of a typed JCS payload. ```rust pub fn canonical_digest(value: &T) -> Result; ``` Source line: `481`. ## federation::envelope::envelope\_digest [#federationenvelopeenvelope_digest] SHA-256 digest of the complete canonical signed envelope. ```rust pub fn envelope_digest( envelope: &SignedFederationEnvelope, ) -> Result; ``` Source line: `487`. ## Source provenance [#source-provenance] Source: `mars-server/src/federation/envelope.rs` · SHA-256 `d066ccafe527ca2681a24c46d2b1511619cd132467921ff8fd458056134bd87f`. [Package overview](/libraries/mars-server). # mars-server · federation::policy URL: https://docs.mars.glass/libraries/mars-server/federation/policy Markdown: https://docs.mars.glass/libraries/mars-server/federation/policy.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::federation::policy. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `federation::policy` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## federation::policy::VersionTrust [#federationpolicyversiontrust] Trust facts established before conflict selection. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct VersionTrust { /// Publisher Ed25519 signature verified against a controller-bound key. pub publisher_signature_verified: bool, /// A matching confirmed anchor receipt was verified in local durable state. pub confirmed_anchor_verified: bool, /// Source registry sequence for this version. pub sequence: u64, /// SHA-256 of the JCS publisher-authored entry. pub content_digest: String } ``` Source line: `11`. ## federation::policy::ConflictWinner [#federationpolicyconflictwinner] Deterministic conflict winner. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ConflictWinner { Local, Remote, Identical, } ``` Source line: `24`. ## federation::policy::ConflictResolutionError [#federationpolicyconflictresolutionerror] Conflict selection failure. ```rust #[derive(Debug, thiserror::Error)] pub enum ConflictResolutionError { #[error("conflict candidate publisher signature is not verified")] UnverifiedPublisherSignature, #[error("conflict candidate digest is malformed")] InvalidDigest, } ``` Source line: `32`. ## federation::policy::resolve\_verified\_conflict [#federationpolicyresolve_verified_conflict] Resolve a conflict only after both publisher signatures have been cryptographically verified. A locally confirmed matching anchor wins first. If anchor evidence is equal, the higher source sequence wins. Equal sequences use the lexically lower canonical SHA-256 digest, yielding the same result on every registry. ```rust pub fn resolve_verified_conflict( local: &VersionTrust, remote: &VersionTrust, ) -> Result; ``` Source line: `45`. ## federation::policy::PeerNetworkError [#federationpolicypeernetworkerror] URL or DNS safety failure. Messages are deliberately non-sensitive and do not include resolved internal addresses. ```rust #[derive(Debug, thiserror::Error)] pub enum PeerNetworkError { #[error("federation peer URL is invalid")] InvalidUrl, #[error("federation peer URL must use HTTPS")] HttpsRequired, #[error("federation peer URL authority is not allowed")] InvalidAuthority, #[error("federation peer DNS returned no usable addresses")] MissingAddress, #[error("federation peer address is blocked by SSRF policy")] BlockedAddress, #[error("federation peer DNS resolution failed")] ResolutionFailed, } ``` Source line: `189`. ## federation::policy::validate\_peer\_url\_and\_addresses [#federationpolicyvalidate_peer_url_and_addresses] Parse an HTTPS peer URL and validate every resolved address. A mixed public/private DNS answer fails closed. Non-public addresses are accepted only when every such address is contained in an explicit CIDR. ```rust pub fn validate_peer_url_and_addresses( raw_url: &str, addresses: &[IpAddr], allow_private_cidrs: &[IpNet], ) -> Result; ``` Source line: `208`. ## federation::policy::resolve\_peer\_endpoint [#federationpolicyresolve_peer_endpoint] Resolve and pin a peer endpoint before constructing an HTTP client. ```rust pub async fn resolve_peer_endpoint( raw_url: &str, allow_private_cidrs: &[IpNet], ) -> Result<(Url, Vec), PeerNetworkError>; ``` Source line: `253`. ## Source provenance [#source-provenance] Source: `mars-server/src/federation/policy.rs` · SHA-256 `be95f7ddb9def0ec9adfe7e98024136229d2dfc05ecc32a7c793386c908ec2f4`. [Package overview](/libraries/mars-server). # mars-server · federation::service URL: https://docs.mars.glass/libraries/mars-server/federation/service Markdown: https://docs.mars.glass/libraries/mars-server/federation/service.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::federation::service. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `federation::service` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## federation::service::FederationService [#federationservicefederationservice] Authenticated inbound sync/discovery surface. ```rust pub struct FederationService { } ``` Source line: `24`. ## federation::service::FederationService::new [#federationservicefederationservicenew] ```rust pub fn new( store: Arc, manager: FederationManager, discovery: Arc, signer: FederationSigner, verifier: FederationEnvelopeVerifier, ) -> Self; ``` Source line: `33`. ## federation::service::FederationService::sync [#federationservicefederationservicesync] Authenticate, authorize, and serve one pull request. ```rust pub async fn sync( &self, envelope: &SignedFederationEnvelope, now: DateTime, ) -> Result, ServerError>; ``` Source line: `50`. ## federation::service::FederationService::discover [#federationservicefederationservicediscover] Authenticate, authorize, and serve a typed MARS-QL request. ```rust pub async fn discover( &self, envelope: &SignedFederationEnvelope, now: DateTime, ) -> Result, ServerError>; ``` Source line: `96`. ## Source provenance [#source-provenance] Source: `mars-server/src/federation/service.rs` · SHA-256 `6eea90edb344dd999e55c160124e787fbbbb152a1701eee75aaec9a6d22cf927`. [Package overview](/libraries/mars-server). # mars-server · federation::transport URL: https://docs.mars.glass/libraries/mars-server/federation/transport Markdown: https://docs.mars.glass/libraries/mars-server/federation/transport.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::federation::transport. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `federation::transport` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## federation::transport::FederationTransportError [#federationtransportfederationtransporterror] Bounded transport failure classes used by circuit-breaker metrics. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] pub enum FederationTransportError { #[error("federation request timed out")] Timeout, #[error("federation peer is unavailable")] Unavailable, #[error("federation TLS authentication failed")] Tls, #[error("federation protocol response is invalid")] Protocol, #[error("federation response exceeded its size limit")] ResponseTooLarge, #[error("federation operation is unsupported")] Unsupported, } ``` Source line: `25`. ## federation::transport::FederationTransportError::as\_str [#federationtransportfederationtransporterroras_str] Stable, bounded metric label. ```rust pub const fn as_str(self) -> &'static str; ``` Source line: `42`. ## federation::transport::FederationTransport [#federationtransportfederationtransport] MARS-owned network boundary for federation. ```rust #[async_trait] pub trait FederationTransport: Send + Sync { async fn sync( &self, peer: &FederationPeerState, request: SignedFederationEnvelope, ) -> Result, FederationTransportError>; async fn discover( &self, peer: &FederationPeerState, request: SignedFederationEnvelope, ) -> Result, FederationTransportError>; } ``` Source line: `56`. ## federation::transport::FederationTransportRegistry [#federationtransportfederationtransportregistry] Immutable-after-startup transport registry for multiple identity-bound peers. ```rust #[derive(Default)] pub struct FederationTransportRegistry { } ``` Source line: `73`. ## federation::transport::FederationTransportRegistry::new [#federationtransportfederationtransportregistrynew] ```rust pub fn new() -> Self; ``` Source line: `78`. ## federation::transport::FederationTransportRegistry::register [#federationtransportfederationtransportregistryregister] ```rust pub fn register( &mut self, peer_did: impl Into, transport: Arc, ) -> Result<(), FederationTransportError>; ``` Source line: `82`. ## federation::transport::FederationTransportRegistry::len [#federationtransportfederationtransportregistrylen] ```rust pub fn len(&self) -> usize; ``` Source line: `94`. ## federation::transport::FederationTransportRegistry::is\_empty [#federationtransportfederationtransportregistryis_empty] ```rust pub fn is_empty(&self) -> bool; ``` Source line: `98`. ## federation::transport::ReqwestFederationTransport [#federationtransportreqwestfederationtransport] HTTPS transport with DNS answers pinned for the client lifetime. ```rust pub struct ReqwestFederationTransport { } ``` Source line: `133`. ## federation::transport::ReqwestFederationTransport::validate\_mtls\_files [#federationtransportreqwestfederationtransportvalidate_mtls_files] Parse configured certificate/key/CA material without opening a socket. ```rust pub fn validate_mtls_files(config: &MtlsConfig) -> Result<(), FederationTransportError>; ``` Source line: `155`. ## federation::transport::ReqwestFederationTransport::for\_peer [#federationtransportreqwestfederationtransportfor_peer] Resolve, validate, and pin one peer. No request is issued during construction. ```rust pub async fn for_peer( peer: &FederationPeerConfig, public_key_base64url: impl Into, request_timeout: Duration, connect_timeout: Duration, ) -> Result; ``` Source line: `167`. ## Source provenance [#source-provenance] Source: `mars-server/src/federation/transport.rs` · SHA-256 `7152b5ddcd1ea06c2c526873fc8affc4df4d24269516c983b64a967105e15619`. [Package overview](/libraries/mars-server). # mars-server · federation::worker URL: https://docs.mars.glass/libraries/mars-server/federation/worker Markdown: https://docs.mars.glass/libraries/mars-server/federation/worker.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::federation::worker. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `federation::worker` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## federation::worker::FederationWorkerConfig [#federationworkerfederationworkerconfig] Bounded synchronization worker policy. ```rust #[derive(Debug, Clone)] pub struct FederationWorkerConfig { pub max_concurrency: u32, pub batch_size: u32, pub sync_interval: Duration, pub lease_duration: Duration, pub request_timeout: StdDuration, pub retry_base: Duration, pub retry_max: Duration, pub jitter_bps: u16, pub breaker_failure_threshold: u32, pub breaker_cooldown: Duration } ``` Source line: `29`. ## federation::worker::FederationWorkerConfig::validate [#federationworkerfederationworkerconfigvalidate] ```rust pub fn validate(&self) -> Result<(), FederationWorkerError>; ``` Source line: `43`. ## federation::worker::FederationRunSummary [#federationworkerfederationrunsummary] Aggregate result of one bounded worker pass. ```rust #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct FederationRunSummary { pub attempted_peers: u32, pub completed_peers: u32, pub failed_peers: u32, pub imported: u64, pub retained_local: u64, pub duplicate_deliveries: u64, pub quarantined: u64 } ``` Source line: `65`. ## federation::worker::FederationWorkerError [#federationworkerfederationworkererror] Worker construction or durable-state failure. ```rust #[derive(Debug, thiserror::Error)] pub enum FederationWorkerError { #[error("federation worker configuration is invalid")] InvalidConfig, #[error("federation durable state failed: {0}")] Store(#[from] ServerError), #[error("federation worker task failed")] Task, } ``` Source line: `91`. ## federation::worker::FederationSyncWorker [#federationworkerfederationsyncworker] Pull-based worker. Claims commit before network activity, imports are idempotent, and cursor completion commits only after every payload has been validated or quarantined. ```rust #[derive(Clone)] pub struct FederationSyncWorker { } ``` Source line: `104`. ## federation::worker::FederationSyncWorker::new [#federationworkerfederationsyncworkernew] ```rust #[allow(clippy::too_many_arguments)] pub fn new( worker_id: impl Into, store: Arc, transport: Arc, signer: FederationSigner, verifier: FederationEnvelopeVerifier, validation: ValidationPipeline, config: FederationWorkerConfig, ) -> Result; ``` Source line: `116`. ## federation::worker::FederationSyncWorker::run\_once [#federationworkerfederationsyncworkerrun_once] Run one bounded synchronization pass. ```rust pub async fn run_once( &self, now: DateTime, ) -> Result; ``` Source line: `142`. ## federation::worker::FederationSyncWorker::run\_until\_shutdown [#federationworkerfederationsyncworkerrun_until_shutdown] Run bounded passes until shutdown. Transient pass failures are recorded and retried on the next interval; they never erase durable cursor or breaker state. ```rust pub async fn run_until_shutdown( self, interval: StdDuration, mut shutdown: tokio::sync::watch::Receiver, ); ``` Source line: `176`. ## Source provenance [#source-provenance] Source: `mars-server/src/federation/worker.rs` · SHA-256 `bb16d7061087244544fddbcb4201908bcae30f2ad129ad074e8ad4fd42d71aa8`. [Package overview](/libraries/mars-server). # mars-server · middleware::auth URL: https://docs.mars.glass/libraries/mars-server/middleware/auth Markdown: https://docs.mars.glass/libraries/mars-server/middleware/auth.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::middleware::auth. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `middleware::auth` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## middleware::auth::MutationContext [#middlewareauthmutationcontext] Authenticated, route-scoped idempotency context injected into mutation handlers. No actor identity is sourced from the request body. ```rust #[derive(Debug, Clone)] pub struct MutationContext { pub route: &'static str, pub key: String, pub request_hash: String, pub expires_at: chrono::DateTime } ``` Source line: `30`. ## middleware::auth::MutationContext::entry\_projection\_response [#middlewareauthmutationcontextentry_projection_response] Reserve a response reconstructed from the authoritative entry projection after the transaction assigns its registry sequence. Use only for commands whose successful response body is exactly the committed \[`mars_protocol::MarsEntry`]. ```rust #[must_use] pub fn entry_projection_response(&self, status: u16) -> IdempotencyRequest; ``` Source line: `44`. ## middleware::auth::MutationContext::stored\_response [#middlewareauthmutationcontextstored_response] Reserve the exact serialized status, content type, and body supplied. Use for every response that cannot be reconstructed solely from a committed entry projection. ```rust #[must_use] pub fn stored_response(&self, response: StoredHttpResponse) -> IdempotencyRequest; ``` Source line: `59`. ## middleware::auth::CapabilityRequirement [#middlewareauthcapabilityrequirement] State supplied to one route's capability middleware. ```rust #[derive(Clone)] pub struct CapabilityRequirement { } ``` Source line: `72`. ## middleware::auth::CapabilityRequirement::for\_mutation [#middlewareauthcapabilityrequirementfor_mutation] ```rust pub fn for_mutation( app: Arc, capability: Capability, route: &'static str, action: AuditAction, ) -> Self; ``` Source line: `80`. ## middleware::auth::ReadCapabilityRequirement [#middlewareauthreadcapabilityrequirement] State supplied to capability-protected read middleware. ```rust #[derive(Clone)] pub struct ReadCapabilityRequirement { } ``` Source line: `97`. ## middleware::auth::ReadCapabilityRequirement::new [#middlewareauthreadcapabilityrequirementnew] ```rust pub fn new(app: Arc, capability: Capability) -> Self; ``` Source line: `103`. ## middleware::auth::require\_capability [#middlewareauthrequire_capability] Resolve a session and require one explicit capability. On success the provider-neutral \[`crate::auth::Principal`] is inserted into request extensions. Missing/invalid sessions return MARS-006; valid sessions that lack the route capability return MARS-007. ```rust pub async fn require_capability( State(requirement): State, request: Request, next: Next, ) -> Response; ``` Source line: `113`. ## middleware::auth::require\_read\_capability [#middlewareauthrequire_read_capability] Require a capability for a protected read without imposing mutation idempotency semantics. ```rust pub async fn require_read_capability( State(requirement): State, mut request: Request, next: Next, ) -> Response; ``` Source line: `332`. ## middleware::auth::require\_operator\_capability [#middlewareauthrequire_operator_capability] Backward-compatible operator-read middleware entry point. ```rust pub async fn require_operator_capability( requirement: State, request: Request, next: Next, ) -> Response; ``` Source line: `371`. ## Source provenance [#source-provenance] Source: `mars-server/src/middleware/auth.rs` · SHA-256 `d1251767a7b7198e780cbc4ca86a9de7504daafb9a62f43d240970d00a28e61b`. [Package overview](/libraries/mars-server). # mars-server · store::memory URL: https://docs.mars.glass/libraries/mars-server/store/memory Markdown: https://docs.mars.glass/libraries/mars-server/store/memory.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::store::memory. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `store::memory` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## store::memory::MemoryStore [#storememorymemorystore] In-memory storage backend backed by one transactional state lock. Every mutation validates all uniqueness and CAS preconditions while holding the write lock, then publishes latest state, snapshot, event, audit, idempotency, and outbox records as one indivisible state transition. ```rust pub struct MemoryStore { } ``` Source line: `92`. ## store::memory::MemoryStore::new [#storememorymemorystorenew] Create a new empty in-memory store. ```rust pub fn new() -> Self; ``` Source line: `98`. ## store::memory::MemoryStore::with\_bonds [#storememorymemorystorewith_bonds] Create an in-memory store with registry-local bond metadata. ```rust pub fn with_bonds(bonds: impl IntoIterator) -> Self; ``` Source line: `105`. ## store::memory::MemoryStore::entry\_count [#storememorymemorystoreentry_count] Returns the number of distinct entry DIDs stored. ```rust pub fn entry_count(&self) -> usize; ``` Source line: `116`. ## store::memory::MemoryStore::event\_count [#storememorymemorystoreevent_count] Returns the number of events in the log. ```rust pub fn event_count(&self) -> usize; ``` Source line: `121`. ## Source provenance [#source-provenance] Source: `mars-server/src/store/memory.rs` · SHA-256 `c1daab53a1dc21cb26dd4003a17c016419aa5d902144d25435ed4ac2bd600a6d`. [Package overview](/libraries/mars-server). # mars-server · store::postgres URL: https://docs.mars.glass/libraries/mars-server/store/postgres Markdown: https://docs.mars.glass/libraries/mars-server/store/postgres.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::store::postgres. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `store::postgres` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## Module condition [#module-condition] ```rust #[cfg(feature = "postgres")] ``` ## pub use sqlx\_core::query::query; [#pub-use-sqlx_corequeryquery] ```rust #[cfg(feature = "postgres")] pub use sqlx_core::query::query; ``` Source line: `29`. ## pub use sqlx\_core::query\_scalar::query\_scalar; [#pub-use-sqlx_corequery_scalarquery_scalar] ```rust #[cfg(feature = "postgres")] pub use sqlx_core::query_scalar::query_scalar; ``` Source line: `30`. ## pub use sqlx\_core::row::Row; [#pub-use-sqlx_corerowrow] ```rust #[cfg(feature = "postgres")] pub use sqlx_core::row::Row; ``` Source line: `31`. ## pub use sqlx\_postgres::\{PgPool, Postgres}; [#pub-use-sqlx_postgrespgpool-postgres] ```rust #[cfg(feature = "postgres")] pub use sqlx_postgres::{PgPool, Postgres}; ``` Source line: `32`. ## store::postgres::sqlx::postgres [#storepostgressqlxpostgres] ```rust #[cfg(feature = "postgres")] pub mod postgres; ``` Source line: `34`. ## pub use sqlx\_postgres::PgPoolOptions; [#pub-use-sqlx_postgrespgpooloptions] ```rust #[cfg(feature = "postgres")] pub use sqlx_postgres::PgPoolOptions; ``` Source line: `35`. ## store::postgres::PostgresStore [#storepostgrespostgresstore] PostgreSQL-backed storage for the MARS registry. Thread-safe via `sqlx::PgPool` (connection pool). Sequence allocation and every mutation side record are committed by one PostgreSQL transaction. ```rust #[cfg(feature = "postgres")] pub struct PostgresStore { } ``` Source line: `161`. ## store::postgres::PostgresStore::connect [#storepostgrespostgresstoreconnect] Connect to PostgreSQL and apply migrations. # Arguments [#arguments] * `database_url` — PostgreSQL connection string (e.g. `postgres://user:pass@host/db`) * `config` — Validated pool and PostgreSQL session bounds. ```rust #[cfg(feature = "postgres")] pub async fn connect(database_url: &str, config: C) -> Result where C: Into,; ``` Source line: `172`. ## store::postgres::PostgresStore::connect\_with\_pool [#storepostgrespostgresstoreconnect_with_pool] Construct a store from an existing PostgreSQL pool and apply migrations. This supports schema-scoped integration tests and deployments that own pool configuration outside MARS. ```rust #[cfg(feature = "postgres")] pub async fn connect_with_pool(pool: PgPool) -> Result; ``` Source line: `217`. ## store::postgres::PostgresStore::pool [#storepostgrespostgresstorepool] Get a reference to the underlying connection pool. ```rust #[cfg(feature = "postgres")] pub fn pool(&self) -> &PgPool; ``` Source line: `256`. ## Source provenance [#source-provenance] Source: `mars-server/src/store/postgres.rs` · SHA-256 `d42e295200f8ed04b0365792f65e8af11225d62ccae1627cbff974e5ce327e71`. [Package overview](/libraries/mars-server). # mars-server · store::sharded_memory URL: https://docs.mars.glass/libraries/mars-server/store/sharded_memory Markdown: https://docs.mars.glass/libraries/mars-server/store/sharded_memory.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::store::sharded_memory. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `store::sharded_memory` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## Module condition [#module-condition] ```rust #[cfg(feature = "sharding")] ``` ## store::sharded\_memory::ShardedMemoryStore [#storesharded_memoryshardedmemorystore] In-memory sharded storage that distributes entries across multiple \[`MemoryStore`] instances via consistent hashing. ```rust #[cfg(feature = "sharding")] pub struct ShardedMemoryStore { } ``` Source line: `26`. ## store::sharded\_memory::ShardedMemoryStore::new [#storesharded_memoryshardedmemorystorenew] Create a new sharded memory store. `shard_ids` must have at least one entry. `virtual_nodes_per_shard` controls the number of ring positions per shard (typical: 150). ```rust #[cfg(feature = "sharding")] pub fn new( shard_ids: &[String], virtual_nodes_per_shard: u32, affinity: AffinityFunction, ) -> Self; ``` Source line: `42`. ## store::sharded\_memory::ShardedMemoryStore::put\_entry\_routed [#storesharded_memoryshardedmemorystoreput_entry_routed] Put an entry into the appropriate shard based on affinity routing. ```rust #[cfg(feature = "sharding")] pub async fn put_entry_routed(&self, entry: MarsEntry) -> Result; ``` Source line: `61`. ## store::sharded\_memory::ShardedMemoryStore::get\_store [#storesharded_memoryshardedmemorystoreget_store] Get the per-shard store for direct access. ```rust #[cfg(feature = "sharding")] pub fn get_store(&self, shard_id: &str) -> Option<&Arc>; ``` Source line: `71`. ## store::sharded\_memory::ShardedMemoryStore::total\_entries [#storesharded_memoryshardedmemorystoretotal_entries] Total entries across all shards. ```rust #[cfg(feature = "sharding")] pub fn total_entries(&self) -> usize; ``` Source line: `76`. ## Source provenance [#source-provenance] Source: `mars-server/src/store/sharded_memory.rs` · SHA-256 `1e826c05d48f1ececa5d76854db1b7459499bf98217667a1c952630f0f87fe81`. [Package overview](/libraries/mars-server). # mars-server · validation::resolver URL: https://docs.mars.glass/libraries/mars-server/validation/resolver Markdown: https://docs.mars.glass/libraries/mars-server/validation/resolver.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::validation::resolver. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `validation::resolver` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## validation::resolver::PublisherKeyResolver [#validationresolverpublisherkeyresolver] Resolves an Ed25519 public key for a given `signature.keyId`. The `key_id` is a DID URL of the form `"did:oas:...#fragment"`. The fragment after `#` identifies a specific key under the controller DID. ```rust #[async_trait] pub trait PublisherKeyResolver: Send + Sync { /// Look up the verifying key for `key_id`. /// /// Returns `Ok(None)` if the key is not known to this resolver (callers /// should treat this as "try the next layer" or, at the outermost layer, /// as a signature rejection). Returns `Err` only on resolver failures /// (e.g. backing store IO error). async fn resolve(&self, key_id: &str) -> Result, ResolverError>; } ``` Source line: `33`. ## validation::resolver::ResolverError [#validationresolverresolvererror] Errors that can occur during key resolution. ```rust #[derive(Debug, thiserror::Error)] pub enum ResolverError { /// The backing store returned an error. #[error("store error: {0}")] Store(String), /// The candidate entry's `item_data` does not contain a usable public key. #[error("invalid key material for `{key_id}`: {reason}")] InvalidKeyMaterial { key_id: String, reason: String }, } ``` Source line: `45`. ## validation::resolver::StaticKeyResolver [#validationresolverstatickeyresolver] Resolver backed by an in-memory `key_id → VerifyingKey` map. Used for tests and for explicitly pinning operator-trusted keys at startup. ```rust #[derive(Default, Clone)] pub struct StaticKeyResolver { } ``` Source line: `63`. ## validation::resolver::StaticKeyResolver::new [#validationresolverstatickeyresolvernew] Create an empty resolver. ```rust pub fn new() -> Self; ``` Source line: `69`. ## validation::resolver::StaticKeyResolver::from\_trust\_config [#validationresolverstatickeyresolverfrom_trust_config] Parse all configured publisher and peer pins into the startup resolver. Invalid pins fail startup instead of surfacing per request. ```rust pub fn from_trust_config(trust: &TrustConfig) -> Result; ``` Source line: `75`. ## validation::resolver::StaticKeyResolver::insert [#validationresolverstatickeyresolverinsert] Insert a key. Returns the previously-pinned key, if any. ```rust pub fn insert(&self, key_id: impl Into, key: VerifyingKey) -> Option; ``` Source line: `99`. ## validation::resolver::StaticKeyResolver::remove [#validationresolverstatickeyresolverremove] Remove a key. ```rust pub fn remove(&self, key_id: &str) -> Option; ``` Source line: `104`. ## validation::resolver::StaticKeyResolver::len [#validationresolverstatickeyresolverlen] Current number of pinned keys. ```rust pub fn len(&self) -> usize; ``` Source line: `109`. ## validation::resolver::StaticKeyResolver::is\_empty [#validationresolverstatickeyresolveris_empty] Whether the resolver has no pinned keys. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `114`. ## validation::resolver::StoreBackedKeyResolver [#validationresolverstorebackedkeyresolver] Resolver backed by an \[`EntryStore`]. Given `key_id = "did:oas:hmr:alice#key-1"`, looks up the entry whose `entry_did == "did:oas:hmr:alice"`. If that entry is a `HumanRootRecord` (or other key-bearing record), pulls the verifying key from `item_data.publicKeys[fragment]` (preferred) or `item_data.publicKey` (fallback for single-key records). The expected `item_data` shape is: ```json { "publicKeys": { "key-1": { "type": "Ed25519", "publicKeyHex": "..." } } } ``` Falls back to a top-level `"publicKey"` (hex or base64url) for compatibility with simpler HMR shapes. ```rust pub struct StoreBackedKeyResolver { } ``` Source line: `148`. ## validation::resolver::StoreBackedKeyResolver::new [#validationresolverstorebackedkeyresolvernew] Wrap an entry store. ```rust pub fn new(store: Arc) -> Self; ``` Source line: `154`. ## validation::resolver::LayeredKeyResolver [#validationresolverlayeredkeyresolver] Composes multiple resolvers. First non-`None` hit wins; errors short-circuit. ```rust pub struct LayeredKeyResolver { } ``` Source line: `183`. ## validation::resolver::LayeredKeyResolver::new [#validationresolverlayeredkeyresolvernew] Build a new layered resolver. ```rust pub fn new(layers: Vec>) -> Self; ``` Source line: `189`. ## Source provenance [#source-provenance] Source: `mars-server/src/validation/resolver.rs` · SHA-256 `a24301f4ff1040cd02ac0a750e361791bb073c6d7d570df8a5c225c9718cfb5a`. [Package overview](/libraries/mars-server). # mars-server · auth::adapters URL: https://docs.mars.glass/libraries/mars-server/auth/adapters Markdown: https://docs.mars.glass/libraries/mars-server/auth/adapters.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::auth::adapters. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `auth::adapters` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## auth::adapters::siws [#authadapterssiws] Concrete external authentication adapters. ```rust #[cfg(feature = "sigil")] pub mod siws; ``` Source line: `4`. ## Source provenance [#source-provenance] Source: `mars-server/src/auth/adapters/mod.rs` · SHA-256 `00b39de43a47a90413f5abdea9dc3d36101abda3bfe15c935c38160b59cc79fc`. [Package overview](/libraries/mars-server). # mars-server · auth::challenge_store URL: https://docs.mars.glass/libraries/mars-server/auth/challenge_store Markdown: https://docs.mars.glass/libraries/mars-server/auth/challenge_store.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::auth::challenge_store. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `auth::challenge_store` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## auth::challenge\_store::ChallengeRecord [#authchallenge_storechallengerecord] Provider challenge stored before credential verification. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ChallengeRecord { pub request_id: String, pub scheme: String, pub payload: serde_json::Value, pub issued_at_ms: i64, pub expires_at_ms: i64 } ``` Source line: `25`. ## auth::challenge\_store::AuthChallengeStore [#authchallenge_storeauthchallengestore] Async durable boundary for issue, single-use consume, and cleanup. ```rust #[async_trait] pub trait AuthChallengeStore: Send + Sync { async fn insert(&self, challenge: ChallengeRecord) -> Result<(), AuthError>; /// Atomically consume an unexpired challenge. /// /// `None` covers unknown, already-consumed, and expired records so callers /// reveal no replay oracle. async fn consume( &self, request_id: &str, now_ms: i64, ) -> Result, AuthError>; async fn cleanup(&self, now_ms: i64) -> Result; fn is_durable(&self) -> bool; } ``` Source line: `35`. ## auth::challenge\_store::InMemoryChallengeStore [#authchallenge_storeinmemorychallengestore] Process-local challenge store for tests and explicitly opted-in development. ```rust #[derive(Debug, Default)] pub struct InMemoryChallengeStore { } ``` Source line: `55`. ## auth::challenge\_store::InMemoryChallengeStore::new [#authchallenge_storeinmemorychallengestorenew] ```rust pub fn new() -> Self; ``` Source line: `60`. ## auth::challenge\_store::PostgresChallengeStore [#authchallenge_storepostgreschallengestore] Production PostgreSQL authentication challenge store. ```rust #[cfg(feature = "postgres")] #[derive(Debug, Clone)] pub struct PostgresChallengeStore { } ``` Source line: `113`. ## auth::challenge\_store::PostgresChallengeStore::new [#authchallenge_storepostgreschallengestorenew] ```rust #[cfg(feature = "postgres")] pub fn new(pool: PgPool) -> Self; ``` Source line: `119`. ## Source provenance [#source-provenance] Source: `mars-server/src/auth/challenge_store.rs` · SHA-256 `fc6cb8f3763237c394834f4400a835424077ada942a2969bf92f1c88f5679be2`. [Package overview](/libraries/mars-server). # mars-server · auth::handlers URL: https://docs.mars.glass/libraries/mars-server/auth/handlers Markdown: https://docs.mars.glass/libraries/mars-server/auth/handlers.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::auth::handlers. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `auth::handlers` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## auth::handlers::SESSION\_COOKIE\_NAME [#authhandlerssession_cookie_name] Cookie name used for browser-friendly session storage. ```rust pub const SESSION_COOKIE_NAME: &str; ``` Source line: `31`. ## auth::handlers::siws\_challenge [#authhandlerssiws_challenge] `POST /v1/auth/siws/challenge`. ```rust #[cfg(feature = "sigil")] pub async fn siws_challenge( State(state): State>, Json(request): Json, ) -> Result; ``` Source line: `140`. ## auth::handlers::siws\_verify [#authhandlerssiws_verify] `POST /v1/auth/siws/verify`. ```rust #[cfg(feature = "sigil")] pub async fn siws_verify( State(state): State>, Json(request): Json, ) -> Result; ``` Source line: `220`. ## auth::handlers::logout [#authhandlerslogout] `POST /v1/auth/logout`. ```rust pub async fn logout( State(state): State>, headers: HeaderMap, ) -> Result; ``` Source line: `275`. ## auth::handlers::session [#authhandlerssession] `GET /v1/auth/session`. ```rust pub async fn session( State(state): State>, headers: HeaderMap, ) -> Result; ``` Source line: `298`. ## Source provenance [#source-provenance] Source: `mars-server/src/auth/handlers.rs` · SHA-256 `c91a529555a6aa14e196732040c481c425aeda80c4d1a6875261e854cb1a9c7b`. [Package overview](/libraries/mars-server). # mars-server · auth::principal URL: https://docs.mars.glass/libraries/mars-server/auth/principal Markdown: https://docs.mars.glass/libraries/mars-server/auth/principal.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::auth::principal. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `auth::principal` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## auth::principal::AuthProfile [#authprincipalauthprofile] Stable identifier for an authentication profile registered with MARS. The string-backed representation is deliberate: OpenAgent, Arsenal, and future profiles can be registered without expanding a closed provider enum in the always-on authentication domain. ```rust #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct AuthProfile(String); ``` Source line: `21`. ## auth::principal::AuthProfile::SIWS [#authprincipalauthprofilesiws] Concrete Sign-In-With-Sigil profile implemented by this release. ```rust pub const SIWS: &'static str; ``` Source line: `25`. ## auth::principal::AuthProfile::OPEN\_AGENT [#authprincipalauthprofileopen_agent] Reserved profile name for a future OpenAgent adapter. ```rust pub const OPEN_AGENT: &'static str; ``` Source line: `27`. ## auth::principal::AuthProfile::ARSENAL [#authprincipalauthprofilearsenal] Reserved profile name for a future Arsenal adapter. ```rust pub const ARSENAL: &'static str; ``` Source line: `29`. ## auth::principal::AuthProfile::FEDERATION [#authprincipalauthprofilefederation] MARS-owned signed registry federation profile. ```rust pub const FEDERATION: &'static str; ``` Source line: `31`. ## auth::principal::AuthProfile::parse [#authprincipalauthprofileparse] Construct a profile identifier after validating its stable wire form. ```rust pub fn parse(value: impl Into) -> Result; ``` Source line: `34`. ## auth::principal::AuthProfile::siws [#authprincipalauthprofilesiws-1] Sign-In-With-Sigil profile identifier. ```rust pub fn siws() -> Self; ``` Source line: `47`. ## auth::principal::AuthProfile::open\_agent [#authprincipalauthprofileopen_agent-1] OpenAgent extension profile identifier. ```rust pub fn open_agent() -> Self; ``` Source line: `52`. ## auth::principal::AuthProfile::arsenal [#authprincipalauthprofilearsenal-1] Arsenal extension profile identifier. ```rust pub fn arsenal() -> Self; ``` Source line: `57`. ## auth::principal::AuthProfile::federation [#authprincipalauthprofilefederation-1] Signed MARS registry federation profile. ```rust pub fn federation() -> Self; ``` Source line: `62`. ## auth::principal::AuthProfile::as\_str [#authprincipalauthprofileas_str] Borrow the stable profile identifier. ```rust pub fn as_str(&self) -> &str; ``` Source line: `67`. ## auth::principal::Capability [#authprincipalcapability] MARS authorization capabilities granted to an authenticated principal. ```rust #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Capability { PublishEntry, UpdateEntry, RevokeEntry, TransferOut, TransferAccept, Attest, Report, FederatedDiscovery, FederationSync, Admin, } ``` Source line: `89`. ## auth::principal::Capability::as\_str [#authprincipalcapabilityas_str] Stable database and diagnostic representation. ```rust pub fn as_str(self) -> &'static str; ``` Source line: `104`. ## auth::principal::CapabilitySet [#authprincipalcapabilityset] Closed, deterministic capability collection. ```rust #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct CapabilitySet(BTreeSet); ``` Source line: `151`. ## auth::principal::CapabilitySet::new [#authprincipalcapabilitysetnew] Empty capability set. ```rust pub fn new() -> Self; ``` Source line: `155`. ## auth::principal::CapabilitySet::entry\_publisher [#authprincipalcapabilitysetentry_publisher] Capabilities granted to a normal entry publisher. ```rust pub fn entry_publisher() -> Self; ``` Source line: `160`. ## auth::principal::CapabilitySet::contains [#authprincipalcapabilitysetcontains] Whether the set grants `capability`. ```rust pub fn contains(&self, capability: Capability) -> bool; ``` Source line: `174`. ## auth::principal::CapabilitySet::iter [#authprincipalcapabilitysetiter] Iterate in stable capability order. ```rust pub fn iter(&self) -> impl Iterator + '_; ``` Source line: `179`. ## auth::principal::Principal [#authprincipalprincipal] Provider-neutral authenticated request principal. ```rust #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Principal { /// Durable session identifier used for audit correlation. pub session_id: uuid::Uuid, /// DID that presented and proved the credential. pub subject_did: String, /// DID permitted to author publisher-bound MARS entries. pub publisher_did: String, /// Root authority DID established by the adapter. pub authorization_root_did: String, /// Adapter-defined root classification retained for profile responses. pub authorization_root_kind: String, /// Authentication profile that established this principal. pub profile: AuthProfile, /// Explicit authorization capabilities. pub capabilities: CapabilitySet, /// Session issue time in server-controlled Unix milliseconds. pub issued_at_ms: i64, /// Session expiry in server-controlled Unix milliseconds. pub expires_at_ms: i64 } ``` Source line: `199`. ## auth::principal::Principal::is\_active\_at [#authprincipalprincipalis_active_at] Whether this principal is still active at `now_ms`. ```rust pub fn is_active_at(&self, now_ms: i64) -> bool; ``` Source line: `222`. ## auth::principal::Principal::require [#authprincipalprincipalrequire] Require a capability without consulting any provider-specific state. ```rust pub fn require(&self, capability: Capability) -> Result<(), AuthError>; ``` Source line: `227`. ## auth::principal::Credential [#authprincipalcredential] Provider credential envelope accepted by the adapter registry. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Credential { pub scheme: String, pub payload: serde_json::Value } ``` Source line: `242`. ## auth::principal::Credential::new [#authprincipalcredentialnew] ```rust pub fn new(scheme: impl Into, payload: serde_json::Value) -> Self; ``` Source line: `248`. ## auth::principal::AuthError [#authprincipalautherror] Fail-closed authentication-domain errors. ```rust #[derive(Debug, thiserror::Error)] pub enum AuthError { #[error("authentication scheme `{scheme}` is not registered")] UnknownScheme { scheme: String }, #[error("authentication profile `{profile}` is not enabled")] ProfileDisabled { profile: AuthProfile }, #[error("invalid authentication profile `{profile}`")] InvalidProfile { profile: String }, #[error("invalid capability `{capability}`")] InvalidCapability { capability: String }, #[error("authentication credential rejected: {0}")] CredentialRejected(String), #[error("authentication dependency failed: {0}")] Dependency(String), #[error("authentication storage failed: {0}")] Storage(String), #[error("authentication registry configuration is invalid: {0}")] Registry(String), #[error("principal `{subject_did}` lacks capability `{capability}`")] MissingCapability { capability: Capability, subject_did: String, }, } ``` Source line: `258`. ## Source provenance [#source-provenance] Source: `mars-server/src/auth/principal.rs` · SHA-256 `9f5ba899eab83b43804784be40f717776f24adb68e86366ccc62c37c66e98207`. [Package overview](/libraries/mars-server). # mars-server · auth::registry URL: https://docs.mars.glass/libraries/mars-server/auth/registry Markdown: https://docs.mars.glass/libraries/mars-server/auth/registry.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::auth::registry. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `auth::registry` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## auth::registry::AuthProfileAdapter [#authregistryauthprofileadapter] Provider adapter boundary. Implementations own provider-specific verification and translate successful proofs into the MARS-owned \[`Principal`] model. The always-on auth domain never imports provider types. ```rust #[async_trait] pub trait AuthProfileAdapter: Send + Sync { /// Stable profile enabled by configuration. fn profile(&self) -> AuthProfile; /// Credential scheme routed to this adapter. fn scheme(&self) -> &'static str; /// Verify one provider credential. async fn authenticate(&self, credential: &Credential) -> Result; } ``` Source line: `16`. ## auth::registry::AuthProfileRegistry [#authregistryauthprofileregistry] Immutable-after-startup registry of concrete authentication adapters. ```rust #[derive(Clone, Default)] pub struct AuthProfileRegistry { } ``` Source line: `29`. ## auth::registry::AuthProfileRegistry::new [#authregistryauthprofileregistrynew] ```rust pub fn new() -> Self; ``` Source line: `35`. ## auth::registry::AuthProfileRegistry::register [#authregistryauthprofileregistryregister] Register a concrete adapter. Duplicate schemes and duplicate profile implementations are rejected so adapter selection cannot depend on registration order. ```rust pub fn register(&mut self, adapter: Arc) -> Result<(), AuthError>; ``` Source line: `43`. ## auth::registry::AuthProfileRegistry::authenticate [#authregistryauthprofileregistryauthenticate] Resolve and invoke the adapter selected by `credential.scheme`. ```rust pub async fn authenticate(&self, credential: &Credential) -> Result; ``` Source line: `73`. ## auth::registry::AuthProfileRegistry::profile\_for\_scheme [#authregistryauthprofileregistryprofile_for_scheme] Profile selected by a credential scheme, if registered. ```rust pub fn profile_for_scheme(&self, scheme: &str) -> Option; ``` Source line: `92`. ## auth::registry::AuthProfileRegistry::contains\_profile [#authregistryauthprofileregistrycontains_profile] Whether a concrete adapter is registered for `profile`. ```rust pub fn contains_profile(&self, profile: &AuthProfile) -> bool; ``` Source line: `97`. ## auth::registry::AuthProfileRegistry::registered\_profiles [#authregistryauthprofileregistryregistered_profiles] Registered profile identifiers in deterministic order. ```rust pub fn registered_profiles(&self) -> BTreeSet; ``` Source line: `102`. ## Source provenance [#source-provenance] Source: `mars-server/src/auth/registry.rs` · SHA-256 `50922efc8fe1cf808292da12a2c9028b3f4196bce0a2b9875fb81b3e8d5b50dd`. [Package overview](/libraries/mars-server). # mars-server · auth::session_store URL: https://docs.mars.glass/libraries/mars-server/auth/session_store Markdown: https://docs.mars.glass/libraries/mars-server/auth/session_store.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::auth::session_store. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `auth::session_store` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## auth::session\_store::IssuedSession [#authsession_storeissuedsession] Newly established session. The token is disclosed only in this result. ```rust #[derive(Clone, PartialEq, Eq)] pub struct IssuedSession { pub token: String, pub principal: Principal } ``` Source line: `32`. ## auth::session\_store::SessionStore [#authsession_storesessionstore] Async session persistence boundary used by auth handlers and middleware. ```rust #[async_trait] pub trait SessionStore: Send + Sync { /// Persist a principal under a new cryptographically random bearer token. async fn issue(&self, principal: Principal) -> Result; /// Resolve an active, non-revoked session at server-controlled `now_ms`. async fn lookup(&self, token: &str, now_ms: i64) -> Result, AuthError>; /// Revoke a token immediately. Returns whether an active row was changed. async fn revoke(&self, token: &str, revoked_at_ms: i64) -> Result; /// Delete expired and revoked records. Returns rows removed. async fn cleanup(&self, now_ms: i64) -> Result; /// Whether records survive process restart and replica replacement. fn is_durable(&self) -> bool; } ``` Source line: `49`. ## auth::session\_store::InMemorySessionStore [#authsession_storeinmemorysessionstore] Process-local session store for tests and explicitly opted-in development. Tokens are hashed here too, keeping test/dev semantics aligned with the production persistence contract. ```rust #[derive(Debug, Default)] pub struct InMemorySessionStore { } ``` Source line: `77`. ## auth::session\_store::InMemorySessionStore::new [#authsession_storeinmemorysessionstorenew] ```rust pub fn new() -> Self; ``` Source line: `82`. ## auth::session\_store::PostgresSessionStore [#authsession_storepostgressessionstore] Production PostgreSQL session store. ```rust #[cfg(feature = "postgres")] #[derive(Debug, Clone)] pub struct PostgresSessionStore { } ``` Source line: `157`. ## auth::session\_store::PostgresSessionStore::new [#authsession_storepostgressessionstorenew] ```rust #[cfg(feature = "postgres")] pub fn new(pool: PgPool) -> Self; ``` Source line: `163`. ## Source provenance [#source-provenance] Source: `mars-server/src/auth/session_store.rs` · SHA-256 `39cd9fb562e6ed809c6c80fef102eefba3cc0ddaac69faf233ca534c2bf8043e`. [Package overview](/libraries/mars-server). # mars-server · anchor::config URL: https://docs.mars.glass/libraries/mars-server/anchor/config Markdown: https://docs.mars.glass/libraries/mars-server/anchor/config.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::anchor::config. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `anchor::config` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## anchor::config::AnchorWorkerConfig [#anchorconfiganchorworkerconfig] Runtime policy for one anchor outbox worker replica. ```rust #[derive(Debug, Clone, PartialEq, Eq)] pub struct AnchorWorkerConfig { pub enabled: bool, pub batch_size: u32, pub lease_duration: Duration, pub max_attempts: u32, pub retry_base: Duration, pub retry_max: Duration, /// Additive deterministic jitter in basis points (`0..=10_000`). pub jitter_bps: u16, pub confirmation_poll: Duration } ``` Source line: `10`. ## Source provenance [#source-provenance] Source: `mars-server/src/anchor/config.rs` · SHA-256 `68c2e26c533f1badc43cb25817d244967ba3ca7001840706e212646b6940b72b`. [Package overview](/libraries/mars-server). # mars-server · anchor::sigil URL: https://docs.mars.glass/libraries/mars-server/anchor/sigil Markdown: https://docs.mars.glass/libraries/mars-server/anchor/sigil.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::anchor::sigil. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `anchor::sigil` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## Module condition [#module-condition] ```rust #[cfg(feature = "sigil")] ``` ## anchor::sigil::SigilRuntime [#anchorsigilsigilruntime] Connected Sigil dependencies assembled before MARS binds its listener. ```rust #[cfg(feature = "sigil")] pub struct SigilRuntime { pub client: Arc, pub port: Arc, pub readiness: SigilDeepReadiness } ``` Source line: `23`. ## anchor::sigil::SigilAnchorPort [#anchorsigilsigilanchorport] Concrete Sigil implementation of the MARS-owned \[`AnchorPort`]. ```rust #[cfg(feature = "sigil")] pub struct SigilAnchorPort { } ``` Source line: `30`. ## anchor::sigil::SigilAnchorPort::with\_client [#anchorsigilsigilanchorportwith_client] Assemble an adapter around an already-hardened HTTP client. This constructor supports deterministic conformance harnesses and dependency injection; production startup uses \[`Self::connect`]. ```rust #[cfg(feature = "sigil")] pub fn with_client( client: Arc, transaction: MarsTransactionConfig, signing_key: [u8; 32], finality_timeout: chrono::Duration, mode: SigilSubmissionMode, submissions_enabled: bool, ) -> Result; ``` Source line: `44`. ## anchor::sigil::SigilAnchorPort::connect [#anchorsigilsigilanchorportconnect] Resolve secrets, build the rustls HTTP client, prove deep readiness, and verify that the configured signing key is authorized by chain identity. ```rust #[cfg(feature = "sigil")] pub async fn connect( config: &SigilAnchorConfig, env: DeploymentEnv, ) -> Result; ``` Source line: `72`. ## anchor::sigil::SigilAnchorPort::mode [#anchorsigilsigilanchorportmode] ```rust #[cfg(feature = "sigil")] #[must_use] pub const fn mode(&self) -> SigilSubmissionMode; ``` Source line: `147`. ## anchor::sigil::SigilAnchorPort::live\_submissions\_enabled [#anchorsigilsigilanchorportlive_submissions_enabled] ```rust #[cfg(feature = "sigil")] #[must_use] pub fn live_submissions_enabled(&self) -> bool; ``` Source line: `152`. ## Source provenance [#source-provenance] Source: `mars-server/src/anchor/sigil.rs` · SHA-256 `7f2d528fdb55f6eb04fd1e75b9e62e918ff779724530fa17ed653805c5ce44b2`. [Package overview](/libraries/mars-server). # mars-server · anchor::test_adapter URL: https://docs.mars.glass/libraries/mars-server/anchor/test_adapter Markdown: https://docs.mars.glass/libraries/mars-server/anchor/test_adapter.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::anchor::test_adapter. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `anchor::test_adapter` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## Module condition [#module-condition] ```rust #[cfg(any(test, feature = "test-anchor"))] ``` ## anchor::test\_adapter::DeterministicAnchorPort [#anchortest_adapterdeterministicanchorport] Deterministic, idempotent adapter compiled only for tests or the explicit `test-anchor` feature. It performs no network I/O. ```rust #[cfg(any(test, feature = "test-anchor"))] #[derive(Default)] pub struct DeterministicAnchorPort { } ``` Source line: `14`. ## anchor::test\_adapter::DeterministicAnchorPort::new [#anchortest_adapterdeterministicanchorportnew] ```rust #[cfg(any(test, feature = "test-anchor"))] #[must_use] pub fn new() -> Self; ``` Source line: `20`. ## Source provenance [#source-provenance] Source: `mars-server/src/anchor/test_adapter.rs` · SHA-256 `caf8c8477aadc2f4790764d63ae046b5f7644cc0af4c1d1d4a5d488dd32401d0`. [Package overview](/libraries/mars-server). # mars-protocol · marsql::ast URL: https://docs.mars.glass/libraries/mars-protocol/marsql/ast Markdown: https://docs.mars.glass/libraries/mars-protocol/marsql/ast.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::marsql::ast. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `marsql::ast` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## marsql::ast::MarsQuery [#marsqlastmarsquery] A fully-parsed MARS-QL query. Represents the output of the recursive-descent parser operating on a MARS-QL string. Every clause is optional except the `DISCOVER` keyword and entry type. # Examples [#examples] ``` # use mars_protocol::marsql::ast::*; let q = MarsQuery { entry_type: QueryEntryType::All, conditions: vec![], ordering: vec![], limit: Some(10), offset: None, }; assert!(q.conditions.is_empty()); ``` ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct MarsQuery { /// The entry type to discover. pub entry_type: QueryEntryType, /// Zero or more filter conditions (implicit AND). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub conditions: Vec, /// Zero or more ordering directives. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub ordering: Vec, /// Optional maximum number of results. #[serde(skip_serializing_if = "Option::is_none")] pub limit: Option, /// Optional cursor for keyset pagination. #[serde(skip_serializing_if = "Option::is_none")] pub offset: Option } ``` Source line: `41`. ## marsql::ast::QueryEntryType [#marsqlastqueryentrytype] The target entry type in a `DISCOVER` clause. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(untagged)] pub enum QueryEntryType { /// A specific OAS entry type. Specific(EntryType), /// Wildcard `*` — matches all entry types. All, } ``` Source line: `70`. ## marsql::ast::Condition [#marsqlastcondition] A single filter condition: `field op value`. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct Condition { /// The dotted field path being tested. pub field: FieldPath, /// The filter operation and its operand(s). pub op: FilterOp } ``` Source line: `85`. ## marsql::ast::FieldPath [#marsqlastfieldpath] A dotted field path such as `"royalty_terms.usage_fee"`. Stored as a vector of segments: `["royalty_terms", "usage_fee"]`. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] pub struct FieldPath(pub Vec); ``` Source line: `101`. ## marsql::ast::FieldPath::as\_dotted [#marsqlastfieldpathas_dotted] Returns the full dotted path as a single string. ```rust pub fn as_dotted(&self) -> String; ``` Source line: `105`. ## marsql::ast::FieldPath::len [#marsqlastfieldpathlen] Returns the number of path segments. ```rust pub fn len(&self) -> usize; ``` Source line: `110`. ## marsql::ast::FieldPath::is\_empty [#marsqlastfieldpathis_empty] Returns `true` if the path has no segments. ```rust pub fn is_empty(&self) -> bool; ``` Source line: `115`. ## marsql::ast::FieldPath::root [#marsqlastfieldpathroot] Returns the first segment, if any. ```rust pub fn root(&self) -> Option<&str>; ``` Source line: `120`. ## marsql::ast::FilterOp [#marsqlastfilterop] A filter operation with its operand(s). ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(tag = "op", content = "value", rename_all = "camelCase")] pub enum FilterOp { /// `field = value` Eq(Value), /// `field != value` NotEq(Value), /// `field > value` Gt(Value), /// `field >= value` Gte(Value), /// `field < value` Lt(Value), /// `field <= value` Lte(Value), /// `field CONTAINS value` — set/string membership. Contains(Value), /// `field CONTAINS_ALL (v1, v2, ...)` — all values present. ContainsAll(Vec), /// `field CONTAINS_ANY (v1, v2, ...)` — at least one value present. ContainsAny(Vec), /// `field IN (v1, v2, ...)` — field matches one of the listed values. In(Vec), } ``` Source line: `133`. ## marsql::ast::Value [#marsqlastvalue] A literal value in a MARS-QL expression. ```rust #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(untagged)] pub enum Value { /// A UTF-8 string value (double-quoted in source). String(String), /// A 64-bit integer value. Integer(i64), /// A 64-bit floating-point value. Number(f64), /// A boolean value (`true` / `false`). Boolean(bool), } ``` Source line: `164`. ## marsql::ast::OrderField [#marsqlastorderfield] An ordering directive in an `ORDER BY` clause. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct OrderField { /// The field to order by. pub field: FieldPath, /// Sort direction (ascending or descending). pub direction: SortDirection } ``` Source line: `196`. ## marsql::ast::SortDirection [#marsqlastsortdirection] Sort direction for `ORDER BY` clauses. ```rust #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub enum SortDirection { /// Ascending order (default). #[default] Asc, /// Descending order. Desc, } ``` Source line: `211`. ## marsql::ast::ShardHint [#marsqlastshardhint] Shard placement hints for query routing. When the `sharding` feature is enabled, queries can include hints that restrict evaluation to specific shards, clusters, or regions. ```rust #[cfg(feature = "sharding")] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(tag = "kind", content = "id", rename_all = "camelCase")] pub enum ShardHint { /// Pin query to a specific shard by ID. Shard(String), /// Pin query to all shards in a specific cluster. Cluster(String), /// Pin query to all shards in a specific region. Region(String), } ``` Source line: `231`. ## marsql::ast::ShardedQuery [#marsqlastshardedquery] Extension to \[`MarsQuery`] that carries shard routing hints. ```rust #[cfg(feature = "sharding")] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct ShardedQuery { /// The base MARS-QL query. pub query: MarsQuery, /// Zero or more shard placement hints (implicit OR — entry matches if it /// belongs to *any* hinted shard/cluster/region). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub hints: Vec } ``` Source line: `245`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/marsql/ast.rs` · SHA-256 `c24d9944dad001cb1f4d3f99be569803ffed77428a77f41e2e97794c93ef792e`. [Package overview](/libraries/mars-protocol). # mars-protocol · marsql::evaluator URL: https://docs.mars.glass/libraries/mars-protocol/marsql/evaluator Markdown: https://docs.mars.glass/libraries/mars-protocol/marsql/evaluator.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::marsql::evaluator. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `marsql::evaluator` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## marsql::evaluator::MarsQueryResult [#marsqlevaluatormarsqueryresult] The result of executing a MARS-QL query against a set of entries. ```rust #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "contracts", derive(schemars::JsonSchema, utoipa::ToSchema))] #[serde(rename_all = "camelCase")] pub struct MarsQueryResult { /// The matching entries (after filtering, sorting, and pagination). pub entries: Vec, /// Total number of entries that matched the filter (before pagination). pub total_count: u64, /// Opaque cursor for the next page, if applicable. #[serde(skip_serializing_if = "Option::is_none")] pub cursor: Option, /// Whether more results exist beyond this page. pub has_more: bool } ``` Source line: `21`. ## marsql::evaluator::evaluate\_condition [#marsqlevaluatorevaluate_condition] Evaluate a single condition against a \[`MarsEntry`]. Returns `true` if the entry satisfies the condition. ```rust pub fn evaluate_condition(entry: &MarsEntry, condition: &Condition) -> bool; ``` Source line: `40`. ## marsql::evaluator::matches\_query [#marsqlevaluatormatches_query] Evaluate all conditions of a query against a \[`MarsEntry`] (AND logic). Returns `true` if the entry matches **all** conditions and the entry type matches the query's entry type filter. ```rust pub fn matches_query(entry: &MarsEntry, query: &MarsQuery) -> bool; ``` Source line: `78`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/marsql/evaluator.rs` · SHA-256 `4469a49ac5a125480877b8db7b7ef53df8af92424c1d5520b38cbf7ace2baeb9`. [Package overview](/libraries/mars-protocol). # mars-protocol · marsql::parser URL: https://docs.mars.glass/libraries/mars-protocol/marsql/parser Markdown: https://docs.mars.glass/libraries/mars-protocol/marsql/parser.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-protocol::marsql::parser. **Package:** `mars-protocol` · **Workspace version:** `0.1.0` · **Module:** `marsql::parser` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## marsql::parser::parse [#marsqlparserparse] Parse a MARS-QL query string into a \[`MarsQuery`] AST. # Errors [#errors] Returns \[`MarsError::ValidationError`] with a descriptive message if the input does not conform to the MARS-QL grammar. # Examples [#examples] ``` # use mars_protocol::marsql::parser::parse; let q = parse("DISCOVER AgentDefinition WHERE status = \"active\" LIMIT 10").unwrap(); assert_eq!(q.limit, Some(10)); ``` ```rust pub fn parse(input: &str) -> Result; ``` Source line: `35`. ## marsql::parser::parse\_sharded [#marsqlparserparse_sharded] Parse a MARS-QL query string into a \[`ShardedQuery`] with optional shard placement hints. The grammar extends the base query with trailing hint clauses: ```text sharded_query = query { shard_hint } ; shard_hint = "SHARD" string | "CLUSTER" string | "REGION" string ; ``` # Examples [#examples-1] ``` # use mars_protocol::marsql::parser::parse_sharded; let sq = parse_sharded( r#"DISCOVER AgentDefinition WHERE status = "active" SHARD "shard-01" REGION "us-east""#, ).unwrap(); assert_eq!(sq.hints.len(), 2); ``` ```rust #[cfg(feature = "sharding")] pub fn parse_sharded(input: &str) -> Result; ``` Source line: `68`. ## Source provenance [#source-provenance] Source: `mars-protocol/src/marsql/parser.rs` · SHA-256 `d983f4b5650de1d699869924abdbcaa9e2cc5d31836bb7fd68b49b6ce0ee1c85`. [Package overview](/libraries/mars-protocol). # mars-server · auth::adapters::siws URL: https://docs.mars.glass/libraries/mars-server/auth/adapters/siws Markdown: https://docs.mars.glass/libraries/mars-server/auth/adapters/siws.md Status: reference Source: MARS source inventory at https://docs.mars.glass/coverage.json Public declarations and documentation for mars-server::auth::adapters::siws. **Package:** `mars-server` · **Workspace version:** `0.1.0` · **Module:** `auth::adapters::siws` This reference follows declared modules and public syntax, including public implementation methods. Function bodies and constant values are omitted. Feature conditions are retained. Private-module re-exports and trait resolution require the compiler; not every declaration is a root import. ## Module condition [#module-condition] ```rust #[cfg(feature = "sigil")] ``` ## auth::adapters::siws::SiwsAuthProfileAdapter [#authadapterssiwssiwsauthprofileadapter] Sign-In-With-Sigil adapter backed by MARS challenge persistence and GAL. ```rust #[cfg(feature = "sigil")] pub struct SiwsAuthProfileAdapter { } ``` Source line: `22`. ## auth::adapters::siws::SiwsAuthProfileAdapter::new [#authadapterssiwssiwsauthprofileadapternew] ```rust #[cfg(feature = "sigil")] pub fn new( challenges: Arc, anchor_client: Arc, clock: Arc, session_ttl_ms: i64, ) -> Result; ``` Source line: `30`. ## Source provenance [#source-provenance] Source: `mars-server/src/auth/adapters/siws.rs` · SHA-256 `0f814523580a6274f3d8c50a0651ef2e87ba3c6469fb5cebfe75e0607dddea7d`. [Package overview](/libraries/mars-server).