# ANVIL — Agent Normative Virtualization & Interoperability Layer

## Universal Runtime Standard for Autonomous Agents

**Specification Version:** 1.0.0
**Date:** February 2026
**Status:** Published
**Author:** Jared Rice Sr. — L1fe Labs, Inc. (l1fe.ai | openagent.id | labs@l1fe.ai)
**Domain:** openagent.id
**License:** Creative Commons Attribution 4.0 International (CC BY 4.0)

---

## Abstract

ANVIL defines a vendor-agnostic runtime standard for autonomous agents — the foundational contract specifying how agents execute, how tools bind, how providers register, how health is monitored, how agents collaborate, and how the full lifecycle from instantiation through termination is governed. ANVIL is the surface upon which all agents are forged.

An ANVIL-compliant agent is a portable, self-describing, collaboration-ready unit of autonomous computation. It carries a cryptographic identity (OAS), possesses scoped authorization (Arsenal), reports structured health telemetry, and implements well-defined contracts for participating in multi-agent collaboration — whether running standalone, within a platform-managed organization, or on-chain as a WASM module.

This specification is vendor-agnostic, framework-agnostic, and platform-agnostic. Any party may implement ANVIL-conforming runtimes, and any agent built against the ANVIL contracts is deployable on any ANVIL-conforming host. The reference implementation is Forge, an ANVIL-compliant SDK available in six languages: Rust, TypeScript, Go, Python, Swift, and Kotlin.

ANVIL is a companion standard to OAS (identity), Arsenal (authorization), and AEGIS (infrastructure). Where OAS defines WHO an agent is, Arsenal defines WHAT it is authorized to do, and AEGIS defines HOW its identity is verified, ANVIL defines HOW the agent executes, collaborates, and behaves at runtime.

---

## Table of Contents

