Home/Docs/Getting Started/Project Manifest Specification

ContextUnity Project Manifest SpecificationπŸ”—

This document is the authoritative specification for ContextUnity project manifests (contextunity.project.yaml). It defines the schema, configuration authority hierarchy (C0–C3), first-class tool declarations, named model pools with fallback and parallel execution strategies, model scoping rules, and prompt resolution semantics.


1. Configuration Authority Hierarchy (C0–C3)πŸ”—

ContextUnity enforces a strict four-level configuration hierarchy as defined in ADR-0002:

LevelScopeAuthority & OwnershipExamples
C0Deployment / OperatorHost environment, router.yml, environment variables, Shield security policies, hard budget caps. Manifests cannot grant permissions, widen tenant scopes, or override C0 security ceilings.OPENAI_API_KEY, Shield master key, physical host ports, rate limits.
C1Project Manifestcontextunity.project.yaml. Project identity, enabled services, global defaults, secret references, named model_pools, first-class tools, and multi-step graphs.router.config.model_pools, router.tools, project.allowed_tenants.
C2Graph / Tool ScopeDeclared on a specific graph or tool definition in the manifest. Restricts or binds model pools, overrides defaults, and defines tool-specific settings.router.tools.<id>.pool, router.tools.<id>.instructions, router.graph.<id>.config.
C3Node / Invocation CallDynamic options passed at runtime by code callers (e.g. via RouterClient.execute_tool). Constrained by C2 and C1 scopes.config={"model": "fast", "instructions": "..."} in application code.
Important

Invariant: C0 deployment settings, Shield security policies, and hard budget caps are absolute ceilings. Manifests (C1), tool scopes (C2), and invocation calls (C3) cannot widen tenant scopes, grant permissions, or bypass C0 security boundaries (fail-closed). Unknown keys in any typed configuration block fail validation immediately during manifest parsing (extra="forbid").


2. Top-Level Manifest StructureπŸ”—

apiVersion: contextunity/v1alpha10
kind: ContextUnityProject

project:
  id: commerce
  name: ContextCommerce PIM
  allowed_tenants:
    - primary-tenant

services:
  router:
    enabled: true
  brain:
    enabled: true
  worker:
    enabled: true
  shield:
    enabled: false

secrets:
  - owner: contextunity
    resolver: env
    keys:
      - SUBQ_API_KEY
      - OPENAI_API_KEY
      - ANTHROPIC_API_KEY

router:
  # First-class standalone tools
  tools: { ... }

  # Multi-step agentic workflows
  graph: { ... }

  # Router configuration & model pools
  config: { ... }

observability:
  health_probe: true
  readiness_check_mode: stream
  expected_tools: []
  tracing:
    transport: disabled

3. First-Class Standalone Tools (router.tools)πŸ”—

3.1 Motivation: Deprecating Dummy Single-Node GraphsπŸ”—

In legacy manifests, invoking a single platform or federated tool (such as platform:classify) required wrapping it in an artificial single-node LangGraph:

# DEPRECATED: Do not wrap single tools in dummy graphs
commerce_matcher:
  nodes:
    - name: classify
      type: tool
      tool_binding: platform:classify
      config:
        tool_config: { ... }
  edges:
    - from_node: __start__
      to_node: classify
    - from_node: classify
      to_node: __end__

This pattern introduced unnecessary graph compilation overhead, synthetic state keys (classification_request, classification_result), and boilerplate edge routing for what is conceptually a direct function or tool call.

3.2 Canonical Tool DeclarationπŸ”—

Tools are declared directly under router.tools.<tool_id>:

Important

Invariant: Standalone platform and federated tools are declared directly under router.tools without requiring an artificial single-node router.graph.

router:
  tools:
    matcher_classify:
      tool: platform:classify
      pool: fast_classifier
      instructions: >-
        Compare the supplier product only with the supplied canonical SKU options.
        Select an option only when product identity and variant attributes agree;
        return no_match when none apply and uncertain when the evidence is ambiguous.
      config:
        max_choice_criteria: 255
        timeout_seconds: 10

