{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://writ.lightningenable.com/schema/mission.schema.json",
  "title": "Writ Mission Manifest",
  "description": "Declarative definition of a bounded, paid, receipted agent mission. One file is the entire configuration surface: task, budget, capabilities, delegated workers, settlement, and work-record signing. SECURITY: a manifest is semi-trusted input — run only manifests you trust. ${ENV} reads the process environment, but only OPT-IN: a name must either be listed in the top-level `env` block or be prefixed WRIT_VAR_, and secret-shaped names (KEY/SECRET/TOKEN/PASSWORD/CRED/NWC/MACAROON/MNEMONIC/SEED/PRIVATE) are refused even when declared, so a manifest cannot exfiltrate a credential or quietly read the rest of your environment; prefer --var for configuration. All output paths are confined to the run directory, and step-output files hold untrusted capability/LLM content (do not open them directly in a browser).",
  "type": "object",
  "required": ["mission", "budget", "capabilities", "workers"],
  "additionalProperties": false,
  "properties": {
    "mission": {
      "type": "object",
      "required": ["name", "goal"],
      "additionalProperties": false,
      "properties": {
        "name": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$", "description": "Slug for the mission; used in run ids and output paths." },
        "goal": { "type": "string", "minLength": 1, "description": "What the mission should accomplish. May reference {{vars}}." },
        "schedule": { "type": "string", "default": "manual", "description": "'manual' or a cron expression (v1: manual only is executed)." },
        "vars": {
          "type": "array",
          "items": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" },
          "description": "Names of variables the mission expects; supplied at run time via --var and referenced as {{name}}. A referenced-but-unsupplied var is a hard error."
        }
      }
    },
    "env": {
      "type": "array",
      "items": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" },
      "description": "Environment variables this manifest is allowed to read through ${NAME}. Reading the environment is opt-in per variable: a ${NAME} reference resolves only when NAME is listed here or is prefixed WRIT_VAR_ (an operator-namespaced escape hatch that needs no declaration); every other reference is a hard error naming the variable and both allowed forms. Secret-shaped names (KEY/SECRET/TOKEN/PASSWORD/CRED/NWC/MACAROON/MNEMONIC/SEED/PRIVATE) are refused even when listed here — declaring one is not a way around that. A declared-but-unset variable is also a hard error, never a silent empty. Omit the block for a mission that reads no environment at all."
    },
    "model": {
      "type": "object",
      "description": "The LLM provider for agent/LLM steps. Bring your own model.",
      "additionalProperties": false,
      "properties": {
        "provider": { "type": "string", "enum": ["anthropic", "openai-compatible", "claude-cli", "codex"], "default": "anthropic", "description": "Default is the HTTP anthropic client. The local-CLI providers (claude-cli, codex) are opt-in." },
        "endpoint": { "type": "string", "description": "Base URL for openai-compatible/anthropic (supports ${ENV} for a declared or WRIT_VAR_-prefixed name). SSRF-guarded before use: an endpoint resolving to loopback/private/cloud-metadata is refused, and the client follows no redirects." },
        "model": { "type": "string", "description": "Model id for the provider." },
        "api_key_env": { "type": "string", "description": "Name of the env var holding the API key (the key itself is never in the manifest). May not name a protected Writ/system secret (WRIT_ROOT_KEY, WRIT_RECEIPT_KEY, WRIT_AUDIT_KEY, DB_ENCRYPTION_KEY, NWC_CONNECTION_STRING, LND_MACAROON_HEX, STRIKE_API_KEY, OPENNODE_API_KEY)." },
        "timeout_seconds": { "type": "integer", "minimum": 1, "description": "Per-call LLM timeout override, in seconds; must be greater than 0. Omit to use the default: for claude-cli/codex (which run a full headless agentic session — tool use, MCP calls, builds — not a single completion) the factory applies 1800s (30 min); openai-compatible/anthropic keep their own client default." }
      }
    },
    "budget": {
      "type": "object",
      "required": ["total_sats"],
      "additionalProperties": false,
      "properties": {
        "total_sats": { "type": "integer", "minimum": 0, "description": "Cumulative spend cap for the whole mission, enforced atomically at the credential-chain root." },
        "per_call_max_sats": { "type": "integer", "minimum": 0, "description": "Ceiling for any single capability call. A call is refused before payment if the price exceeds this or the capability's own max_sats_per_call, whichever is lower." },
        "currency_display": { "type": "string", "enum": ["sats", "usd"], "default": "sats", "description": "Display unit for human output only; all accounting is in sats." }
      }
    },
    "settlement": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "mode": { "type": "string", "enum": ["simulated", "wallet"], "default": "simulated", "description": "'simulated' runs the full pipeline against an in-process L402 endpoint with no real money (every artifact marked simulated). 'wallet' pays real Lightning invoices via a detected wallet (LND > NWC > Strike), bounded by budget." }
      }
    },
    "approvals": {
      "type": "object",
      "additionalProperties": false,
      "description": "Human-in-the-loop gate. Omit or leave empty for fully autonomous operation within the budget/scope bounds.",
      "properties": {
        "threshold_sats": { "type": "integer", "minimum": 0, "description": "Any single call at or above this sat amount suspends the run for human approval. 0 = every paid call needs approval." },
        "cumulative_threshold_sats": { "type": "integer", "minimum": 0, "description": "The total sats the run may spend without approval. A call that would take the run's unapproved spend (settled, reserved, or awaiting reconciliation) over this suspends for approval. Approved spend is not counted, and approving does not reset the count." },
        "window_threshold_sats": { "type": "integer", "minimum": 0, "description": "The sats the run may spend without approval in any rolling window of window_seconds. Requires window_seconds." },
        "window_seconds": { "type": "integer", "minimum": 1, "maximum": 31536000, "description": "Length of the rolling window for window_threshold_sats, in seconds. Requires window_threshold_sats." },
        "approval_ttl_minutes": { "type": "integer", "minimum": 1, "default": 15, "description": "How long an approval stays usable after a human grants it." }
      },
      "dependentRequired": {
        "window_threshold_sats": ["window_seconds"],
        "window_seconds": ["window_threshold_sats"]
      }
    },
    "capabilities": {
      "type": "array",
      "minItems": 1,
      "description": "The capabilities the mission may call. A worker's scope must reference these ids.",
      "items": {
        "type": "object",
        "required": ["id", "kind"],
        "additionalProperties": false,
        "properties": {
          "id": { "type": "string", "pattern": "^[a-z0-9]+([.][a-z0-9]+)*$", "description": "Hierarchical capability id (e.g. dns.whois, llm.write). Capability caveats match against this." },
          "kind": { "type": "string", "enum": ["internal", "http", "l402-http"], "description": "internal = in-process (e.g. llm.*, free); http = plain HTTP (SSRF-guarded, no payment); l402-http = paid per-call over L402." },
          "base_url": { "type": "string", "description": "Required for http/l402-http. SSRF-guarded and DNS re-resolved at call time." },
          "path": { "type": "string", "description": "Resource path appended to base_url." },
          "method": { "type": "string", "enum": ["GET", "POST"], "default": "GET" },
          "max_sats_per_call": { "type": "integer", "minimum": 0, "default": 0, "description": "Per-call price ceiling for this capability. An L402 challenge above this is refused before payment. 0 for internal." },
          "allow_local": { "type": "boolean", "default": false, "description": "Permit loopback/private targets for THIS capability only (local mock/demo endpoints). Cloud-metadata endpoints are denied even so. Flagged loudly by `writ validate`." }
        },
        "allOf": [
          {
            "if": { "properties": { "kind": { "enum": ["http", "l402-http"] } } },
            "then": { "required": ["base_url"] }
          }
        ]
      }
    },
    "workers": {
      "type": "array",
      "minItems": 1,
      "description": "Each worker receives a delegated child credential — strictly narrower than the mission root (its scope, a slice of the budget, a shorter expiry). Workers run in order (v1).",
      "items": {
        "type": "object",
        "required": ["name", "scope", "steps"],
        "additionalProperties": false,
        "properties": {
          "name": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$", "description": "Worker name; appears as the actor in the work record." },
          "scope": {
            "type": "array",
            "items": { "type": "string" },
            "description": "The capability ids this worker's delegated credential may call. Must be a subset of the declared capabilities; the delegated credential cannot reach anything outside it."
          },
          "budget_sats": { "type": "integer", "minimum": 0, "description": "Cumulative sat slice for this worker. Sum across workers must not exceed budget.total_sats. 0 = an internal-only worker with no external spend authority." },
          "expires_minutes": { "type": "integer", "minimum": 1, "default": 30, "description": "Lifetime of the worker's delegated credential." },
          "parent": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$", "description": "Optional name of another worker (declared EARLIER) that delegates authority to this one — a real agent→agent hop: this worker's credential is attenuated from the parent's, not from the mission root. The grant must be strictly narrower than the parent's (scope ⊆ parent, budget ≤ parent, expiry ≤ parent); the authority engine enforces this cryptographically. Omit for a top-level worker delegated straight from the root. A child's budget is a sub-allocation of its parent's slice, so it does NOT count again toward budget.total_sats." },
          "steps": {
            "type": "array",
            "minItems": 1,
            "items": {
              "type": "object",
              "required": ["type"],
              "additionalProperties": false,
              "properties": {
                "type": { "type": "string", "enum": ["call", "agent"], "description": "'call' = one deterministic capability call; 'agent' = a bounded LLM tool-loop choosing only among the worker's scoped capabilities." },
                "capability": { "type": "string", "description": "For type=call: the capability id to invoke." },
                "task": { "type": "string", "description": "For type=agent: the instruction to the worker model. May reference {{vars}}." },
                "max_iterations": { "type": "integer", "minimum": 1, "default": 6, "description": "For type=agent: hard cap on tool-loop iterations." },
                "input": { "type": "object", "description": "For type=call: structured input for the capability (query params / body / internal-executor instruction).", "additionalProperties": true },
                "output": { "type": "string", "description": "Optional filename to write this step's output to under runs/<run-id>/ (e.g. dossier.md). Must be a relative path confined to the run directory (absolute/rooted paths and '..' escapes are refused). The file holds untrusted capability/LLM content — do not open it directly in a browser." },
                "expect_refusal": { "type": "boolean", "default": false, "description": "For type=call only: assert this call is EXPECTED to be refused by the authority/budget guard (an overreach — out of scope, over budget, or expired). A refusal is recorded as a signed 'denied' work-record and the run CONTINUES (so one run can show both bounded success and a blocked overreach); if the call unexpectedly SUCCEEDS, the run fails — the delegated bound had no teeth." }
              },
              "allOf": [
                { "if": { "properties": { "type": { "const": "call" } } }, "then": { "required": ["capability"] } },
                { "if": { "properties": { "type": { "const": "agent" } } }, "then": { "required": ["task"] } }
              ]
            }
          }
        }
      }
    },
    "work_record": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "signing": { "type": "string", "enum": ["dev-ephemeral", "env", "key-file"], "default": "dev-ephemeral", "description": "How the receipt signer key is resolved. dev-ephemeral generates a throwaway per-run key (loud warning, refused under --production). env reads WRIT_RECEIPT_KEY. key-file reads a configured path." },
        "key_file": { "type": "string", "description": "Path to the signing key when signing=key-file." },
        "identity_file": { "type": "string", "description": "Path to the signer identity record (signer-identity.json, written by `writ keys init`) for signing=env|key-file. Defaults to the file next to key_file, or WRIT_RECEIPT_IDENTITY_FILE for env. The record is copied into the run directory and its hash is committed into the first receipt; required under --production, a warning when missing otherwise." },
        "output_dir": { "type": "string", "default": "runs/", "description": "Root directory for run outputs. Must be a relative path with no '..' escape (absolute/rooted paths are refused)." }
      }
    }
  }
}