1. [Introduction](#1-introduction)
2. [Terminology](#2-terminology)
3. [Architecture Overview](#3-architecture-overview)
4. [Identity Contract](#4-identity-contract)
5. [Capability Contract](#5-capability-contract)
6. [Provider System](#6-provider-system)
7. [Generation Interface](#7-generation-interface)
8. [Tool Contract](#8-tool-contract)
9. [Agent Execution Model](#9-agent-execution-model)
10. [Communication Contract](#10-communication-contract)
11. [Collaboration Contract](#11-collaboration-contract)
12. [Health Contract](#12-health-contract)
13. [Lifecycle Contract](#13-lifecycle-contract)
14. [Telemetry Contract](#14-telemetry-contract)
15. [Security Model](#15-security-model)
16. [Interoperability](#16-interoperability)
17. [Conformance Levels](#17-conformance-levels)
18. [Security Considerations](#18-security-considerations)
19. [Privacy Considerations](#19-privacy-considerations)
20. [References](#20-references)
21. [Appendix A: Interface Schemas](#appendix-a-interface-schemas)
22. [Appendix B: Collaboration Pattern Catalog](#appendix-b-collaboration-pattern-catalog)
23. [Appendix C: Conformance Test Scenarios](#appendix-c-conformance-test-scenarios)
24. [Appendix D: Revision History](#appendix-d-revision-history)

---

## 1. Introduction

### 1.1 Problem Statement

The autonomous agent ecosystem suffers from runtime fragmentation. Every framework — LangChain, CrewAI, AutoGen, custom implementations — defines its own agent lifecycle, tool binding, health monitoring, and collaboration primitives. Agents built for one framework cannot execute on another. There is no portable agent artifact, no universal runtime contract, and no standard mechanism for agents to participate in collaborative work regardless of where they were built.

Three specific gaps prevent interoperable agent execution:

1. **No portable runtime contract.** An agent built for Framework A cannot run on Framework B's runtime. Tool bindings, provider interfaces, lifecycle hooks, and health profiles are framework-specific with no shared standard.

2. **No collaboration contract.** Multi-agent systems exist, but every framework implements collaboration differently. There is no standard interface for an agent to receive delegated tasks, share context with peers, handle interruptions, or participate in structured collaboration patterns. Agents must be purpose-built for their specific orchestration framework.

3. **No identity-native execution.** Existing agent runtimes treat identity as an afterthought — an API key, an environment variable, a configuration parameter. There is no standard requiring that every agent operation carries cryptographic identity context, that every tool invocation is authorized against a capability token, or that every collaboration message is signed by a verified identity.

### 1.2 Design Goals

ANVIL addresses these gaps through the following design goals:

1. **Portable agent artifacts.** An ANVIL-compliant agent module MUST execute on any ANVIL-compliant runtime. The WASM module is the portable artifact; the manifest declares required capabilities.

2. **Eight runtime contracts.** ANVIL defines eight orthogonal contracts that together specify a complete agent: identity, capability, tool, health, communication, collaboration, lifecycle, and telemetry. An agent implementing all eight is fully ANVIL-compliant.

3. **Collaboration by default.** Every ANVIL-compliant agent implements the Collaboration Contract. An agent does not need a special "multi-agent mode" — it is always collaboration-ready. When running standalone, the collaboration interfaces are dormant. When composed into an organization, the platform activates them.

4. **Identity-native execution.** Every agent operation carries identity context. Every tool invocation checks authorization. Every message is signed. Identity is not a feature; it is the substrate.

5. **Vendor agnosticism.** ANVIL does not privilege any LLM provider, framework, platform, blockchain, or runtime implementation. The conformance suite certifies compliance.

6. **WASM/WASI-native.** Every component of an ANVIL-compliant agent MUST compile to `wasm32-wasi`. This enables deployment on any platform: local processes, cloud containers, mobile devices, blockchain WASI execution layers.

### 1.3 Scope

This specification defines:

- The eight runtime contracts (identity, capability, tool, health, communication, collaboration, lifecycle, telemetry)
- The agent execution model (tool loops, delegation, step control)
- The provider system (LLM provider registration, capability declaration, model routing)
- The generation interface (text, structured, streaming)
- The communication interface (messaging, pub/sub, protocol negotiation)
- The collaboration interface (roles, shared context, task delegation, interruption, sessions)
- The health profile and lifecycle state machine
- The telemetry emission model
- The security model (sandbox profiles, resource quotas, audit trails)
- The interoperability model (cross-runtime, cross-language, cross-platform, cross-chain)
- Three conformance levels

This specification does NOT define:

- Specific LLM provider APIs (these are provider-specific implementations)
- Orchestration logic (this is platform-specific — e.g., Aut0, MOON protocol)
- Specific collaboration topologies (these are defined by ODL and deployed by platforms)
- Economic or incentive models (see $SIGIL token specification)
- Blockchain or consensus mechanisms (see MACA specification)

### 1.4 Relationship to Existing Standards

| Standard | Relationship |
|----------|-------------|
| OAS | ANVIL agents carry OAS identities. The Identity Contract wraps OAS primitives. |
| Arsenal | ANVIL agents authorize operations via Arsenal ACTs. The Capability Contract wraps Arsenal primitives. |
| AEGIS | ANVIL runtimes authenticate agents via AEGIS. Identity verification is delegated to AEGIS. |
| OATS | ANVIL health profiles contribute signals to OATS trust scores. |
| Bioagentic | ANVIL telemetry feeds Bioagentic behavioral classification. |
| Fabrics | ANVIL identity context enables Fabrics entity-aware routing. |
| MAP Protocols | ANVIL communication and collaboration interfaces align with MIM, MOON, MANA, MACE protocols. |
| OAS-DL | ADL compiles to ANVIL agent manifests. ODL compiles to collaboration topology configurations. |
| W3C WASI | ANVIL agents compile to WASI components for portable execution. |

---

## 2. Terminology

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [RFC 2119] [RFC 8174].

| Term | Definition |
|------|-----------|
| **ANVIL-Compliant Agent** | An agent module that implements all required interfaces defined in this specification at its declared conformance level. |
| **ANVIL-Compliant Runtime** | A host environment that provides all required host functions and services defined in this specification. |
| **Agent Module** | A WASM binary or native executable that implements the ANVIL agent interfaces. The portable deployment artifact. |
| **Agent Manifest** | A declarative document accompanying an agent module, declaring required capabilities, resource requirements, supported collaboration roles, and conformance level. |
| **Runtime Contract** | A set of interfaces and behavioral requirements that an agent MUST implement. ANVIL defines eight contracts. |
| **Collaboration Session** | A bounded period during which two or more agents interact through the Collaboration Contract interfaces. |
| **Collaboration Role** | The behavioral mode an agent assumes within a collaboration session: Coordinator, Worker, or Peer. |
| **Shared Context** | A typed key-value workspace accessible to all participants in a collaboration session. |
| **Delegated Task** | A structured unit of work assigned to an agent by a coordinator or peer, with defined inputs, expected outputs, and constraints. |
| **Interruption** | A priority override or suspension directive delivered to an agent during execution. |
| **Host Function** | A function provided by the ANVIL-compliant runtime that agent modules call via the WASI interface. |
| **Provider** | An LLM service implementation (e.g., OpenAI, Anthropic, local model) that the agent invokes through the Generation Interface. |

---

## 3. Architecture Overview

### 3.1 Eight Contracts Model

An ANVIL-compliant agent is defined by eight orthogonal contracts:

```
┌─────────────────────────────────────────────────────────┐
│                   ANVIL Agent Runtime                   │
│                                                         │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐    │
│  │ Identity │ │Capability│ │   Tool   │ │  Health  │    │
│  │ Contract │ │ Contract │ │ Contract │ │ Contract │    │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘    │
│                                                         │
│  ┌──────────────────┐ ┌────────────────────────────┐    │
│  │  Communication   │ │     Collaboration          │    │
│  │    Contract      │ │       Contract             │    │
│  └──────────────────┘ └────────────────────────────┘    │
│                                                         │
│  ┌──────────┐ ┌──────────┐                              │
│  │Lifecycle │ │Telemetry │                              │
│  │ Contract │ │ Contract │                              │
│  └──────────┘ └──────────┘                              │
└─────────────────────────────────────────────────────────┘
```

Each contract is independently testable and independently implementable. A conformance suite validates each contract in isolation and in combination.

### 3.2 Layered Architecture

```
┌─────────────────────────────────────────┐
│           Application Layer             │  Agent logic, business rules
├─────────────────────────────────────────┤
│          Collaboration Layer            │  Roles, sessions, shared context
├─────────────────────────────────────────┤
│         Communication Layer             │  Messaging, pub/sub, protocols
├─────────────────────────────────────────┤
│            Execution Layer              │  Tool loops, generation, steps
├─────────────────────────────────────────┤
│           Security Layer                │  Identity, capability, sandbox
├─────────────────────────────────────────┤
│          Runtime Layer (Host)           │  WASI host functions, resource mgmt
└─────────────────────────────────────────┘
```

### 3.3 Component Model

An ANVIL deployment consists of:

| Component | Responsibility | Example |
|-----------|---------------|---------|
| **Agent Module** | Implements the eight contracts | A Forge-built WASM binary |
| **Runtime Host** | Provides host functions, manages resources | Aut0 daemon, Sigil WASI layer |
| **Provider Registry** | Routes generation requests to LLM backends | Forge provider system |
| **Tool Registry** | Discovers and manages available tools | MAT protocol, local registry |
| **Message Transport** | Delivers inter-agent messages | MIM protocol, in-process channels |
| **Context Store** | Backs the shared context interface | In-memory, DHT, on-chain state |
| **Health Aggregator** | Collects and reports health profiles | MOMENT protocol, Prometheus |
| **Telemetry Sink** | Receives telemetry spans and events | MOTIF protocol, OpenTelemetry |

---

## 4. Identity Contract

### 4.1 Requirements

Every ANVIL-compliant agent MUST possess a cryptographic identity conforming to the Open Agent Specification (OAS).

```
interface IdentityContract {
  // Returns the agent's OAS DID
  did() -> OasDid

  // Returns the full OAS Identity Document
  document() -> OasDocument

  // Returns the lineage chain to human root
  lineage() -> LineageChain

  // Sign arbitrary data with the agent's Ed25519 key
  sign(data: bytes) -> Ed25519Signature

  // Verify a signature from another entity
  verify(signer_did: OasDid, data: bytes, signature: Ed25519Signature) -> bool

  // Derive a child identity for sub-agent creation
  derive_child(name: string, kind: EntityKind) -> ChildIdentity
}
```

### 4.2 Identity Lifecycle

1. An agent MUST receive its identity during instantiation, before any other operation.
2. An agent's DID MUST NOT change after instantiation.
3. An agent MUST be able to derive child identities for sub-agents it creates.
4. Child identities MUST include a valid AgentLineageProof2025 linking to the parent.
5. The derivation depth MUST NOT exceed the maximum generation configured by the runtime (default: 16).

### 4.3 Identity Context Propagation

Every operation an agent performs MUST carry identity context:

- Every tool invocation MUST include the invoking agent's DID.
- Every message sent MUST be signed with the agent's Ed25519 key.
- Every generation request SHOULD include the agent's DID for audit purposes.
- Every collaboration session join MUST present the agent's OAS Identity Document.

### 4.4 Identity at Birth

An agent MUST have its identity established before transitioning from `Initializing` to `Ready`. An agent without a valid OAS identity MUST NOT transition to `Ready` and MUST remain in `Initializing` or transition to `Error`.

---

## 5. Capability Contract

### 5.1 Requirements

Every ANVIL-compliant agent MUST operate under a scoped Arsenal Agent Capability Token (ACT).

```
interface CapabilityContract {
  // Returns the agent's current ACT
  capability_token() -> AgentCapabilityToken

  // Check if a specific scope is authorized
  has_scope(scope: string) -> bool

  // Check authorization for a tool invocation
  authorize_tool(tool: Tool) -> Result<(), AuthError>

  // Delegate a subset of capabilities to a child agent
  delegate(child_did: OasDid, scopes: Scope[]) -> AgentCapabilityToken

  // Report capability token expiration
  token_expires_at() -> Timestamp
}
```

### 5.2 Authorization Model

1. An agent MUST NOT invoke any tool without a valid ACT that includes the tool's required scope.
2. An agent MUST NOT delegate capabilities it does not possess. Child capabilities MUST be a strict subset of parent capabilities.
3. An agent MUST handle ACT expiration gracefully — either by requesting renewal from the runtime or by pausing operations that require authorization.
4. An ACT MUST be bound to the agent's OAS DID via proof-of-possession.

### 5.3 Capability-Aware Tool Binding

Tool tiers map to Arsenal scope patterns:

| Tool Tier | Scope Pattern | Authorization |
|-----------|--------------|---------------|
| Tier 1 — Platform | `runtime:platform:*` | Runtime-granted, always available |
| Tier 2 — External | `tools:<tool-id>:invoke` | Requires explicit ACT scope |
| Tier 3 — Embedded | (none) | Executes within agent sandbox, no external scope |

---

## 6. Provider System

### 6.1 Provider Interface

ANVIL defines a universal interface for LLM providers:

```
interface LanguageModelProvider {
  // Provider metadata
  provider_id() -> string
  model_id() -> string
  capabilities() -> ModelCapabilities

  // Synchronous generation
  generate(params: GenerateParams) -> GenerateResult

  // Streaming generation
  stream(params: GenerateParams) -> Stream<StreamChunk>
}
```

### 6.2 Model Capabilities

```
struct ModelCapabilities {
  text_generation: bool
  structured_output: bool
  tool_calling: bool
  vision: bool
  audio: bool
  embedding: bool
  max_context_tokens: u32
  max_output_tokens: u32
}
```

### 6.3 Provider Registration

Providers MUST be registered with the runtime before use. Registration includes:

1. A unique `provider_id` (e.g., `openai`, `anthropic`, `ollama`).
2. Available model identifiers (e.g., `gpt-4o`, `claude-sonnet-4-20250514`).
3. Capability declarations for each model.
4. Authentication credentials (delivered via Arsenal Secret Delivery Protocol).

### 6.4 Provider Agnosticism

The `namespace:implementation` pattern from OAS-DL applies to providers: agent definitions declare intent (e.g., `cognition: openai:gpt-4o`) and the runtime resolves to the appropriate provider. Swapping providers MUST NOT require changes to agent logic.

---

## 7. Generation Interface

### 7.1 Text Generation

```
interface GenerationInterface {
  generate_text(messages: ModelMessage[], options: GenerateOptions) -> GenerateTextResult
  stream_text(messages: ModelMessage[], options: GenerateOptions) -> TextStream
  generate_object<T>(messages: ModelMessage[], schema: Schema<T>, options: GenerateOptions) -> T
  stream_object<T>(messages: ModelMessage[], schema: Schema<T>, options: GenerateOptions) -> ObjectStream<T>
}
```

### 7.2 Message Format

```
struct ModelMessage {
  role: "system" | "user" | "assistant" | "tool"
  content: MessageContent  // text, image, audio, tool_result
}
```

### 7.3 Generation Options

```
struct GenerateOptions {
  temperature: f64?
  max_tokens: u32?
  stop_sequences: string[]?
  tools: ToolDefinition[]?
  tool_choice: ToolChoice?
  output_format: OutputFormat?
}
```

### 7.4 Streaming Contract

Streaming responses MUST emit chunks in a standardized format:

```
enum StreamChunk {
  TextDelta(string)
  ToolCallStart { id: string, name: string }
  ToolCallDelta { id: string, args_delta: string }
  ToolCallEnd { id: string }
  Metadata { usage: TokenUsage }
  Error(StreamError)
  Done
}
```

---

## 8. Tool Contract

### 8.1 Tool Interface

```
interface Tool {
  // Tool metadata
  name() -> string
  description() -> string
  parameters() -> JsonSchema
  tier() -> ToolTier  // Platform, External, Embedded

  // Execution
  execute(args: Value) -> ToolResult
  execute_async(args: Value) -> Future<ToolResult>

  // Authorization requirements
  required_scope() -> string?
  needs_approval() -> bool
}
```

### 8.2 Tool Tier Classification

| Tier | Description | Sandbox | Arsenal Scope | Examples |
|------|-------------|---------|--------------|----------|
| **Tier 1 — Platform** | Provided by the runtime | None | Runtime-granted | Clock, random, environment info |
| **Tier 2 — External** | Interacts with external systems | Network access | Required | API calls, web scraping, database queries |
| **Tier 3 — Embedded** | Runs within agent sandbox | Full sandbox | Not required | Calculations, text processing, data transforms |

### 8.3 Tool Invocation Lifecycle

```
Agent calls tool.execute(args)
       │
       ▼
Runtime checks identity: is agent authenticated?
       │ No → return IdentityRequired error
       │ Yes ↓
       ▼
Runtime checks capability: does ACT include scope for this tool?
       │ No → return CapabilityDenied error
       │ Yes ↓
       ▼
Runtime checks approval: does tool require human approval?
       │ Yes → route to approval handler → wait for approval/denial
       │ No ↓
       ▼
Runtime checks resource quota: within limits?
       │ No → return QuotaExceeded error
       │ Yes ↓
       ▼
Runtime dispatches to appropriate tier:
  Tier 1 → execute in runtime context
  Tier 2 → execute outside sandbox, return result
  Tier 3 → execute within sandbox
       │
       ▼
Return ToolResult to agent
       │
       ▼
Runtime updates health profile (success/failure, latency)
       │
       ▼
Runtime emits telemetry span
```

### 8.4 Tool Discovery

Agents MAY discover available tools at runtime through the Tool Discovery interface:

```
interface ToolDiscovery {
  list_tools(filter: ToolFilter?) -> ToolDescriptor[]
  get_tool(name: string) -> ToolDescriptor?
  register_tool(tool: Tool) -> Result<(), ToolRegistrationError>
  unregister_tool(name: string) -> Result<(), ToolRegistrationError>
}
```

---

## 9. Agent Execution Model

### 9.1 Tool Loop

The fundamental agent execution pattern is the tool loop:

```
FUNCTION tool_loop(agent, input, options):
  messages = [system_prompt, input]
  step_count = 0

  LOOP:
    step_count += 1

    // Check stop conditions
    IF options.stop_when(messages, step_count):
      RETURN extract_result(messages)

    // Check step limit
    IF step_count > options.max_steps:
      RETURN error("max steps exceeded")

    // Run prepare step hook
    prepared = options.prepare_step(messages, step_count)

    // Generate with LLM
    response = agent.generate(prepared.messages, prepared.options)

    // Process tool calls
    IF response.has_tool_calls():
      FOR tool_call IN response.tool_calls:
        result = agent.execute_tool(tool_call)
        messages.append(tool_result_message(tool_call, result))
      CONTINUE

    // No tool calls — generation complete
    messages.append(assistant_message(response))
    RETURN extract_result(messages)
```

### 9.2 Stop Conditions

```
interface StopWhen {
  // Evaluate whether the agent should stop
  should_stop(messages: ModelMessage[], step_count: u32) -> bool
}
```

Built-in stop conditions:

| Condition | Description |
|-----------|-------------|
| `StopWhen::TextGenerated` | Stop when the model produces text without tool calls |
| `StopWhen::MaxSteps(n)` | Stop after n steps |
| `StopWhen::ToolCalled(name)` | Stop when a specific tool is called |
| `StopWhen::Custom(fn)` | User-defined stop condition |

### 9.3 Sub-Agent Delegation

An agent MAY delegate work to sub-agents it creates:

```
FUNCTION delegate_to_subagent(parent, task, config):
  // 1. Derive child identity from parent
  child_identity = parent.identity.derive_child(config.name, EntityKind::Agent)

  // 2. Create scoped capability token
  child_act = parent.capability.delegate(child_identity.did, config.scopes)

  // 3. Instantiate sub-agent
  child = runtime.instantiate(config.module, child_identity, child_act)

  // 4. Execute task
  result = child.run(task)

  // 5. Terminate sub-agent
  runtime.terminate(child)

  RETURN result
```

### 9.4 Multi-Agent Patterns

ANVIL recognizes the following execution patterns, implementable through the Collaboration Contract (Section 11):

| Pattern | Description | Coordination |
|---------|-------------|-------------|
| **Sequential Pipeline** | Agent A → Agent B → Agent C | Output of each feeds into next |
| **Fan-Out / Fan-In** | Coordinator → N workers → Aggregator | Parallel dispatch, result aggregation |
| **Debate** | N agents argue, judge evaluates | Adversarial argumentation |
| **Consensus** | N agents vote on outcome | Majority or threshold agreement |
| **Hierarchical Delegation** | Manager delegates to team leads, who delegate to workers | Multi-level task decomposition |
| **Blackboard** | All agents read/write shared state | Asynchronous contribution |

---

## 10. Communication Contract

### 10.1 Requirements

Every ANVIL-compliant agent MUST implement the Communication Contract, enabling structured inter-agent messaging.

```
interface CommunicationContract {
  // Direct messaging
  send(recipient: AgentDID, message: AgentMessage) -> SendResult
  receive() -> AgentMessage?

  // Publish/subscribe
  broadcast(topic: string, message: AgentMessage) -> SendResult
  subscribe(topic: string) -> SubscriptionHandle
  unsubscribe(handle: SubscriptionHandle) -> ()

  // Protocol negotiation
  offer_protocol(recipient: AgentDID, protocols: ProtocolOffer[]) -> ProtocolAccept
  accept_protocol(offer: ProtocolOffer) -> ProtocolAccept
}
```

### 10.2 Message Envelope

All inter-agent messages MUST use a standard envelope:

```
struct AgentMessage {
  id: UUID
  from: AgentDID
  to: AgentDID | Topic
  timestamp: Timestamp
  protocol: string          // e.g., "anvil.collaboration", "marc", "mana"
  message_type: string      // e.g., "task.delegate", "context.update", "interrupt"
  payload: Value            // Protocol-specific payload
  correlation_id: UUID?     // Links related messages
  reply_to: UUID?           // References a previous message
  signature: Ed25519Signature  // Agent's signature over envelope
}
```

### 10.3 Signature Requirements

1. All messages MUST be signed with the sending agent's Ed25519 key.
2. Recipients MUST verify the signature before processing.
3. Messages with invalid signatures MUST be rejected.
4. The signature covers the canonical serialization (JCS) of all fields except `signature`.

### 10.4 Transport Agnosticism

The Communication Contract defines the interface, not the transport. Implementations MAY use:

| Transport | Context | Example |
|-----------|---------|---------|
| In-process channels | Same process, same runtime | Rust `mpsc`, Go channels |
| MIM Protocol | Distributed, cross-process | MAP mesh messaging |
| WebSocket | Real-time, client-server | Aut0 daemon to remote agents |
| On-chain messages | Sigil blockchain | Cross-organization zone messaging |

The runtime MUST provide at least one transport. The agent MUST NOT depend on a specific transport.

### 10.5 Protocol Negotiation

Before sustained interaction, agents negotiate communication protocols:

1. Agent A sends a `ProtocolOffer` listing supported protocols and versions.
2. Agent B responds with a `ProtocolAccept` selecting a common protocol.
3. Both agents switch to the negotiated protocol for subsequent messages.
4. If no common protocol exists, the negotiation fails with `ProtocolMismatch`.

---

## 11. Collaboration Contract

### 11.1 Purpose

The Collaboration Contract defines the agent-side interface for participating in multi-agent work. It does not define orchestration logic — that is the responsibility of the platform (e.g., Aut0) or protocol (e.g., MOON). The Collaboration Contract specifies what an agent MUST implement to be a well-behaved participant in any collaboration pattern.

An agent does not need to know whether it is running standalone or in a fifty-agent organization with six departments. It implements the same interfaces. The environment determines whether collaboration is active.

### 11.2 Collaboration Roles

Every ANVIL-compliant agent declares which collaboration roles it supports in its Agent Manifest. An agent MAY support multiple roles.

```
enum CollaborationRole {
  // Coordinates work across multiple agents
  // Decomposes tasks, assigns work, aggregates results
  Coordinator

  // Receives delegated tasks and produces results
  // Executes assigned work within defined constraints
  Worker

  // Collaborates with equals on shared objectives
  // Contributes to shared context, participates in decisions
  Peer
}
```

#### 11.2.1 Coordinator Role Contract

An agent supporting the `Coordinator` role MUST implement:

```
interface CoordinatorContract {
  // Decompose a high-level task into sub-tasks for delegation
  decompose_task(task: Task) -> TaskDecomposition

  // Assign a sub-task to a specific agent
  assign_task(agent: AgentDID, task: DelegatedTask) -> AssignmentResult

  // Collect and aggregate results from workers
  aggregate_results(results: TaskResult[]) -> AggregatedResult

  // Handle worker failure (reassign, retry, degrade)
  handle_worker_failure(agent: AgentDID, failure: TaskFailure) -> RecoveryAction
}
```

#### 11.2.2 Worker Role Contract

An agent supporting the `Worker` role MUST implement:

```
interface WorkerContract {
  // Receive and acknowledge a delegated task
  on_task_delegated(task: DelegatedTask) -> TaskAcknowledgment

  // Report progress on an assigned task
  report_progress(task_id: TaskId, progress: TaskProgress) -> ()

  // Submit completed task result
  submit_result(task_id: TaskId, result: TaskResult) -> ()

  // Handle task cancellation
  on_task_cancelled(task_id: TaskId, reason: CancellationReason) -> ()
}
```

#### 11.2.3 Peer Role Contract

An agent supporting the `Peer` role MUST implement:

```
interface PeerContract {
  // Propose a contribution to shared work
  propose(proposal: Proposal) -> ProposalId

  // Vote on a peer's proposal
  vote(proposal_id: ProposalId, vote: Vote) -> ()

  // Receive notification of consensus outcome
  on_consensus(proposal_id: ProposalId, outcome: ConsensusOutcome) -> ()
}
```

### 11.3 Collaboration Interface

Every ANVIL-compliant agent MUST implement the core Collaboration Interface, regardless of which roles it supports:

```
interface CollaborationContract {
  // === Session Lifecycle ===

  // Join a collaboration session
  on_session_join(session: CollaborationSession) -> JoinAcknowledgment

  // Handle session state transitions
  on_session_transition(transition: SessionTransition) -> ()

  // Leave a collaboration session
  on_session_leave(session_id: SessionId, reason: LeaveReason) -> ()


  // === Shared Context ===

  // Read a value from shared context
  context_read(key: string) -> ContextEntry?

  // Write a value to shared context
  context_write(key: string, value: ContextEntry) -> WriteResult

  // Subscribe to context changes
  context_subscribe(key_pattern: string) -> ContextSubscription

  // Handle notification of context change by another agent
  on_context_updated(key: string, value: ContextEntry, author: AgentDID) -> ()


  // === Task Delegation ===

  // Receive a delegated task (Worker/Peer role)
  on_task_delegated(task: DelegatedTask) -> TaskAcknowledgment

  // Delegate a task to another agent (Coordinator/Peer role)
  delegate_task(recipient: AgentDID, task: DelegatedTask) -> DelegationResult


  // === Interruption Handling ===

  // Handle an interruption (priority override, suspension, new directive)
  on_interrupt(interrupt: Interrupt) -> InterruptResponse

  // Handle a preemption (forced stop of current work)
  on_preempt(preemption: Preemption) -> PreemptionResponse


  // === Capability Advertisement ===

  // Declare what this agent can do
  advertise_capabilities() -> AgentCapabilityProfile

  // Query whether this agent can handle a specific task type
  can_handle(task_type: string, requirements: TaskRequirements) -> bool
}
```

### 11.4 Collaboration Session

A Collaboration Session is the bounded context within which agents interact:

```
struct CollaborationSession {
  session_id: SessionId
  session_type: SessionType        // Pipeline, FanOut, Debate, Consensus, Hierarchical, Blackboard
  participants: SessionParticipant[]
  coordinator: AgentDID?           // Present if session has a coordinator
  shared_context_id: ContextId     // Reference to shared context store
  created_at: Timestamp
  timeout: Duration?               // Maximum session duration
  metadata: Value                  // Session-specific configuration
}

struct SessionParticipant {
  agent_did: AgentDID
  role: CollaborationRole
  joined_at: Timestamp
  status: ParticipantStatus        // Active, Suspended, Completed, Failed
}
```

#### 11.4.1 Session Lifecycle States

```
                    ┌──────────┐
                    │ Proposed │
                    └────┬─────┘
                         │ all participants accept
                         ▼
                    ┌──────────┐
              ┌─────│  Active  │─────┐
              │     └────┬─────┘     │
              │          │           │
         timeout    all work    coordinator
         expires    complete    dissolves
              │          │           │
              ▼          ▼           ▼
         ┌────────┐ ┌──────────┐ ┌───────────┐
         │TimedOut│ │Completing│ │ Dissolved │
         └────────┘ └────┬─────┘ └───────────┘
                         │
                    final aggregation
                         │
                         ▼
                    ┌──────────┐
                    │Completed │
                    └──────────┘
```

Valid transitions:

| From | To | Trigger |
|------|----|---------|
| Proposed | Active | All required participants accept |
| Proposed | Dissolved | Timeout or coordinator cancels |
| Active | Completing | All tasks completed, entering aggregation |
| Active | TimedOut | Session timeout exceeded |
| Active | Dissolved | Coordinator dissolves session |
| Completing | Completed | Aggregation finished, results distributed |

### 11.5 Shared Context

The Shared Context provides a typed key-value workspace for collaboration:

```
struct ContextEntry {
  key: string
  value: Value                   // Typed payload
  value_type: string             // Schema identifier for the value
  author: AgentDID               // Who wrote this entry
  version: u64                   // Monotonically increasing version
  timestamp: Timestamp
  visibility: ContextVisibility  // Session, Role, Agent
}

enum ContextVisibility {
  Session    // Visible to all session participants
  Role(CollaborationRole)  // Visible only to agents in this role
  Agent(AgentDID)  // Visible only to a specific agent
}
```

#### 11.5.1 Context Conflict Resolution

When multiple agents write to the same key:

1. **Last-Writer-Wins** is the default strategy. The entry with the highest `version` wins.
2. Agents MAY implement **Merge Functions** for specific key types, registered during session creation.
3. The runtime MUST guarantee that `version` is monotonically increasing per key.
4. The runtime MUST notify all subscribed agents when a context entry changes.

#### 11.5.2 Context Transport

The Shared Context interface is transport-agnostic. Implementations MAY back it with:

| Backend | Context | Characteristics |
|---------|---------|----------------|
| In-memory map | Same process | Fastest, no persistence |
| Distributed cache | Cross-process | Low latency, eventual consistency |
| MIM messages | Cross-network | MAP-native, signed entries |
| On-chain state | Sigil blockchain | Deterministic, persistent, verifiable |

### 11.6 Task Delegation

The Task Delegation system provides structured work assignment beyond simple message passing:

```
struct DelegatedTask {
  task_id: TaskId
  task_type: string              // Semantic type (e.g., "research", "analyze", "write")
  description: string            // Human-readable description
  input: Value                   // Typed input data
  output_schema: JsonSchema      // Expected output format
  constraints: TaskConstraints
  delegator: AgentDID            // Who assigned this task
  priority: TaskPriority         // Critical, High, Normal, Low
  deadline: Timestamp?           // When the result is needed
  context_keys: string[]         // Shared context keys relevant to this task
}

struct TaskConstraints {
  max_steps: u32?               // Maximum tool loop iterations
  max_tokens: u32?              // Maximum LLM tokens
  max_duration: Duration?       // Maximum wall clock time
  allowed_tools: string[]?      // Whitelist of tools the worker may use
  required_confidence: f64?     // Minimum confidence in result
}

struct TaskResult {
  task_id: TaskId
  status: TaskStatus            // Completed, Failed, Partial
  output: Value                 // Result data conforming to output_schema
  confidence: f64?              // Agent's confidence in the result (0.0-1.0)
  metadata: TaskResultMetadata  // Steps taken, tokens used, time elapsed
  signature: Ed25519Signature   // Worker's signature over the result
}

enum TaskStatus {
  Completed    // Task finished successfully
  Failed       // Task could not be completed
  Partial      // Task partially completed (some output available)
}
```

#### 11.6.1 Delegation Protocol

```
Coordinator                          Worker
    │                                   │
    │──── DelegatedTask ───────────────>│
    │                                   │
    │<─── TaskAcknowledgment ────────── │
    │     (accepted / rejected)         │
    │                                   │
    │<─── TaskProgress (optional) ───── │  (periodic updates)
    │                                   │
    │<─── TaskProgress (optional) ───── │
    │                                   │
    │<─── TaskResult ────────────────── │
    │     (completed / failed / partial)│
    │                                   │
```

#### 11.6.2 Task Acknowledgment

When a task is delegated, the worker MUST respond with an acknowledgment:

```
struct TaskAcknowledgment {
  task_id: TaskId
  accepted: bool
  rejection_reason: string?      // If rejected: "capability_mismatch", "overloaded", "unauthorized"
  estimated_completion: Duration? // If accepted: estimated time to completion
}
```

An agent MUST reject a task if:
- It does not support the task's `task_type`.
- It does not have the required capabilities (tools, scopes) for the task.
- It is in a lifecycle state that prevents new work (Paused, Error, Terminated).

### 11.7 Interruption Handling

Agents MUST handle interruptions — directives that override or suspend current work:

```
struct Interrupt {
  interrupt_id: InterruptId
  interrupt_type: InterruptType
  source: AgentDID              // Who sent the interrupt (coordinator, human, system)
  priority: InterruptPriority   // Override, Urgent, Normal
  payload: Value                // Type-specific payload
  timestamp: Timestamp
}

enum InterruptType {
  // New higher-priority task — suspend current work, handle this first
  PriorityOverride { new_task: DelegatedTask }

  // Suspend current work indefinitely
  Suspend { reason: string }

  // Resume previously suspended work
  Resume { task_id: TaskId }

  // Abort current work entirely
  Abort { task_id: TaskId, reason: string }

  // New directive from coordinator — adjust approach
  Redirect { task_id: TaskId, new_instructions: string }

  // Human interjection — human-in-the-loop input
  HumanInterjection { message: string, require_acknowledgment: bool }
}

struct InterruptResponse {
  interrupt_id: InterruptId
  acknowledged: bool
  current_state: InterruptedState  // What was the agent doing when interrupted?
  checkpoint: Value?               // Serialized state for potential resume
}

struct InterruptedState {
  task_id: TaskId?
  step_count: u32
  progress_percentage: f64?
  can_resume: bool                 // Whether the interrupted work can be resumed
}
```

#### 11.7.1 Interrupt Processing Rules

1. `PriorityOverride` and `Abort` interrupts MUST be processed immediately — the agent MUST suspend or terminate current work before handling the interrupt.
2. `Suspend` interrupts MUST cause the agent to checkpoint its state (if possible) and transition to the `Paused` lifecycle state.
3. `Resume` interrupts MUST restore the agent from its checkpoint and continue execution.
4. `HumanInterjection` interrupts MUST be surfaced to the agent's reasoning loop as high-priority context.
5. If an agent cannot checkpoint its state for a `Suspend`, it MUST report `can_resume: false` in the `InterruptResponse`.

### 11.8 Capability Advertisement

Agents advertise their capabilities so coordinators and platforms can make informed assignment decisions:

```
struct AgentCapabilityProfile {
  agent_did: AgentDID
  supported_roles: CollaborationRole[]
  supported_task_types: string[]       // e.g., ["research", "code.write", "data.analyze"]
  available_tools: string[]            // Tool names the agent has access to
  provider_capabilities: ModelCapabilities  // What the underlying LLM can do
  current_load: LoadMetrics            // How busy the agent currently is
  max_concurrent_tasks: u32            // How many tasks the agent can handle simultaneously
}
```

---

## 12. Health Contract

### 12.1 Health Profile

Every ANVIL-compliant agent MUST maintain and report a Health Profile:

```
struct HealthProfile {
  agent_did: AgentDID
  lifecycle_state: LifecycleState
  cpu_usage_percent: f64
  memory_usage_bytes: u64
  error_rate: f64              // errors / total invocations
  avg_latency_ms: f64
  tool_success_rate: f64       // successful / total tool calls
  generation_success_rate: f64 // successful / total LLM calls
  uptime_seconds: u64
  active_tasks: u32            // Currently executing tasks
  completed_tasks: u64         // Total completed since instantiation
  last_updated: Timestamp
}
```

### 12.2 Health Status Derivation

```
enum HealthStatus {
  Healthy     // All metrics within normal range
  Degraded    // Some metrics outside normal range but agent is functional
  Critical    // Agent is at risk of failure
}
```

Derivation rules:

| Condition | Status |
|-----------|--------|
| error_rate < 0.05 AND avg_latency_ms < threshold AND tool_success_rate > 0.95 | Healthy |
| error_rate < 0.20 AND tool_success_rate > 0.80 | Degraded |
| error_rate >= 0.20 OR tool_success_rate <= 0.80 OR lifecycle_state == Error | Critical |

### 12.3 Health Reporting

1. The runtime MUST collect health metrics automatically — developers MUST NOT be required to update health profiles manually.
2. Health profiles MUST be queryable by the runtime, platform, and authorized external systems.
3. Health profiles SHOULD be reported to the platform's health aggregator (e.g., MOMENT protocol) at regular intervals (RECOMMENDED: every 30 seconds).

---

## 13. Lifecycle Contract

### 13.1 Lifecycle State Machine

Every ANVIL-compliant agent MUST implement the following lifecycle state machine:

```
                    ┌──────────────┐
                    │ Initializing │
                    └──────┬───────┘
                           │ identity + capabilities resolved
                           ▼
                    ┌──────────────┐
              ┌────>│    Ready     │<────┐
              │     └──────┬───────┘     │
              │            │ run()       │
              │            ▼             │
              │     ┌──────────────┐     │
              │     │   Running    │─────┘ step complete, no more work
              │     └──┬───┬───┬───┘
              │        │   │   │
              │   pause│   │   │error
              │        ▼   │   ▼
              │  ┌────────┐│ ┌───────┐
              │  │ Paused ││ │ Error │
              │  └───┬────┘│ └───┬───┘
              │      │     │     │
              │  resume    │  recovered
              │      │     │     │
              └──────┘     │     │
                           └──┬──┘
                              │ terminate
                              ▼
                       ┌──────────────┐
                       │  Terminated  │
                       └──────────────┘
```

### 13.2 Valid Transitions

| From | To | Trigger | Requirements |
|------|----|---------|-------------|
| Initializing | Ready | Identity and capabilities resolved | Valid OAS DID, valid ACT |
| Initializing | Error | Initialization failure | — |
| Initializing | Terminated | Fatal initialization failure | — |
| Ready | Running | `run()` invoked | — |
| Ready | Terminated | Explicit termination | — |
| Running | Ready | Step complete, no pending work | — |
| Running | Paused | Suspend interrupt or explicit pause | Checkpoint state if possible |
| Running | Error | Recoverable error | — |
| Running | Terminated | Fatal error or explicit termination | — |
| Paused | Running | Resume interrupt or explicit resume | Restore from checkpoint |
| Paused | Terminated | Explicit termination | — |
| Error | Ready | Recovery successful | — |
| Error | Terminated | Recovery failed or explicit termination | — |

### 13.3 Lifecycle Hooks

Agents MAY implement lifecycle hooks that the runtime calls at state transitions:

```
interface LifecycleHooks {
  on_initialize() -> Result<(), InitError>
  on_ready() -> ()
  on_start() -> ()
  on_pause(reason: string) -> Checkpoint?
  on_resume(checkpoint: Checkpoint?) -> ()
  on_error(error: AgentError) -> RecoveryAction
  on_terminate(reason: string) -> ()
}
```

---

## 14. Telemetry Contract

### 14.1 Telemetry Model

ANVIL defines an OpenTelemetry-compatible telemetry model:

```
struct TelemetrySpan {
  trace_id: TraceId
  span_id: SpanId
  parent_span_id: SpanId?
  operation_name: string
  start_time: Timestamp
  end_time: Timestamp?
  status: SpanStatus
  attributes: Map<string, Value>
  events: SpanEvent[]
  agent_did: AgentDID           // OAS identity context
}
```

### 14.2 Required Spans

ANVIL-compliant agents MUST emit spans for:

| Operation | Span Name | Required Attributes |
|-----------|-----------|-------------------|
| Generation | `anvil.generate` | `provider`, `model`, `tokens.input`, `tokens.output` |
| Tool invocation | `anvil.tool.invoke` | `tool.name`, `tool.tier`, `duration_ms` |
| Task delegation | `anvil.task.delegate` | `task.id`, `task.type`, `delegatee` |
| Task execution | `anvil.task.execute` | `task.id`, `task.type`, `steps` |
| Collaboration session | `anvil.session` | `session.id`, `session.type`, `participants` |
| Lifecycle transition | `anvil.lifecycle` | `from_state`, `to_state`, `reason` |
| Message send | `anvil.message.send` | `recipient`, `protocol`, `message_type` |

### 14.3 Audit Trail

The runtime MUST maintain an audit trail of security-sensitive operations:

| Event | Data Recorded |
|-------|---------------|
| Agent instantiation | OAS DID, module hash, capabilities loaded, sandbox profile |
| Capability check | Capability requested, granted/denied, ACT reference |
| Tool invocation | Tool ID, tier, parameters (redacted), result status |
| Network access | Domain, method, status code, bytes transferred |
| Inter-agent message | Sender DID, recipient DID, protocol, message type |
| Lifecycle transition | From state, to state, reason |
| Collaboration session join/leave | Session ID, role, participants |
| Task delegation | Task ID, delegator DID, worker DID, task type |
| Interrupt received | Interrupt type, source, current state |
| Context write | Key, author DID, version, visibility |
| Resource quota event | Quota type, current usage, limit, action taken |

Audit entries MUST be signed by the runtime's Ed25519 key and timestamped.

---

## 15. Security Model

### 15.1 Sandbox Profiles

ANVIL defines sandbox profiles controlling agent resource access:

```
struct SandboxProfile {
  network_access: NetworkPolicy     // Allowed domains, ports, protocols
  filesystem_access: FilesystemPolicy // Read/write paths, size limits
  memory_limit: u64                 // Maximum memory in bytes
  cpu_limit: f64                    // CPU time fraction (0.0-1.0)
  execution_timeout: Duration       // Maximum wall-clock time per invocation
  max_concurrent_tools: u32         // Maximum simultaneous tool executions
  max_sub_agents: u32               // Maximum child agents
}
```

### 15.2 Resource Quotas

Runtimes MUST enforce resource quotas per agent:

| Resource | Quota Type | Default |
|----------|-----------|---------|
| Memory | Hard limit | 256 MB |
| CPU time | Soft limit | 50% of available |
| Network bandwidth | Rate limit | 10 MB/s |
| Tool invocations | Count per minute | 100 |
| LLM tokens | Count per session | Configurable |
| Sub-agents | Count | 16 |
| Context entries | Count per session | 1000 |

### 15.3 Secret Handling

Secrets (API keys, database credentials, cryptographic keys) are handled via Arsenal's Secret Delivery Protocol:

1. Secrets are encrypted with the agent's X25519 public key (hybrid encryption).
2. Only the intended agent can decrypt (proof-of-possession via Ed25519 key).
3. Secrets are stored in the runtime's secure memory (not in WASM linear memory).
4. Agents access secrets via host functions that return decrypted values.
5. Secrets MUST NOT be serialized to persistent storage in plaintext.
6. Secrets MUST be zeroized from memory after use.

---

## 16. Interoperability

### 16.1 Cross-Runtime Portability

An ANVIL-compliant agent module MUST execute on any ANVIL-compliant runtime:

- The WASM module is the portable artifact.
- The manifest declares required capabilities and resource requirements.
- Any runtime that provides the required host functions can execute the module.

### 16.2 Cross-Language Bindings

ANVIL interface contracts are defined in language-neutral terms. Forge provides reference bindings for six languages:

| Language | Package | Status |
|----------|---------|--------|
| Rust | `forge-rs` | Reference implementation |
| TypeScript | `@forge/sdk` | Full implementation |
| Go | `forge-go` | Full implementation |
| Python | `forge-py` | Full implementation |
| Swift | `ForgeSDK` | Full implementation |
| Kotlin | `forge-kt` | Full implementation |

All language bindings compile to `wasm32-wasi` and produce ANVIL-compliant modules.

### 16.3 Cross-Platform Deployment

ANVIL modules deploy to any platform that provides an ANVIL-compliant runtime:

| Platform | Runtime Provider | Notes |
|----------|-----------------|-------|
| Linux/macOS/Windows | Forge CLI | Development and production |
| Docker/Kubernetes | Forge container runtime | Cloud deployment |
| Sigil blockchain | Sigil WASI execution layer | On-chain deployment |
| iOS/Android | Forge mobile runtime | Mobile agent deployment |
| Embedded | Forge embedded runtime | IoT/edge deployment |
| Aut0 Platform | Aut0 daemon | Managed organizational deployment |

### 16.4 Cross-Chain Execution

ANVIL modules deployed on Sigil can interact with off-chain ANVIL agents:

1. On-chain agent sends a message to an off-chain agent via MARS discovery.
2. The off-chain runtime receives the message via MIM transport.
3. The off-chain agent processes and responds.
4. The response is delivered back to the on-chain agent.

Identity verification (OAS) and authorization (Arsenal) work identically in both directions.

---

## 17. Conformance Levels

### 17.1 Level 0 — Basic Runtime

An agent claiming ANVIL L0 conformance MUST implement:

| Contract | Requirement |
|----------|-------------|
| Identity | Valid OAS DID (may be self-issued) |
| Capability | Basic scope checking (ACT optional) |
| Tool | Tool interface with tier classification |
| Health | Health profile with lifecycle state |
| Communication | Send/receive messages |
| Collaboration | `on_task_delegated`, `on_interrupt` (minimal) |
| Lifecycle | Full state machine |
| Telemetry | Generation and tool invocation spans |

### 17.2 Level 1 — Accountable Runtime

An agent claiming ANVIL L1 conformance MUST implement everything in L0 plus:

| Contract | Requirement |
|----------|-------------|
| Identity | Verified OAS lineage to human root |
| Capability | Arsenal ACT with proof-of-possession |
| Collaboration | Full Collaboration Contract (all roles, shared context, sessions) |
| Telemetry | Full audit trail with signed entries |

### 17.3 Level 2 — Full Runtime

An agent claiming ANVIL L2 conformance MUST implement everything in L1 plus:

| Contract | Requirement |
|----------|-------------|
| Identity | Sigil-anchored OAS identity |
| Capability | Lineage-aware authorization policies |
| Collaboration | Checkpoint/resume, capability advertisement |
| WASM | Complete `wasm32-wasi` compilation, deterministic execution |
| Telemetry | On-chain audit anchoring |

---

## 18. Security Considerations

1. **Identity spoofing.** Agents MUST verify message signatures before processing. The Communication Contract requires Ed25519 signatures on all messages.

2. **Capability escalation.** The Capability Contract enforces strict subset delegation. A child agent MUST NOT possess capabilities exceeding its parent's.

3. **Context poisoning.** Shared Context entries are signed by their author. Agents SHOULD verify the author's identity and authority before acting on context data.

4. **Interrupt injection.** Interrupts MUST be signed by an authorized source (coordinator, platform, human root). Agents MUST reject unsigned or unauthorized interrupts.

5. **Resource exhaustion.** The Security Model enforces resource quotas. Agents that exceed quotas MUST be throttled or terminated by the runtime.

6. **WASM sandbox escapes.** WASI modules operate in a sandboxed environment with no direct syscall access. All external interactions go through host functions.

---

## 19. Privacy Considerations

1. **Context visibility.** The Shared Context supports visibility levels (Session, Role, Agent) to limit information exposure within collaboration sessions.

2. **Task content.** Delegated tasks may contain sensitive data. The runtime SHOULD encrypt task payloads in transit and at rest.

3. **Health data.** Health profiles may reveal operational patterns. Access to health data SHOULD be restricted to authorized platforms and auditors.

4. **Telemetry data.** Audit trails contain detailed operational records. Storage and access MUST comply with applicable data protection regulations.

---

## 20. References

### 20.1 Normative References

- **[OAS]** Rice, J., "Open Agent Specification," openagent.id, February 2026.
- **[Arsenal]** Rice, J., "Arsenal: Capability Token Standard," openagent.id, February 2026.
- **[AEGIS]** Rice, J., "AEGIS: Autonomous Entity Gateway & Infrastructure Standard," openagent.id, February 2026.
- **[RFC 2119]** Bradner, S., "Key words for use in RFCs," BCP 14, RFC 2119, March 1997.
- **[RFC 8174]** Leiba, B., "Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words," BCP 14, RFC 8174, May 2017.
- **[WASI]** Bytecode Alliance, "WebAssembly System Interface," wasi.dev, 2024.
- **[Ed25519]** Bernstein, D.J., et al., "High-speed high-security signatures," 2012.

### 20.2 Informative References

- **[OATS]** Rice, J., "OATS: Open Agent Trust Scoring," openagent.id, February 2026.
- **[Bioagentic]** Rice, J., "Bioagentic: Universal Entity Classification Protocol," openagent.id, February 2026.
- **[Fabrics]** Rice, J., "Fabrics: Entity-Aware Routing Standard," openagent.id, February 2026.
- **[OAS-DL]** Rice, J., "OAS-DL: Definition Languages," openagent.id, February 2026.
- **[MAP]** Rice, J., "MAP: Multi-Agentic Protocol Architecture," l1fe.ai, February 2026.
- **[OpenTelemetry]** OpenTelemetry Authors, "OpenTelemetry Specification," opentelemetry.io, 2024.

---

## Appendix A: Interface Schemas

### A.1 Agent Manifest Schema

```json
{
  "$schema": "https://openagent.id/schemas/anvil/manifest/v1",
  "type": "object",
  "required": ["name", "version", "conformance_level", "module", "identity", "capabilities"],
  "properties": {
    "name": { "type": "string" },
    "version": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$" },
    "conformance_level": { "enum": ["L0", "L1", "L2"] },
    "module": {
      "type": "object",
      "properties": {
        "wasm_hash": { "type": "string", "description": "BLAKE3 hash of the WASM module" },
        "entry_point": { "type": "string", "default": "_start" }
      }
    },
    "identity": {
      "type": "object",
      "properties": {
        "did": { "type": "string", "pattern": "^did:oas:" },
        "lineage_required": { "type": "boolean" }
      }
    },
    "capabilities": {
      "type": "object",
      "properties": {
        "required_scopes": { "type": "array", "items": { "type": "string" } },
        "required_tools": { "type": "array", "items": { "type": "string" } }
      }
    },
    "collaboration": {
      "type": "object",
      "properties": {
        "supported_roles": {
          "type": "array",
          "items": { "enum": ["Coordinator", "Worker", "Peer"] }
        },
        "supported_task_types": { "type": "array", "items": { "type": "string" } },
        "max_concurrent_tasks": { "type": "integer", "default": 1 },
        "supports_checkpoint": { "type": "boolean", "default": false }
      }
    },
    "resources": {
      "type": "object",
      "properties": {
        "min_memory_bytes": { "type": "integer" },
        "max_memory_bytes": { "type": "integer" },
        "requires_network": { "type": "boolean" },
        "requires_filesystem": { "type": "boolean" }
      }
    }
  }
}
```

---

## Appendix B: Collaboration Pattern Catalog

### B.1 Sequential Pipeline

```
Agent A ──[output]──> Agent B ──[output]──> Agent C ──[result]──> Coordinator

Session type: Pipeline
Roles: Coordinator (orchestrator), Workers (A, B, C)
Context: Each worker writes its output; next worker reads predecessor's output.
Delegation: Coordinator delegates tasks sequentially, each with dependency on previous result.
```

### B.2 Fan-Out / Fan-In

```
                ┌──> Worker A ──┐
Coordinator ────┤──> Worker B ──┤──> Aggregator ──> Result
                └──> Worker C ──┘

Session type: FanOut
Roles: Coordinator (fan-out + aggregation), Workers (parallel)
Context: Coordinator writes task parameters; each worker writes results; coordinator reads all.
Delegation: Coordinator delegates N tasks simultaneously with independent constraints.
```

### B.3 Debate

```
Proponent ←──argue──→ Opponent
              │
          Judge evaluates
              │
           Verdict

Session type: Debate
Roles: Peers (proponent, opponent), Coordinator (judge)
Context: Each peer writes arguments; judge reads both and writes verdict.
```

### B.4 Consensus

```
Peer A ──vote──┐
Peer B ──vote──┤──> Tally ──> Outcome
Peer C ──vote──┘

Session type: Consensus
Roles: Peers (all participants)
Context: Each peer writes a proposal; all peers vote; outcome computed by threshold.
```

### B.5 Hierarchical Delegation

```
Director
├── Team Lead A
│   ├── Worker A1
│   └── Worker A2
└── Team Lead B
    ├── Worker B1
    └── Worker B2

Session type: Hierarchical
Roles: Coordinators (Director, Team Leads), Workers (A1, A2, B1, B2)
Context: Hierarchical — each level writes to its scope; parent reads children's results.
```

### B.6 Blackboard

```
Agent A ──write──┐
Agent B ──write──┤──> Shared Blackboard <──read── All Agents
Agent C ──write──┘

Session type: Blackboard
Roles: Peers (all agents read and write)
Context: All agents contribute asynchronously to shared context; no explicit coordination.
```

---

## Appendix C: Conformance Test Scenarios

### C.1 Identity Contract Tests

| Test | Description | Expected |
|------|-------------|----------|
| `identity.did_present` | Agent has a valid OAS DID after initialization | DID matches `did:oas:*` pattern |
| `identity.sign_verify` | Agent signs data and signature verifies | Verification succeeds |
| `identity.derive_child` | Agent derives a sub-agent identity | Child has valid lineage proof |
| `identity.context_propagation` | Tool invocation includes agent DID | DID present in invocation context |

### C.2 Collaboration Contract Tests

| Test | Description | Expected |
|------|-------------|----------|
| `collab.session_join` | Agent joins a collaboration session | JoinAcknowledgment returned |
| `collab.task_delegate_accept` | Worker accepts a compatible task | TaskAcknowledgment with accepted=true |
| `collab.task_delegate_reject` | Worker rejects an incompatible task | TaskAcknowledgment with accepted=false |
| `collab.context_write_read` | Agent writes context, another reads | Value matches |
| `collab.context_subscribe` | Agent subscribes to context changes | Notification received on change |
| `collab.interrupt_priority` | Agent receives PriorityOverride | Current work suspended, new task started |
| `collab.interrupt_suspend_resume` | Agent suspended then resumed | State restored from checkpoint |
| `collab.pipeline_pattern` | Three agents in sequential pipeline | Final output incorporates all three contributions |
| `collab.fanout_pattern` | One coordinator, three parallel workers | All results aggregated correctly |
| `collab.capability_advertisement` | Agent advertises capabilities | Profile matches manifest declarations |

### C.3 Cross-Language Tests

Every test in C.1-C.2 MUST produce identical results across all six language implementations.

---

## Appendix D: Revision History

| Version | Date | Changes |
|---------|------|---------|
| 1.0.0 | February 2026 | Initial release. Defines eight runtime contracts: identity, capability, tool, health, communication, collaboration, lifecycle, telemetry. Introduces Collaboration Contract with roles (Coordinator, Worker, Peer), shared context, task delegation, interruption handling, and session lifecycle. Six collaboration patterns cataloged. Three conformance levels. Cross-platform deployment model including Sigil blockchain. |

---

*ANVIL: The foundational surface upon which all agents are forged.*

*This specification is published under Creative Commons Attribution 4.0 International (CC BY 4.0). Any party may implement, extend, and distribute ANVIL-conforming systems without restriction.*

*For questions, errata, and contributions: https://openagent.id/spec/anvil/v1*