3.3 Tool AttributesπŸ”—

  • tool (required, str): The tool binding identifier (e.g. platform:classify, platform:web_search, federated:search_brands).
  • pool (optional, str): Name of the model pool configured under router.config.model_pools. Restricts model selection to this pool.
  • model (optional, str): Strictly pins the tool to a single model (e.g. subq/classifier:SUBQ_API_KEY or openai/gpt-5.6-luna). If specified, the tool cannot use any other model or fallback.
  • instructions (optional, str): Default tool instructions / prompt.
  • config / settings (optional, dict[str, Any]): Tool-specific parameters (e.g. max_choice_criteria, timeout_seconds).

4. Model Pools & Strategies (router.config.model_pools)πŸ”—

4.1 SpecificationπŸ”—

Model pools provide reusable, resilient groups of AI models with configurable failover or parallel execution strategies. Each candidate model declares its own provider-qualified reference, individual secret_ref, and custom settings.

Important

Invariant: Each pool declares one type (llm, classifier, or embedding; default llm). Router validates every candidate against the authoritative catalog before model initialization. Strategies (fallback, first_win, parallel) apply across these pool types with per-candidate credentials and settings. Candidate declarations support structured mappings and compact string shorthand <model>:<secret_ref>.

Named pools bound to platform:classify require type: classifier. A mismatched pool or candidate raises a configuration error before model construction or provider I/O.

Automatic global LLM fallback excludes catalog entries with tier: frontier. Frontier execution requires an explicit manifest pool candidate or an authorized caller selection within its admitted scope, as specified in ADR-0023.

router:
  config:
    model_pools:
      fast_classifier:
        type: classifier
        strategy: fallback  # "fallback" | "first_win" | "parallel"
        models:
          - name: subq/classifier
            secret_ref: SUBQ_API_KEY
            settings:
              max_choice_criteria: 255
              timeout_seconds: 5
          - name: openai/decisions
            secret_ref: OPENAI_API_KEY
            settings:
              max_choice_criteria: 255

      deep_reasoning:
        type: llm
        strategy: fallback
        models:
          - name: openai/gpt-6-luna
            secret_ref: OPENAI_API_KEY
          - name: anthropic/claude-sonnet-5-5
            secret_ref: ANTHROPIC_API_KEY

4.2 Compact Shorthand SyntaxπŸ”—

For simple candidate declarations without extra settings, string shorthand <model>:<secret_ref> is supported:

models:
  - subq/classifier:SUBQ_API_KEY
  - openai/decisions:OPENAI_API_KEY

4.3 Execution StrategiesπŸ”—

Model pools support three distinct execution strategies depending on the operational goal:

router:
  config:
    model_pools:
      # 1. Fallback: Sequential failover across providers
      fast_classifier:
        type: classifier
        strategy: fallback
        models:
          - subq/classifier:SUBQ_API_KEY
          - openai/decisions:OPENAI_API_KEY

      # 2. First-Win: Concurrent race to minimize tail latency
      latency_sensitive:
        type: classifier
        strategy: first_win
        models:
          - subq/classifier:SUBQ_API_KEY
          - openai/decisions:OPENAI_API_KEY

      # 3. Parallel: Run all candidates and return all responses
      ensemble_review:
        type: llm
        strategy: parallel
        models:
          - openai/gpt-6-luna:OPENAI_API_KEY
          - anthropic/claude-sonnet-5-5:ANTHROPIC_API_KEY

1. strategy: fallback (Sequential Failover)πŸ”—

  • Behavior: Invocations attempt the primary candidate first.
  • Failover Triggers: Automatically switches to the next candidate only upon retryable errors:
    • HTTP 429 (ModelRateLimitError / Quota Exceeded)
    • HTTP 500, 502, 503, 504 (ModelError upstream)
    • Network / Connection Timeout (ModelTimeoutError / httpx.TimeoutException)
    • Provider Outage / Unavailability
  • Credential Switch: When failing over from subq/classifier to openai/decisions, Router automatically resolves OPENAI_API_KEY for the second candidate.
  • Fatal Errors: Non-retryable errors (e.g. HTTP 400 Bad Request, schema validation errors, cost budget exceeded) fail immediately without falling back.
  • Return Value: Single successful response.

2. strategy: first_win (Concurrent Race)πŸ”—

  • Behavior: Dispatches the request concurrently to all candidates in the pool.
  • Mechanism: Monitors tasks via asyncio.wait(..., return_when=FIRST_COMPLETED) or asyncio.as_completed. As soon as the first candidate completes successfully, all remaining pending tasks are immediately cancelled.
  • Fault Tolerance: If a candidate raises an exception, the race continues until another candidate succeeds or all fail.
  • Use Case: Eliminating p99 latency spikes on user-facing critical paths.
  • Return Value: Single successful response from the fastest winning model.

3. strategy: parallel (Ensemble / Multi-Model Execution)πŸ”—

  • Behavior: Dispatches the request concurrently to all candidates in the pool and waits for all of them to complete (asyncio.gather(..., return_exceptions=True)).
  • Return Value: Returns the results of all models as a dictionary keyed by model name:
    {
        "openai/gpt-6-luna": ModelResponse(...),
        "anthropic/claude-sonnet-5-5": ModelResponse(...)
    }
  • Use Case: Multi-model consensus, majority voting, comparison, auditing, and high-reliability verification.

5. Model Selection, Inheritance & Code Override RulesπŸ”—

This section illustrates how manifest declarations govern model selection, how tools inherit defaults, and how runtime Python code interacts with pools.

Important

Invariant: Runtime model overrides passed by callers (config={"model": ...}) are constrained fail-closed to the tool's configured pool or pinned model. Requests for unpermitted models fail immediately with ConfigurationError.

5.1 Manifest Setup (YAML)πŸ”—

router:
  config:
    # 1. Project Global Defaults
    models:
      llm:
        default: openai/gpt-6-luna
        secret_ref: OPENAI_API_KEY

    # 2. Named Model Pools
    model_pools:
      standard_classifier:
        type: classifier
        strategy: fallback
        models:
          - name: openai/decisions
            secret_ref: OPENAI_API_KEY
          - name: subq/classifier
            secret_ref: SUBQ_API_KEY

      fast_classifier:
        type: classifier
        strategy: fallback
        models:
          - name: subq/classifier
            secret_ref: SUBQ_API_KEY
            settings:
              max_choice_criteria: 255
          - name: openai/decisions
            secret_ref: OPENAI_API_KEY

  # 3. First-Class Tool Declarations
  tools:
    # Case A: Standard classifier pool
    general_classifier:
      tool: platform:classify
      pool: standard_classifier
      instructions: "Categorize input into general categories."

    # Case B: Pool Scoped (restricted to fast_classifier pool)
    matcher_classify:
      tool: platform:classify
      pool: fast_classifier
      instructions: "Match supplier product to canonical catalog SKU."
      settings:
        max_choice_criteria: 255

    # Case C: Strict Model Pinning (locked to exactly one model)
    strict_subq_tool:
      tool: platform:classify
      model: subq/classifier:SUBQ_API_KEY
      instructions: "Process strictly with SubQ."

5.2 Resolution Behavior by Tool CaseπŸ”—

ToolManifest BindingAllowed Models at RuntimeDefault Execution Behavior
general_classifier (Case A)pool: standard_classifier['openai/decisions', 'subq/classifier']Executes openai/decisions with fallback to subq/classifier.
matcher_classify (Case B)pool: fast_classifierRestricted strictly to ['subq/classifier', 'openai/decisions']Uses the complete pool strategy. An explicit admitted model override narrows it to that model.
strict_subq_tool (Case C)model: subq/classifierOnly ['subq/classifier']. No overrides or fallbacks allowed.Always executes subq/classifier.

5.3 Invocation from Python CodeπŸ”—

Here is how application code invokes these tools and how options work:

from contextunity.core.sdk import RouterClient
from contextunity.core.sdk.types import ClassificationRequest, ClassificationOption
from contextunity.core.exceptions import ConfigurationError

request = ClassificationRequest(
    subject="Apple iPhone 15 Pro Max 256GB Natural Titanium",
    options=[
        ClassificationOption(option_id="sku-101", description="iPhone 15 Pro Max 256GB Titanium"),
        ClassificationOption(option_id="sku-102", description="iPhone 15 Pro 128GB Black"),
    ],
)

async with RouterClient(token=token, tenant_id=tenant_id) as client:

    # -------------------------------------------------------------
    # 1. Standard Call (no config overrides): uses tool default & fallback pool
    # -------------------------------------------------------------
    result = await client.execute_tool(
        tool_name="matcher_classify",
        payload={"classification_request": request.model_dump(mode="json")},
    )
    # Execution: Tries subq/classifier first; if 429/timeout occurs,
    # fails over to openai/decisions automatically.

    # -------------------------------------------------------------
    # 2. Explicit Model Override (allowed candidate from pool)
    # -------------------------------------------------------------
    result = await client.execute_tool(
        tool_name="matcher_classify",
        payload={"classification_request": request.model_dump(mode="json")},
        config={"model": "openai/decisions"},
    )
    # Execution: Bypasses SubQ and calls openai/decisions directly,
    # because openai/decisions is an admitted member of 'fast_classifier'.

    # -------------------------------------------------------------
    # 3. Dynamic Instructions Override (Tier 1 Prompt)
    # -------------------------------------------------------------
    result = await client.execute_tool(
        tool_name="matcher_classify",
        payload={"classification_request": request.model_dump(mode="json")},
        config={
            "instructions": "TEST PROMPT: Match only if color and capacity match 100% exactly."
        },
    )
    # Execution: Replaces tool manifest instructions with the dynamic test prompt.

    # -------------------------------------------------------------
    # 4. Security / Scope Violation (Fail-Closed)
    # -------------------------------------------------------------
    try:
        await client.execute_tool(
            tool_name="matcher_classify",
            payload={"classification_request": request.model_dump(mode="json")},
            config={"model": "anthropic/claude-3-7-sonnet"},
        )
    except ConfigurationError as exc:
        print(exc)
        # Output:
        # ConfigurationError: Model 'anthropic/claude-3-7-sonnet' is not permitted
        # for tool 'matcher_classify'. Admitted candidates for pool 'fast_classifier':
        # ['subq/classifier', 'openai/decisions'].

6. Prompt and Instructions Resolution HierarchyπŸ”—

The effective instructions or prompt provided to a model or tool are resolved using a 4-tier precedence:

Important

Invariant: Prompt resolution enforces 4-tier precedence: (1) dynamic caller request.instructions, (2) C2 tool instructions, (3) candidate model settings.prompt, or (4) fail-closed ConfigurationError. Silent execution without instructions is prohibited.

flowchart TD
    Start["Tool Invocation"] --> T1{"Tier 1: Dynamic Prompt in Code Call?<br/>(options['instructions'] / options['prompt'])"}
    T1 -- Yes --> UseT1["Apply Dynamic Code Prompt<br/>(Fast iteration & testing)"]
    T1 -- No --> T2{"Tier 2: Tool Manifest Default?<br/>(router.tools.<id>.instructions)"}
    T2 -- Yes --> UseT2["Apply Tool Manifest Default"]
    T2 -- No --> T3{"Tier 3: Model-Specific Prompt?<br/>(model_pools.<pool>.models[i].settings.prompt)"}
    T3 -- Yes --> UseT3["Apply Model-Specific Prompt"]
    T3 -- No --> T4["Tier 4: Fail Closed!<br/>Raise ConfigurationError before HTTP"]

Precedence Details:πŸ”—

  • Tier 1 (Dynamic Code Call): config={"instructions": "..."} or prompt="..." passed in RouterClient.execute_tool. Enables developers to test and refine prompts immediately in unit tests and local code without redeploying or restarting services.
  • Tier 2 (Tool Declaration): router.tools.<tool_id>.instructions defined in contextunity.project.yaml. Serves as the stable production baseline for the tool.
  • Tier 3 (Model Declaration): settings.prompt defined on an individual candidate in router.config.model_pools. Used when a specific model requires tailored system formatting.
  • Tier 4 (Fail-Closed Boundary): If no instructions or prompt are resolved from Tiers 1–3, Router refuses to execute the tool, raising ConfigurationError("No instructions or prompt provided for tool invocation"). Silent execution with empty prompts is strictly prohibited.

7. Complete Manifest ExampleπŸ”—

Below is a complete, production-grade manifest demonstrating first-class tools, model pools, fallback strategies, and multi-step graphs:

apiVersion: contextunity/v1alpha10
kind: ContextUnityProject

project:
  id: commerce
  name: ContextCommerce PIM
  allowed_tenants:
    - primary-tenant

services:
  router:
    enabled: true
  brain:
    enabled: true
  worker:
    enabled: true
  shield:
    enabled: false

secrets:
  - owner: contextunity
    resolver: env
    keys:
      - SUBQ_API_KEY
      - OPENAI_API_KEY
      - ANTHROPIC_API_KEY

router:
  # First-class tools
  tools:
    matcher_classify:
      tool: platform:classify
      pool: fast_classifier
      instructions: >-
        Compare the supplier product only with the supplied canonical SKU options.
        Select an option only when product identity and variant attributes agree;
        return no_match when none apply and uncertain when the evidence is ambiguous.
      settings:
        max_choice_criteria: 255
        timeout_seconds: 5

    gardener_enrich:
      tool: platform:classify
      pool: fast_classifier
      instructions: >-
        Validate and categorize incoming raw catalog items into canonical taxonomies.
      settings:
        max_choice_criteria: 100

  # Multi-step agentic workflows
  graph:
    gardener:
      template: yaml:gardener
      runtime:
        taxonomy_version: v2
      overrides:
        classify:
          pool: fast_classifier

    enricher:
      template: yaml:enricher
      runtime:
        bilingual: true
      overrides:
        enrich:
          model: openai/gpt-5.6-luna

  # Global router configuration
  config:
    model_pools:
      fast_classifier:
        type: classifier
        strategy: fallback
        models:
          - name: subq/classifier
            secret_ref: SUBQ_API_KEY
            settings:
              max_choice_criteria: 255
              timeout_seconds: 5
          - name: openai/decisions
            secret_ref: OPENAI_API_KEY
            settings:
              max_choice_criteria: 255

      deep_reasoning:
        type: llm
        strategy: fallback
        models:
          - name: openai/gpt-5.6-luna
            secret_ref: OPENAI_API_KEY
          - name: anthropic/claude-3-7-sonnet
            secret_ref: ANTHROPIC_API_KEY

    models:
      llm:
        default: openai/gpt-5.6-luna
        secret_ref: OPENAI_API_KEY
      embeddings:
        default: vertex/text-embedding-005

observability:
  health_probe: true
  readiness_check_mode: stream
  expected_tools: []
  tracing:
    transport: disabled

8. Cost Budget Hierarchy & Standalone Model SemanticsπŸ”—

ContextUnity enforces model cost limits at the invocation boundary and reconciles provider spend within each ExecuteTool call or GraphRun. Every budget uses the typed USD microdollar block budget: {max_cost_micros: <integer>, currency: USD}. Deployment C0 uses CU_ROUTER_VERDICT_MAX_COST_MICROS, which defaults to 100000000.

8.1 Three-Level Budget HierarchyπŸ”—

LevelSourceManifest / Code MappingBehavior
Level 1: Invocation ceiling (C3)Tool declaration and caller configtool.config.max_cost_micros and ExecuteTool.config.max_cost_microsThe lower supplied integer ceiling applies to the invocation.
Level 2: Project and pool ceilings (C1/C2)Project manifestrouter.config.conductor.budget and router.config.model_pools.<pool>.budgetEach supplied typed budget narrows the execution ceiling. The pool inherits the project ceiling and can narrow it further.
Level 3: Model pricing preflightAuthoritative model catalogBaseModel.estimate_cost(request)Cold-cache cost estimation must fit the remaining effective ceiling before provider I/O.

The effective ceiling is the minimum of the supplied invocation, project, pool, and deployment limits. BaseModel.estimate_cost(request) performs cold-cache preflight from the canonical price catalog before provider I/O. Billed remote LLM entries require a verified provider API max_output_tokens bound with source URL and check date. A request or provider-config output cap narrows the estimate only when the current adapter forwards that cap. Unknown prices, unsupported modalities, invalid limits, and missing bounds raise ModelBudgetExceededError before provider I/O. Local zero-cost models remain eligible without a fictitious API output cap. Provider adapters currently use the standard service tier; an unforwarded raw service_tier value does not change the estimate.

Classification pool candidates use the existing provider settings mapping for generation controls such as max_output_tokens, max_tokens, and max_completion_tokens. Provider aliases follow the adapter's normal precedence, and the same settings are used to build the preflight and provider request. When these settings omit an output limit, preflight prices against the catalog's provider API maximum and the adapter retains its existing default behavior.

Reservations are atomic and scoped to the active ExecuteTool call or GraphRun. A successful provider response reconciles its actual usage. A failed or cancelled attempt with unknown spend retains its full estimate. Fallback reserves each retry as it starts; parallel strategies reserve the sum of all candidate retry estimates before starting any candidate. first_win also reserves the concurrent sum, then cancels and drains losing tasks. This keeps cancellation and retry costs within the same ceiling.

8.2 Standalone Model Semantics (Virtual Pools)πŸ”—

When a standalone manifest tool under router.tools.<tool_id> references a model directly without specifying a named pool, ExecuteTool compiles its invocation into a virtual pool:

router:
  tools:
    direct_luna_tool:
      tool: platform:classify
      model: openai/gpt-6-luna:OPENAI_API_KEY
  1. Virtual Pool Resolution: Router treats model as an implicit, single-candidate virtual pool:
    • Pool name: __virtual__/<tool_id>
    • Strategy: fallback (one candidate)
    • Candidates: [openai/gpt-6-luna] with resolved credential OPENAI_API_KEY.
  2. Budget Inheritance: The virtual pool inherits router.config.conductor.budget and the deployment C0 ceiling. It has no separate budget block; the tool declaration and caller limits narrow the inherited ceiling at L1.
  3. Invocation ceiling: The tool declaration and caller config limits combine by minimum with the inherited pool and project ceilings.
  4. Execution lifetime: Reservations and settled cost accumulate across attempts within the ExecuteTool call. A new execution receives a new ledger.

For platform:classify, a direct LLM declaration retains structured LLM classification through this compiler-created virtual pool. A named pool bound to platform:classify must have type: classifier; a manifest-authored __virtual__/... name does not grant the direct-model exception.

Provider options for a direct model use the declaration's existing settings mapping. Virtual-pool compilation carries these options into its single candidate's settings, including output-token aliases resolved by the provider adapter. Tool controls retain their normal configuration validation.


9. Durable Execution Traces & Manifest Observability PipelineπŸ”—

Observability in ContextUnity distinguishes between durable execution facts (business audit, billing, state replay) and technical telemetry (distributed tracing, metrics).

flowchart LR
    ToolExec["Tool Execution<br/>(ExecuteTool RPC)"] --> Snap["TerminalTraceSnapshot<br/>(Execution facts, token usage, cost)"]
    Snap --> Brain["Brain Durable Execution Trace<br/>(LogTrace RPC - Canonical Truth)"]
    Brain --> SQLite["Brain Durable Storage<br/>(SQLite / Event Store)"]
    Brain -. Optional .-> OTLP["OpenTelemetry Export<br/>(export_terminal_trace_optional)"]

9.1 Brain Execution Trace as Canonical TruthπŸ”—

  • LogTrace RPC: The primary recording boundary for all workflow steps, tool executions, and model invocations.
  • Records exact token counts, cost in micros, latency, model versions, tenant ID, and provenance hashes.
  • Invariant: Brain durable trace records are the sole source of truth for billing, SLA auditing, and execution replays.

9.2 Standalone ExecuteTool IntegrationπŸ”—

  • Standalone tools executed via RouterService.ExecuteTool are first-class execution units in the Brain trace pipeline.
  • Router captures a TerminalTraceSnapshot for every ExecuteTool invocation, recording tool identity, caller tenant, execution latency, and token/cost metrics.
  • Emits the snapshot to Brain via LogTrace, ensuring standalone tools share full parity with multi-step graph nodes.

9.3 Secondary OpenTelemetry (OTLP) ExportπŸ”—

  • OpenTelemetry is treated as a secondary technical export (export_terminal_trace_optional), decoupled from application business logic.
  • Telemetry collectors receive OTLP spans exported asynchronously from Brain trace snapshots.
  • If OTLP transport is disabled (observability.tracing.transport: disabled) or fails, execution continues unhindered; durable execution facts in Brain are never compromised.