Skip to content

apcore — AI-Perceivable Core Standard Specification

Canonical specification. This document is the single normative source for the apcore protocol. Where any other document disagrees with it, this document wins.

Version: 2.0.0 Status: Draft Draft Revision: 5 Last Updated: 2026-11-30


Table of Contents


1. Overview

1.1 Project Positioning

apcore (AI-Perceivable Core) is a governed, protocol-neutral runtime and module standard for agent-callable application capabilities.

One-sentence definition:

apcore defines and enforces the schemas, behavioral metadata, access rules, approval gates, and execution lifecycle of a capability before adapters expose it to MCP, A2A, CLI, HTTP, or direct code.

Positioning: - Governed capability runtime: apcore validates and governs application capabilities at the execution boundary - Protocol-neutral definition: a capability is defined once and projected through independently versioned adapters - Complementary to MCP/A2A: transport protocols define how peers communicate; apcore defines what is executed and which runtime rules are enforced - Cross-language contract: Python, TypeScript, and Rust SDKs implement the same normative specification

1.2 Core Principles

Principle Description
Schema-driven All modules enforce definition of input_schema / output_schema / description
Three-layer Metadata Core (enforced Schema) + Annotations (behavior Annotations) + Extensions (free metadata)
Directory as ID Directory path automatically maps to module ID, zero manual configuration
Agent-readable Schema + annotations give agents structured capability metadata without promising model comprehension
Protocol-neutral Adapters can project the same governed capability to code, MCP, A2A, CLI, or HTTP surfaces

1.3 Design Goals

  • Protocol neutrality: Modules can be exposed through code, MCP, A2A, CLI, HTTP, and future adapters
  • Agent readability: Enforced schemas make capability contracts machine-readable and independently validatable
  • Developer Experience: Directory as ID, zero configuration, automatic discovery
  • Cross-language: Specification supports implementation in any programming language; the maintained implementations are the Python, TypeScript and Rust SDKs, checked against the shared conformance fixtures
  • Extensibility: ACL, middleware, observability

1.4 Relationship with MCP/A2A

apcore is a module construction specification, MCP/A2A is a communication protocol. They are complementary:

┌─────────────────────────────────────────────────────────────┐
│              apcore — AI-Perceivable Core                    │
│                                                             │
│  Solves: How to develop AI-Perceivable modules              │
│  - Directory as ID / Schema-driven / ACL / Observability / Middleware │
└─────────────────────────────────────────────────────────────┘
                           ↓ Modules can be exposed as
┌─────────────┬─────────────┬─────────────┬─────────────────┐
│ MCP Server  │  HTTP API   │  CLI Tool   │  Direct Code    │
│ (Clients)   │  (Adapters) │  (Terminal) │  (Native SDK)   │
└─────────────┴─────────────┴─────────────┴─────────────────┘

apcore focuses on "how to build AI-perceivable modules", MCP focuses on "how to call tools".

1.5 Specification Keywords

The keywords in the table have the meanings defined by BCP 14 (RFC 2119 and RFC 8174) when written in uppercase in normative text.

English Chinese Meaning
MUST / REQUIRED / SHALL Must Absolute requirement, non-compliance means non-conformance
MUST NOT / SHALL NOT Forbidden Absolutely prohibited
SHOULD / RECOMMENDED Should Strongly recommended, can deviate only with sufficient reason
SHOULD NOT / NOT RECOMMENDED Should Not Strongly discouraged, unless there's sufficient reason
MAY / OPTIONAL May Completely optional, implementer decides

1.6 Term Definitions

Core terms used in this specification are defined as follows:

Term English Definition
Module Module Basic execution unit of apcore, encapsulates a function, MUST define input_schema, output_schema, and description. Can optionally define documentation to provide detailed documentation. Neither field is length-limited by default; 200 and 5000 characters are the recommended ceilings, and a project that wants them enforced sets validation.binding.description_max_length / documentation_max_length (§9.1.2)
Schema Schema Data structure definition based on JSON Schema Draft 2020-12, used for validating input/output and for AI/LLM understanding
Canonical ID Canonical ID Globally unique identifier for a module, automatically generated from directory path, format is dot-separated snake_case (e.g., executor.email.send_email)
Registry Registry Core component responsible for module discovery, registration, loading, and management
Executor Executor Core component responsible for module invocation execution, handles Schema validation, ACL checking, middleware dispatching
Context Context Runtime context object during module execution, carries trace_id, call chain, identity information, and shared state
Access Control List ACL Set of rules defining inter-module invocation permissions, based on caller_id/target_id pattern matching
Middleware Middleware Interceptor running before and after module execution, executes in onion model, can modify input/output
Extension Point Extension Point Replaceable component interface provided by framework (e.g., SchemaLoader, ModuleLoader), allows custom implementation
Annotations Annotations Module-level behavior metadata (readonly, destructive, etc.), helps AI/LLM make invocation decisions
Metadata Metadata Completely open key-value dictionary for storing extension information, framework does not validate its content
Entry Point Entry Point Code entry location of module, format is filename:ClassName, can be auto-inferred or manually configured
Call Chain Call Chain Complete list of module ID paths from root invocation to current invocation, used for loop detection and depth limiting
Trace ID Trace ID Identifier uniquely identifying a complete invocation chain, MUST be 32-char lowercase hex (W3C Trace Context format)
Identity Identity Structured expression of caller_id identity (user/service/Agent/API Key/system), ACL engine depends on it

1.7 API Naming Conventions

apcore public API uses concise universal names (e.g., Module, Context, Registry), relying on language-native namespace mechanisms to avoid conflicts:

Language Namespace Isolation Method Example
Python Package import from apcore import Module / import apcore
Go Package name qualification apcore.Module(...)
Rust Module path apcore::Module
TypeScript Module import import { Module } from 'apcore-js'
Java Package path import com.apcore.Module

Implementations MUST follow these naming rules: - In languages with namespace mechanisms, MUST NOT add redundant prefixes to public APIs - In languages without namespace mechanisms, MUST use apcore_ prefix - Error types SHOULD be prefixed with their domain (e.g., ModuleError, SchemaValidationError)

1.8 Runtime Profiles

A conformant SDK declares the profiles it implements. A requirement applies when its profile is active. Shared module IDs, schemas, errors and execution semantics have the same meaning across profile combinations.

Profile Scope
Core In-memory registration and metadata, schema validation, call and preflight, ACL and approval governance, middleware, lifecycle, cancellation, and streaming completion
Configuration File-backed configuration, ACL rules, external schemas and overrides
Discovery Filesystem scanning, file bindings, watchers, and reload driven by an external source
System Modules Health, usage, manifest, control, and event composition driven by host configuration
Events Host-owned subscriber factories, optional sinks, retry, and dead-letter delivery
Observability Optional exporters and host-specific telemetry sinks. Core execution may deliver data to a sink supplied by the host.

The default SDK assembly MUST provide the Core Profile and MUST allow in-memory registration and execution independently of a filesystem, YAML parser, file watcher, HTTP listener, or external service. Extension profiles MUST be explicitly installed or composed by the host. An SDK may provide a full assembly that selects its extension profiles together. When selected, each extension profile MUST implement the requirements in its corresponding protocol sections. Outside the SDK, adapter profiles (§4.17) own protocol-specific tool shapes and network delivery.


2. Naming Specification

2.1 Directory as ID (Core Rule)

Directory path is the single source of truth for module IDs. IDs are automatically generated from directory paths, zero configuration.

Implementations MUST convert directory paths to Canonical IDs according to the following algorithm:

Algorithm: directory_to_canonical_id(file_path, extensions_root)

Input:
  file_path      — Complete relative path of module file (e.g., "extensions/executor/validator/db_params.py")
  extensions_root — Extension root directory name (default "extensions")

Output:
  canonical_id   — Dot-separated module ID (e.g., "executor.validator.db_params")

Preconditions:
  - file_path must start with extensions_root + "/"
  - file_path must contain file extension

Steps:
  1. relative_path ← Remove extensions_root + "/" prefix from file_path
  2. relative_path ← Remove file extension (last "." and everything after it)
  3. segments ← Split relative_path by "/"
  4. For each segment, perform validation:
     a. If segment is empty string → Throw INVALID_PATH error
     b. If segment doesn't match /^[a-z][a-z0-9_]*$/ → Throw INVALID_SEGMENT error
  5. canonical_id ← Join all segments with "."
  6. If len(canonical_id) > 192 → Throw ID_TOO_LONG error
  7. Return canonical_id

Complexity: O(n), where n is the number of characters in the path
directory_to_id:
  # Rule: Remove extensions/ prefix and file extension, convert path separator to dot
  rule: "extensions/{path}/{name}.{ext} → {path}.{name}"

  # Examples
  examples:
    - file: "extensions/executor/validator/db_params.py"
      id: "executor.validator.db_params"

    - file: "extensions/api/handler/task_submit.py"
      id: "api.handler.task_submit"

    - file: "extensions/orchestrator/engine/task_flow.py"
      id: "orchestrator.engine.task_flow"

  # ID format constraints
  format:
    pattern: "^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)*$"
    separator: "."
    case: "snake_case"
    max_length: 192

2.1.1 Multi-Class Discovery (Opt-In)

Implementations MAY support multi-class discovery mode, which allows multiple module classes to be defined in a single file. Multi-class discovery MUST be explicitly enabled — the default (single-class) behavior MUST remain unchanged.

Opt-in is per class: a class takes part when it carries the implementation's multi-class marker, and a file is in multi-class mode when at least one of its classes carries it (D-107). In a file in multi-class mode, only the classes that carry the marker receive IDs: implementations MUST NOT register a class of that file that does not carry the marker, whether or not it implements the Module interface. A marked class's ID is always base_id + "." + class_segment, however many classes of the file carry the marker — one marked class beside an unmarked Module class included — so marking a second class never renames the first. The one exception is rule 5 below: a file with exactly one Module class keeps its base_id (D-147).

When multi-class discovery is enabled for a file:

  1. The scanner MUST enumerate all exported classes in the file.
  2. For each class that carries the marker and implements the Module interface, derive its ID:
  3. base_id ← directory_to_canonical_id(file_path, extensions_root) [Algorithm A01]
  4. class_segment ← snake_case_name(ClassName)
  5. module_id ← base_id + "." + class_segment
  6. The resulting module_id MUST conform to the Canonical ID grammar (§2.7).
  7. If two classes in the same file produce the same class_segment, implementations MUST raise MODULE_ID_CONFLICT.
  8. A file with exactly one Module class MUST produce the same ID whether multi-class mode is on or off (backward compatibility guarantee).

snake_case_name is a repairing conversion for a class name, in this order:

  1. Insert _ between a run of uppercase letters and an uppercase letter followed by a lowercase letter (HTTPSender → HTTP_Sender).
  2. Insert _ between a lowercase letter or digit and an uppercase letter (MathOps → Math_Ops).
  3. Replace every character other than ASCII A–Z, a–z and 0–9 with _.
  4. Lowercase.
  5. Collapse consecutive _ to one.
  6. Strip leading and trailing _.

Examples:

class Addition   → "addition"
class MathOps    → "math_ops"
class HTTPSender → "http_sender"

snake_case_name is distinct from §2.2's non-repairing snake_case_identifier. Implementations MUST NOT share one transformation between the two operations.

Module ID Format Constraint

All module IDs MUST conform to the following regular expression:

^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$

Allowed characters: - Lowercase ASCII letters (a-z) - Digits (0-9) - Underscores (_) - Dots (.) as namespace separators only

Explicitly prohibited: - Hyphens (-) — reserved for MCP/OpenAI tool name normalization (dot→hyphen conversion must be bijective) - Uppercase letters - Spaces, special characters

All SDK implementations MUST validate module IDs against this pattern during register(). Invalid IDs MUST be rejected with INVALID_MODULE_ID error (the dedicated module-ID validation code defined in the error registry below and mandated by docs/features/error-system.md §Error Code Constants; see also the register() and Executor.call contracts in docs/features/registry-system.md and docs/features/core-executor.md).

2.2 ID Map (Cross-language Conversion)

ID Map covers two conversions. Implementations MUST support canonical conversion from a language-native ID to a Canonical ID (Algorithm A02, below). A02 receives a valid identifier in the source language; it does not repair an arbitrary string. A value that cannot become a Canonical ID is rejected at step 5, rather than rewritten. Separately, an operator can replace the ID that discovery derives for a given module file through an ID map file (below).

Algorithm: normalize_to_canonical_id(local_id, language)

Input:
  local_id  — Language-native format ID (e.g., Rust's "executor::validator::db_params")
  language  — Source language identifier (python | rust | go | java | typescript)

Output:
  canonical_id — Dot-separated snake_case format Canonical ID

Steps:
  1. Determine separator sep based on language:
     - python: "."  |  rust: "::"  |  go: "."  |  java: "."  |  typescript: "."
  2. segments ← Split local_id by sep
  3. For each segment, perform snake_case_identifier normalization:
     a. If segment contains no ASCII uppercase character (U+0041–U+005A),
        return it unchanged.
     b. Otherwise insert one "_" at each ASCII case boundary:
        - ASCII lowercase or digit followed by ASCII uppercase
        - ASCII uppercase followed by ASCII uppercase then ASCII lowercase
     c. Map each ASCII uppercase character to its ASCII lowercase counterpart.
        Leave every other code point unchanged.
     d. Return. Do not collapse, strip, replace, or otherwise repair characters.
  4. canonical_id ← Join all segments with "."
  5. Validate canonical_id conforms to ID EBNF syntax (see §2.7)
  6. Return canonical_id

snake_case_identifier preserves leading and trailing underscores. A trailing underscore can pass §2.7; a leading underscore fails it and an operator who needs a different registered ID uses id_map.overrides, not an inferred repair. The case operation is deliberately ASCII-scoped, matching §2.7's ASCII output alphabet: a non-ASCII identifier is preserved through step 3 and rejected by step 5. Implementations MUST NOT replace an out-of-alphabet character and return the replacement as a Canonical ID. An existing __ remains __; this operation only adds case boundary underscores.

ID map file. id_map.overrides (§9.1) is the path of a YAML map file. A map supplied directly to the registry or discoverer (Registry(id_map_path=…) / idMapPath / DefaultDiscoverer::with_id_map) takes precedence over the key (D-73). The file carries a top-level mappings list; each entry maps one module file, by its path relative to the extension root, to the Canonical ID it is registered under:

# apcore.yaml
id_map:
  overrides: "./id_map.yaml"
# id_map.yaml
mappings:
  - file: "executor/validator/db_params.py"   # relative to the extension root
    id: "executor.validation.db_params"
  1. During discovery, after Algorithm A01 has derived each file's ID, a file named by an entry's file is registered under that entry's id instead. A file the map does not name keeps its derived ID. The replacement ID is validated like any other discovered ID (§2.6, §2.7); one that fails validation is not registered.
  2. A configured map file that does not exist fails with CONFIG_NOT_FOUND. One that does not parse, or whose top level has no mappings list, fails with CONFIG_INVALID.
  3. An entry without file is skipped with a warning.
  4. An entry's file is resolved against the extension root the file is discovered under, in every implementation; it is never resolved against the working directory or the map file's directory. An entry carries file and id only (D-138).
  5. id_map.overrides is path-typed (§9.2.1). null means no ID map, and an empty value — including a set-but-empty environment variable — falls through to the next tier (§9.2.1 requirement 5) (D-138).

2.2.1 Bare-Name Canonicalization

SDKs MUST expose canonicalize_name(name) (TypeScript: canonicalizeName) for converting an arbitrary name, such as a CLI subcommand, to one §2.7 segment. This is a separate, explicitly repairing operation; it MUST NOT change A02, split a language-native ID, register a module, or invent a prefix for an invalid start.

The public CanonicalNameResult has original_name, nullable canonical_name, and nullable error fields (TypeScript: originalName and canonicalName). CanonicalNameError identifies one of empty_name, non_ascii, invalid_start, or name_too_long. For a string input the function MUST return a result, rather than raise an exception or panic; original_name MUST retain the input exactly. A success has a canonical segment and no error; a failure has no canonical segment and exactly one error.

Implementations MUST apply these steps in order:

  1. If any input character is outside ASCII, return non_ascii before trimming or case conversion. Implementations MUST NOT transliterate, delete, or replace non-ASCII characters to manufacture a legal-looking name.
  2. Trim leading and trailing ASCII characters outside [A-Za-z0-9_]. Existing leading and trailing underscores are retained.
  3. Apply A02's ASCII case-boundary insertion and ASCII lowercase conversion to the remaining name.
  4. Replace each maximal run of ASCII characters outside [A-Za-z0-9_] with one underscore. Existing underscore runs remain unchanged. Dots and colons are name punctuation here, not namespace or language separators.
  5. If the candidate is empty, return empty_name; otherwise, if its first character is not [a-z], return invalid_start.
  6. If the candidate exceeds 192 ASCII characters, return name_too_long. Implementations MUST NOT truncate it.
  7. Return the candidate with no error.

This operation checks segment syntax only. A reserved word such as system is a syntactically valid segment; namespace reservation, the full ID's length, and normalization collisions remain subject to §2.5–§2.7 during scanning and registration. Different names can produce the same segment, so a caller MUST NOT treat this function as proof that a module ID is unique or registrable.

Examples: cat-file → cat_file, api::GetUser → api_get_user, a___b → a___b, 2fa → invalid_start, getÜber → non_ascii. Shared verification: conformance/fixtures/canonicalize_name.json.

2.3 Special Word Handling

Rules for handling abbreviations when converting class names:

abbreviations:
  # Common abbreviations
  words: [http, api, db, id, url, sql, json, xml, html, css, tcp, udp, ip]

  # Rule: Treat abbreviations as normal words, capitalize only first letter
  # Reason: HttpJsonParser is more readable than HTTPJSONParser

  # Examples
  examples:
    id: "api.handler.http_json_parser"
    class: "HttpJsonParser"      # Not HTTPJSONParser

2.4 Version Number Handling

versioning:
  # Filename format
  pattern: "{name}_v{major}.{ext}"

  # Examples
  examples:
    - file: "db_params.py"       # No version = default version
      id: "executor.validator.db_params"

    - file: "db_params_v2.py"
      id: "executor.validator.db_params_v2"

  # Version resolution
  resolution:
    default: "latest"            # Use latest version by default
    explicit: true               # Allow explicit specification: module_id@v2

2.5 Reserved Words

reserved_words:
  # Tested against the FIRST segment of an ID only (§2.6 step 2)
  framework: [system, internal, core, apcore, plugin, schema, acl]

ephemeral is not a reserved word: the ephemeral.* namespace is restricted by registration path — Registry.register() only — rather than refused, and a reserved word would make register() reject every ID in it (§2.5.1). A segment that starts with an underscore or a digit is already excluded by the Canonical ID grammar (§2.7).

Reserved namespace semantics:

Namespace Purpose Registration mechanism
system.* Built-in framework modules (health, manifest, usage, control) Framework-internal only (e.g., Registry.register_internal()); user code MUST NOT register system.* IDs
internal.* Reserved for SDK-private modules; not intended for user code Implementation-defined
core.* Reserved for future spec promotion of metadata extension keys Reserved — no current use
apcore.*, plugin.*, schema.*, acl.* Reserved for framework subsystem extensions Reserved — no current use
ephemeral.* Programmatically-generated runtime modules (Agent-synthesized tools, on-the-fly composition) Standard Registry.register() only; framework-internal register_internal() MUST reject ephemeral.* IDs. See §2.5.1 for the full namespace contract.

2.5.1 The ephemeral.* Namespace

The ephemeral.* namespace holds modules created programmatically at runtime: agent-synthesized tools, on-the-fly compositions of existing modules, and per-session scratch tools. Such a module has no filesystem source. Its ID is supplied by the registering caller and is validated against the Canonical ID grammar (§2.7) like any other; Algorithm A01 (§2.1) governs discovery only and does not constrain Registry.register().

Membership. A module ID belongs to the namespace when it equals ephemeral or begins with ephemeral.. An ID whose first segment merely starts with those letters (ephemerals.tool) does not.

Registration.

  1. Registry.register() is the only registration path for an ephemeral.* ID.
  2. register_internal(), or its equivalent privileged API, MUST reject an ephemeral.* ID with an error that directs the caller to Registry.register().
  3. Discovery MUST NOT populate the namespace. An ephemeral.* ID yielded by filesystem discovery (§3.6) or by a custom discoverer is never registered; filesystem discovery that derives one fails with an error.
  4. The errors of rule 2 and rule 3 carry the code INVALID_MODULE_ID (§8.2) (D-148).

Rationale: each reserved namespace maps to exactly one registration path — system.* only through register_internal() (§6.6.1), ephemeral.* only through register(). That keeps framework-provenance and caller-provenance modules distinct in the audit trail, and keeps an agent-synthesized module off the privileged path that exists to bypass the reserved-namespace check.

Annotations.

  1. An ephemeral.* module SHOULD declare requires_approval: true (§4.4), so that agent-synthesized code does not run without a human decision.
  2. An ephemeral.* module SHOULD declare discoverable: false (§4.4). It remains callable by exact ID.
  3. When the effective requires_approval of an ephemeral.* module being registered — the union of its code-level and metadata annotation sources (§7.4) — is not true, Registry.register() SHOULD log a warning. The omission is not an error and does not fail the registration.

Access control and approval. A call to an ephemeral.* module passes the ACL check (§6) and the approval gate (§7) exactly as a call to any other module does; the namespace carries no exemption from either.

Audit events. Each registration and each unregistration of an ephemeral.* module MUST produce exactly one apcore.registry.module_registered or apcore.registry.module_unregistered event (§9.16.2) — never the plain registry event plus a second contextual one. The event's module_id is the ephemeral ID, and its payload carries:

Key Value
caller_id context.caller_id of the registering call; "@external" when it is absent, null or empty
identity A snapshot of context.identity with credential-bearing attributes redacted or omitted; null when the context carries no identity
namespace_class "ephemeral"

All three keys are always present. The rule holds for the bare ID ephemeral exactly as for ephemeral.<name>. An implementation's standard bootstrap — the client with the event system enabled (sys_modules.events.enabled: true, §9.15.3) — MUST deliver the event to the event emitter it wires, and a registration or unregistration that is given no context reports caller_id: "@external" and identity: null (D-148).

Registrations outside the namespace carry the payload §9.16.2 defines.

Lifecycle. An ephemeral.* module remains registered until Registry.unregister() removes it; the framework does not expire it.

Isolation. Sandboxing the code an ephemeral.* module executes is the host's responsibility. This specification governs the module's registration, access control, approval and audit, not its execution environment.

2.6 ID Conflict Detection

Implementations MUST perform conflict detection during module scanning, module registration, and dynamic loading.

Algorithm: detect_id_conflicts(new_id, existing_ids, reserved_words)

Input:
  new_id         — Canonical ID to be registered
  existing_ids   — Set of already registered IDs
  reserved_words — Set of reserved words (§2.5)

Output:
  conflict_result — { type: string, severity: "error" | "warning", message: string } | null

Steps:
  1. Exact duplication detection:
     If new_id ∈ existing_ids → Return { type: "duplicate_id", severity: "error" }
  2. Reserved word detection (FIRST SEGMENT ONLY — see below):
     first_segment ← new_id up to the first "." (the whole ID when it has none)
     If first_segment ∈ reserved_words → Return { type: "reserved_word", severity: "error" }
  3. Case collision detection:
     normalized_new ← lowercase(new_id)
     For each existing_id ∈ existing_ids:
       normalized_existing ← lowercase(existing_id)
       If normalized_new == normalized_existing and new_id ≠ existing_id:
         → Return { type: "case_collision", severity: "warning" }
  4. Return null (no conflict)

Complexity: O(n), where n is the number of registered IDs

Step 2 tests the first segment and nothing else.

A reserved word claims a namespace, not a token. §2.5 describes system.*, internal.* and apcore.* as namespaces; §6.6.1 restricts registration of IDs prefixed system.. Ownership of a prefix is what the reservation is for, and only the first segment can assert it: foo.system.bar is not in the system namespace and impersonates nothing.

Segments after the first are unrestricted, including when they equal a reserved word: executor.schema.validate, orchestrator.core.dispatch and api.acl.check are legal IDs. They claim no namespace and shadow nothing, so rejecting them would buy no security and cost a large part of the natural naming space. First-segment enforcement is sufficient against threat T8, impersonation of system.* (security-considerations.md §2.1).

conflict_detection:
  when: [Module scanning, Module registration, Dynamic loading]

  types:
    duplicate_id:
      description: "Same ID already exists"
      action: "error"

    reserved_word:
      description: "Uses reserved word"
      action: "error"

    case_collision:
      description: "Only differs in case (cross-language conflict risk)"
      action: "warning"

2.7 ID Formal Grammar

The formal definition of Canonical ID uses EBNF notation. All implementations MUST reject IDs that do not conform to this grammar.

(* apcore Canonical ID EBNF *)

canonical_id    = segment , { "." , segment } ;
segment         = lower_alpha , { lower_alpha | digit | "_" } ;
lower_alpha     = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i"
                | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r"
                | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" ;
digit           = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;

(* Constraints *)
(* 1. canonical_id total length MUST NOT exceed 192 characters *)
(* 2. the FIRST segment MUST NOT be a reserved word (§2.5, §2.6 step 2), except for an ID *)
(*    registered through register_internal() (§6.6.1); later segments are unrestricted *)
(* 3. segment MUST NOT start with a digit (guaranteed by production) *)
(* In multi-class discovery mode, module_id = base_id "." class_segment where *)
(* class_segment is the snake_case-converted class name. The full ID must still *)
(* conform to the canonical_id production above. *)

Equivalent regular expression for the production (constraints 1 and 2 are checked separately): ^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$


3. Directory Specification

3.1 Standard Directory Structure

Implementations MUST follow the directory structure below. The nesting depth under extensions/ directory (not including extensions/ itself) MUST NOT exceed 8 levels.

{project_root}/
├── extensions/                   # Extensions directory (max depth: 8 levels)
│   ├── api/                      # Level 1 grouping: API layer
│   │   ├── validator/            # Level 2 grouping: Validators
│   │   │   ├── http_json_schema.{ext}
│   │   │   ├── http_json_schema_meta.yaml
│   │   │   └── ...
│   │   ├── parser/               # Level 2 grouping: Parsers
│   │   └── handler/              # Level 2 grouping: Handlers
│   │
│   ├── orchestrator/             # Level 1 grouping: Orchestration engine layer
│   │   ├── engine/               # Level 2 grouping: Engine
│   │   ├── validator/
│   │   └── parser/
│   │
│   └── executor/                 # Level 1 grouping: Executor layer
│       ├── handler/
│       └── validator/
│
├── schemas/                      # Schema definition directory (YAML)
│   └── {canonical_id}.schema.yaml
│
├── acl/                          # Access control configuration directory
│   └── {scope}_acl.yaml
│
└── apcore.yaml                   # Framework configuration file

3.2 Layer Definitions

Level 1 Grouping Responsibility Typical Level 2 Groupings
api API entry layer, handles external requests validator, parser, handler
orchestrator Orchestration engine layer, task scheduling and process control engine, validator, parser, scheduler
executor Executor layer, actual business execution handler, validator, connector
common Common components util, middleware, decorator

3.3 ID Generation Rules

id_generation:
  # Directory path → Canonical ID
  source: "directory_path"

  # Exclusions
  exclude:
    - extensions_root_dir    # Exclude "extensions/"
    - file_extension      # Exclude ".py", ".rs", etc.

  # Example
  example:
    input: "extensions/executor/validator/db_params.py"
    output: "executor.validator.db_params"

Implementations MUST NOT follow symbolic links (symlinks) in default mode. If symbolic link support is needed, it MUST be enabled through explicit configuration:

# apcore.yaml
extensions:
  follow_symlinks: false  # Default value, MUST NOT follow
  • When symbolic link following is enabled, implementations MUST detect symbolic link loops
  • The resolved path of symbolic links MUST still be within the extensions_root scope

3.5 Hidden File Handling

Implementations MUST ignore the following files and directories during module scanning:

Pattern Example Description
Starts with . .git/, .env Hidden files/directories
Starts with _ _internal/, _test.py Internal files/directories
__pycache__/ — Python cache
node_modules/ — Node.js dependencies
*.pyc — Python compiled files

The five rows above are built in and are not configurable: an implementation applies them whatever the configuration says.

Implementations MUST additionally apply extensions.ignore_patterns, matched as a glob-dialect value under §9.2.3 (Algorithm A25) against the entry name — one path segment, case-sensitively. The two lists are a union: a configured pattern adds to the built-in rows and cannot remove one.

3.6 Scanning Algorithm

Implementations MUST scan the extensions directory according to the following algorithm:

Algorithm: scan_extensions(extensions_root, config)

Input:
  extensions_root — Extensions root directory path
  config          — Scan configuration (follow_symlinks, ignore_patterns, max_depth)

Output:
  modules — List of [(file_path, canonical_id)]

Steps:
  1. If extensions_root doesn't exist or is not a directory → Throw CONFIG_ERROR
  2. modules ← []
  3. Recursively traverse extensions_root:
     For each entry (file or directory):
       a. If entry name matches a built-in row of §3.5, or matches any
          config.ignore_patterns entry under A25 (§9.2.3) → Skip
       b. If entry is a symbolic link:
          - If config.follow_symlinks == false → Skip
          - Otherwise resolve it to its canonical real path. If that path is not
            inside the canonical extensions_root → Skip and issue a warning
            (D-94). Otherwise continue with the resolved target (D-127).
       c. If entry is a directory:
          - If current depth >= config.max_depth (default 8) → Skip and issue warning
          - If its canonical real path has already been visited → Skip (D-127:
            this is what terminates a directory cycle and what stops an aliased
            directory being discovered twice)
          - Otherwise → Recurse into it
       d. If entry is a file and extension belongs to supported_extensions:
          - real ← canonical real path of entry.path
          - If real has already been recorded → Skip (D-127: recorded once)
          - canonical_id ← directory_to_canonical_id(real, extensions_root)
          - If canonical_id passes validation → Append (entry.path, canonical_id) to modules
          - If validation fails → Log warning
  4. Perform detect_id_conflicts batch detection on modules
  5. Return modules

Complexity: O(n), where n is the number of filesystem entries

A symlink is recorded once, under its real path (D-127). With follow_symlinks: true, the real target inside the root is recorded once; file identity, module ID and visited-directory tracking are all keyed on the canonical real path:

  1. Containment is checked on the resolved real path, and deduplication uses that same path. A check on the link and a dedupe on the link are two different keys, and only the real path answers "is this the same file".
  2. The module ID is derived from the canonical real path relative to the root, never from whichever alias the traversal reached first. An alias-derived ID would depend on directory iteration order, which is not stable across filesystems or platforms.

Directory symlinks are covered by the same key: an aliased directory whose real path was already visited is skipped, which both prevents the duplicate and terminates a cycle.

Rationale: keyed on the link path, one file reached by two paths becomes two modules with different IDs — a duplicate registration that step 4's detect_id_conflicts cannot catch because the IDs differ.

Not in scope: TOCTOU. A single canonical check cannot stop a party who can replace the link between the scan and the load. Whether a file-handle or directory-descriptor level defence is warranted depends on whether the extensions root is attacker-writable; that threat-model question is assessed in Security Considerations §2.8.


4. Schema Specification

4.1 Overview

All modules MUST define input_schema and output_schema to support: - LLM tool calling (MCP compatible) - Runtime data validation - Automatic API documentation generation - Cross-language interoperability

4.2 Schema Format

The input_schema and output_schema MUST use JSON Schema Draft 2020-12. The *.schema.yaml file is a module document containing those Schemas. Its top-level $schema identifies the APCore module document Schema. A $schema inside an input or output Schema identifies that Schema's dialect, https://json-schema.org/draft/2020-12/schema.

Compliance Requirements:

Requirement Level Description
Core vocabulary MUST Identifiers, references, and definitions such as $id, $schema, $ref, and $defs
Applicator vocabulary MUST Subschema application such as properties, additionalProperties, items, and anyOf
Validation vocabulary MUST Assertions such as type, required, minimum, pattern, and enum
Module document $schema SHOULD Declare the APCore module document Schema URI at the top of the file
APCore extensions MUST Use the x- prefix for custom extensions. See §4.3.
additionalProperties SHOULD Explicitly set additionalProperties: false for a closed input object

See Type Mapping §17.2 for the keyword support and rejection rules. Use a type array such as ["string", "null"], or an anyOf branch with {"type": "null"}, to accept null. nullable is an OpenAPI 3.0 keyword and has no validation effect in Draft 2020-12. The unknown-keyword rule in §4.15 applies to it.

# schemas/executor/validator/db_params.schema.yaml

$schema: "https://apcore.apstack.org/schemas/module-schema.schema.json"
version: "1.0.0"
module_id: "executor.validator.db_params"

# Module description (LLM readable)
description: |
  Validates database operation parameters, checks table name format and SQL syntax safety.
  Suitable for pre-validation before executing SQL.

# Input Schema
input_schema:
  type: object
  properties:
    table:
      type: string
      pattern: "^[a-z][a-z0-9_]*$"
      description: "Target database table name"
      x-llm-description: "Database table name, only lowercase letters, numbers, and underscores allowed, must start with a letter"
      x-examples: ["user_info", "order_detail", "product_catalog"]

    sql:
      type: string
      description: "SQL statement"
      x-llm-description: "SQL statement to execute, will undergo safety checks"
      x-constraints: "Dangerous operations like DROP, TRUNCATE are not allowed"

    timeout:
      type: integer
      default: 30
      minimum: 1
      maximum: 300
      description: "Timeout in seconds"

  required: [table, sql]
  additionalProperties: false

# Output Schema
output_schema:
  type: object
  properties:
    valid:
      type: boolean
      description: "Whether validation passed"

    message:
      type: string
      description: "Validation result message"

    errors:
      type: array
      items:
        type: object
        properties:
          field:
            type: string
          code:
            type: string
          message:
            type: string
      description: "Error details list"

    warnings:
      type: array
      items:
        type: string
      description: "Warning messages"

  required: [valid]

# Error Schema (optional)
error_schema:
  type: object
  properties:
    code:
      type: string
      enum: [INVALID_TABLE, DANGEROUS_SQL, TIMEOUT, INTERNAL_ERROR]
    message:
      type: string
    details:
      type: object
  required: [code, message]

4.3 LLM Extension Fields

Field Type Description
x-llm-description string Dedicated description for LLM (see usage guide below)
x-examples array Example values to help LLM understand value range
x-constraints string Business constraint description
x-sensitive boolean Mark sensitive fields (e.g., passwords), LLM should not log

Relationship between description and x-llm-description

Field Audience Purpose
description All consumers (humans, AI, doc generators) Universal field description, exported to AI protocols as field description
x-llm-description AI/LLM only Use only when AI description needs to be significantly different from human description

Use Cases:

  • Security warnings: AI needs additional security constraint hints (e.g., "only SELECT statements allowed")
  • Usage guidance: Special behavior constraints when AI calls (e.g., "don't hard-code this value")
  • Semantic supplementation: description is concise for humans, but AI needs more context to fill correctly

Export Rules:

  • Adapters SHOULD prefer x-llm-description: If field has both description and x-llm-description, replace description with x-llm-description when exporting to AI protocols
  • If field has only description, export as-is
  • Strict mode export (§4.16) strips all x-* fields, always using description

Anti-pattern: Don't add x-llm-description to every field. For most fields, description is sufficient for both humans and AI, use x-llm-description only when there's a clear difference in needs.

x-constraints Usage Guidance

x-constraints is for business rules that JSON Schema keywords cannot express. Do not use it to duplicate what JSON Schema already provides natively:

Constraint Type Correct Approach Incorrect Approach
Number range "minimum": 0, "maximum": 100 "x-constraints": "Value must be 0-100"
String pattern "pattern": "^[A-Z]{3}$" "x-constraints": "Must be 3 uppercase letters"
Fixed options "enum": ["a", "b", "c"] "x-constraints": "One of a, b, or c"
Cross-field rule "x-constraints": "end_date must be after start_date" ✅ Correct use
Domain rule "x-constraints": "User must have verified email" ✅ Correct use

When a constraint can be expressed as a JSON Schema keyword (minimum, maximum, pattern, enum, minLength, maxLength, multipleOf), always prefer the keyword. x-constraints is the last resort for constraints that are inherently natural-language.

4.4 Module Behavior Annotations (Annotations)

Annotations are module-level behavior metadata that help AI/LLM make invocation decisions.

# Module behavior annotations specification
annotations:
  type: object
  properties:
    readonly:
      type: boolean
      default: false
      description: "Whether module is read-only (no side effects). true means no state modification."

    destructive:
      type: boolean
      default: false
      description: "Whether module has destructive operations. true means may delete/overwrite data."

    idempotent:
      type: boolean
      default: false
      description: "Whether module is idempotent. true means repeated calls with same parameters won't produce additional side effects."

    requires_approval:
      type: boolean
      default: false
      description: "Whether THIS MODULE requires human approval before execution. A module-level declaration, not the governance-effective value — see the note below. When an ApprovalHandler is configured, the Executor enforces this at runtime (see §7 Approval System)."

    discoverable:
      type: boolean
      default: true
      description: "Whether the module appears in enumeration surfaces (Registry.list(), manifest export, MCP tools/list). false hides the module from discovery while keeping it callable by ID — caller must already know the module ID. ephemeral.* modules SHOULD set discoverable: false (§2.5.1)."

    open_world:
      type: boolean
      default: true
      description: "Whether involves external systems. true means connects to external APIs/services/network."

    streaming:
      type: boolean
      default: false
      description: "Whether module supports streaming output. true means module can emit partial results progressively."

    cacheable:
      type: boolean
      default: false
      description: "Whether the module output can be cached. true means identical inputs produce identical outputs within cache_ttl."

    cache_ttl:
      type: integer
      default: 0
      description: "Suggested cache duration in seconds. 0 means no caching. Only meaningful when cacheable=true."

    cache_key_fields:
      type: array
      items:
        type: string
      default: null
      description: "Input fields that determine cache key. null means all input fields are used. Only meaningful when cacheable=true."

    paginated:
      type: boolean
      default: false
      description: "Whether the module returns paginated results. true means the module accepts pagination parameters (cursor/offset) and returns partial result sets."

    pagination_style:
      type: string
      default: cursor
      description: "Pagination strategy. Well-known values: 'cursor' (opaque continuation token), 'offset' (numeric offset+limit), 'page' (page-number-based). Custom strategies are allowed. Only meaningful when paginated=true."
      examples: [cursor, offset, page]

    extra:
      type: object
      additionalProperties: true
      default: {}
      description: "Open extension map for ecosystem-specific or vendor annotation metadata. Keys SHOULD use a `<namespace>.<name>` form (e.g. `mcp.category`, `cli.approval_message`, `a2a.skill_id`). The `core.*` namespace is RESERVED for future spec promotion. Wire-format rules in §4.4.1 are normative."

Annotations Design Principles:

Principle Description
All optional Use default values when not defined
Hints + Enforcement Most annotations are hints for AI; requires_approval can be enforced at runtime via the Approval System (§7)
Aligned with MCP Field design compatible with MCP ToolAnnotations
Extensible Can add new fields without breaking compatibility

requires_approval: false does not mean no approval will be required

The annotation is a module-level declaration: it says whether this module always needs a human. It is one of several sources, and §6.9 rows 3–5 compose them by union — an ACL rule carrying approval: required (§6.1.6), an ExecutionPolicy override, or gate_destructive can each require approval for a particular call on a module whose annotation says false. A client that reads the annotation and stops there under-warns.

The governance-effective value is call-site dependent, because the ACL condition that decides it reads what the call carries (§6.1.7). It is obtained from Executor.validate() (§7.9.5), which reports the same verdict the approval gate will enforce. The annotation describes the module; the preflight describes the call.

Ignoring this is not unsafe — the gate still fails closed and asks the human at execution time. What is lost is the client's ability to say in advance that a call will need approval, which is why the annotation is read before calling.

Why this is not a conditional tri-state. The module author cannot know the answer: it depends on the ACL the deployment loads and the policy it configures, none of which is visible when the annotation is written. A third value would have to be computed by the framework from the loaded governance config rather than declared — which is validate() under another name, on a field every consumer reads as a boolean.

AI usage of Annotations decision examples:

readonly=true         → AI can call safely, no confirmation needed
destructive=true      → AI should warn user before calling
idempotent=true       → AI can safely retry failed calls
requires_approval=true → AI must seek user consent; Executor enforces via ApprovalHandler (§7)
requires_approval=false → this MODULE asks for none; the CALL may still need one — preflight to find out (§7.9.5)
discoverable=false    → AI / orchestrator hides the module from enumeration surfaces (still callable by exact ID)
open_world=true       → AI knows this call involves external systems, may be slow
streaming=true        → AI knows this module emits partial results progressively
cacheable=true        → AI knows it can reuse previous results within cache_ttl
paginated=true        → AI knows to pass pagination params and expect partial results

4.4.1 Annotations Extension Field (extra) — Wire Format

ModuleAnnotations carries an open extension map under the field extra, used by ecosystem packages and vendor integrations to attach metadata that is not part of the core annotation set. The on-the-wire JSON shape is normative across all SDK implementations.

Producer rules:

  1. Implementations MUST serialize annotation extension data as a nested JSON object under the key extra.
  2. Implementations MUST NOT flatten extension keys onto the annotations root object.
  3. Producers MUST NOT emit both a nested extra.k and a top-level k for the same key in the same payload.
  4. When extra is empty, producers SHOULD emit "extra": {} rather than omitting the field, to keep the wire shape stable across SDKs.

Consumer rules:

  1. Consumers MUST accept the canonical nested form {"extra": {...}}.
  2. Consumers MAY accept top-level overflow keys (i.e. unknown keys at the annotations root) as a compatibility shim. Such keys MUST be normalized into the nested extra object on deserialize and re-serialized in nested form.
  3. When a deserialization input contains BOTH a nested extra.k and a top-level k with the same key, the nested value MUST win.
  4. When extra is absent or null, consumers MUST treat it as an empty object.

Key naming:

  1. extra keys SHOULD use the form <namespace>.<name>, where <namespace> identifies the consuming subsystem or vendor (e.g. mcp.category, cli.approval_message, a2a.skill_id, vendor.acme.priority).
  2. The core.* namespace is RESERVED for future promotion of extra keys into standard Annotations fields.
  3. Dots in extra keys are part of the literal key string. Implementations MUST NOT interpret a.b.c as a nested path on either serialize or deserialize.
  4. Extension keys MUST NOT collide with any canonical field name listed in §4.4. If a collision is observed during deserialization, the canonical field MUST win and the extension key MUST be discarded with a warning.

Promotion to standard fields:

  1. When a community-adopted extra key is promoted to a standard Annotations field in a future spec version, that change MUST go through one MINOR deprecation cycle in which both forms (the new standard field AND the extra.<old_key> entry) are accepted by consumers, before the extra form is removed.

Conformance: Cross-language behavior is locked by ../../conformance/fixtures/annotations_extra_round_trip.json.

Example (canonical wire form):

{
  "readonly": true,
  "destructive": false,
  "idempotent": true,
  "requires_approval": false,
  "open_world": true,
  "streaming": false,
  "cacheable": false,
  "cache_ttl": 0,
  "cache_key_fields": null,
  "paginated": false,
  "pagination_style": "cursor",
  "discoverable": true,
  "extra": {
    "mcp.category": "tools",
    "cli.approval_message": "Are you sure?"
  }
}

4.5 Module Usage Examples (Examples)

Examples provide concrete input/output examples to help AI/LLM understand complex modules more accurately.

# Module examples specification
examples:
  type: array
  items:
    type: object
    properties:
      title:
        type: string
        description: "Example title"

      description:
        type: string
        description: "Example description (optional)"

      inputs:
        type: object
        description: "Example input (must conform to input_schema)"

      output:
        type: object
        description: "Example output (optional, conforms to output_schema)"
    required: [title, inputs]

Example:

examples:
  - title: "Send plain text email"
    description: "Send plain text email via SMTP"
    inputs:
      to: "[email protected]"
      subject: "Hello"
      body: "World"
    output:
      success: true
      message_id: "msg_123"

  - title: "Send HTML email"
    description: "Send HTML format email to multiple recipients via SMTP"
    inputs:
      to: ["[email protected]", "[email protected]"]
      subject: "Notification"
      html: "<h1>Hello</h1>"
      smtp_host: "smtp.example.com"
      smtp_port: 587
    output:
      success: true
      message_id: "msg_456"

Examples Design Principles:

Principle Description
All optional Not providing examples doesn't affect module functionality
Inputs must be valid inputs must conform to input_schema
Multi-scenario coverage Recommend covering typical usage and edge cases
Aligned with Anthropic Similar to Anthropic input_examples, improves LLM understanding

4.6 Module Extension Metadata (Metadata)

Metadata is a completely open dict for custom extensions beyond the framework protocol.

# Module metadata specification
metadata:
  type: object
  additionalProperties: true
  description: "Free extension metadata, framework doesn't validate content"

Common usage examples:

metadata:
  # Performance hints
  cost_per_call: 0.001
  avg_latency_ms: 500
  max_latency_ms: 5000

  # Data sensitivity
  data_sensitivity: ["PII"]

  # Operations info
  owner: "email-team"
  sla: "99.9%"
  documentation_url: "https://docs.example.com/send-email"

  # Custom business fields
  billing_category: "communication"

Recommended AI Metadata Conventions:

When modules are consumed by AI agents, the following metadata keys help agents understand when, how, and at what cost to use a module. These are conventions, not enforced by the framework.

Intent Hints — Help agents decide whether to use this module:

metadata:
  # AI intent hints (all optional, free-form strings)
  x-when-to-use: "Use when the user wants to send a transactional email (order confirmation, password reset, etc.)"
  x-when-not-to-use: "Do not use for marketing/bulk emails; use the bulk-email module instead"
  x-common-mistakes: "Forgetting to set reply_to; passing HTML in plain_text field"
  x-workflow-hints: "Call validate-email module first to verify recipient address exists"

Planning Hints — Help agents build multi-step plans:

metadata:
  # Preconditions: what must be true before calling this module
  x-preconditions:
    - "User must be authenticated"
    - "module.validate_card must have succeeded"

  # Postconditions: what will be true after calling this module
  x-postconditions:
    - "Payment record created in database"
    - "Confirmation email queued"

  # Side effects: external state changes caused by this module
  x-side-effects:
    - "Charges credit card via Stripe API"
    - "Writes to orders table"

Performance & Cost Hints — Help agents make cost-aware decisions:

metadata:
  # Cost estimation (units are implementation-defined, e.g., USD)
  x-cost-per-call: 0.001
  x-avg-latency-ms: 500
  x-max-latency-ms: 5000

  # SLA targets (for monitoring; enforcement is an ecosystem concern)
  x-sla:
    availability: 0.999
    p95_latency_ms: 500

Trust & Verification Hints — Help agents assess output reliability:

metadata:
  # Output source: where does the data come from?
  x-output-source: "database"    # database | api | generated | cached | computed
  # Verification hint: how to cross-check the output
  x-verification-hint: "Cross-check amounts with accounting.get_balance"

Routing & Verification Hints — Help orchestrators choose the right model, inject required state, and preflight destructive calls:

metadata:
  # Reasoning demand: hint to upstream model routers for tier selection
  x-reasoning-demand: medium     # one of: low | medium | high

  # Context keys this module reads from context.data
  # (does NOT include framework-owned Context fields like trace_id, caller_id)
  x-required-context-keys:
    - user_preferences
    - billing_account_id

  # Dry-run capability: module-level signal that Executor.validate() is meaningful
  x-supports-dry-run: true
Key Category Purpose
x-when-to-use Intent Positive guidance: scenarios where this module is the right choice
x-when-not-to-use Intent Negative guidance: scenarios where a different module should be used
x-common-mistakes Intent Known pitfalls that AI agents (and humans) frequently encounter
x-workflow-hints Intent Suggested pre/post steps or related modules in a typical workflow
x-preconditions Planning What must be true before calling this module
x-postconditions Planning What will be true after successful execution
x-side-effects Planning External state changes caused by this module
x-cost-per-call Performance Estimated cost per invocation
x-avg-latency-ms Performance Average execution latency in milliseconds
x-max-latency-ms Performance Maximum expected latency in milliseconds
x-sla Performance SLA targets (availability, latency percentiles)
x-output-source Trust Data provenance: database, api, generated, cached, computed
x-verification-hint Trust How to cross-check the output for correctness
x-reasoning-demand Routing One of low/medium/high. Hint of the minimum reasoning capability the calling agent needs; consumed by upstream model routers for tier selection.
x-required-context-keys Planning Array of context.data key names the module reads. Does not include framework-owned Context fields (trace_id, caller_id, etc.).
x-supports-dry-run Verification Boolean. Module-level signal that Executor.validate() (see §12.2) is meaningful for this module — i.e., the module overrides preflight() and/or has no destructive side-effects pre-execute.

Metadata Design Principles:

Principle Description
Completely free Framework doesn't validate or interpret metadata content
Can be used by middleware Middleware can read metadata for custom logic
Doesn't affect execution metadata doesn't participate in module execution flow
Open extension When custom needs arise, metadata is the first landing spot

4.7 Three-layer Metadata Summary

┌───────────────────────────────────────────────────────────┐
│                  Module Metadata Three-layer Design        │
├───────────────────────────────────────────────────────────┤
│                                                           │
│  ┌─────────────────────────────────────────────────┐     │
│  │  Core Layer (Required)                          │     │
│  │  input_schema / output_schema / description     │     │
│  │  → AI understands "what" the module does        │     │
│  └─────────────────────────────────────────────────┘     │
│                          ↓                                │
│  ┌─────────────────────────────────────────────────┐     │
│  │  Annotation Layer (Optional, type-safe)         │     │
│  │  annotations / examples / name / tags / version │     │
│  │  → AI understands "how to use" the module       │     │
│  └─────────────────────────────────────────────────┘     │
│                          ↓                                │
│  ┌─────────────────────────────────────────────────┐     │
│  │  Extension Layer (Optional, free dict)          │     │
│  │  metadata: dict[str, Any]                       │     │
│  │  → Custom extension needs (framework unconstrained)  │
│  └─────────────────────────────────────────────────┘     │
│                                                           │
└───────────────────────────────────────────────────────────┘

4.8 Description and Documentation Field Specification

4.8.1 Design Principles

apcore adopts the Progressive Disclosure design pattern, referencing the Claude Agent Skills standard, splitting module information into brief description and detailed documentation:

Field Required Length Limit Markdown Purpose
description Required No default limit; ≤200 characters recommended (§9.1.2) No Brief module function description for AI quick matching and understanding
documentation Optional No default limit; ≤5000 characters recommended (§9.1.2) Yes Detailed documentation including usage scenarios, constraints, configuration requirements

Core Philosophy:

AI Module Discovery Flow:
├─ Phase 1: Module Discovery
│   └─ Read all modules' description (≤200 chars)
│   └─ Quickly determine candidate modules
│
├─ Phase 2: Invocation Decision
│   └─ Read candidate modules' Schema + Annotations
│   └─ Optionally read documentation (detailed info)
│   └─ Confirm parameters and behavior characteristics
│
└─ Phase 3: Execution Preparation
    └─ Read detailed documentation (documentation/docstring)
    └─ Learn detailed usage and examples

Standard Correspondence:

apcore Claude Skill OpenAPI JSON Schema
description description summary title
documentation instructions description description

4.8.2 Description Field

MUST: - Recommended length: ≤200 characters (approx. 100 Chinese characters). Not enforced unless validation.binding.description_max_length is set (§9.1.2) - Content requirements: Explain "what it does" + "when to use" + "key characteristics" - Avoid redundancy: Parameter info already defined in Schema need not be repeated

SHOULD: - Highlight function verbs and usage scenarios - Explain key behavior characteristics (e.g., idempotency, side effects) - Single line or brief paragraph (≤3 lines)

SHOULD NOT: - Include detailed usage examples (put in documentation or docstring) - Repeat parameter lists from Schema - Exceed 200 characters

Recommended Format:

# Format 1: Single-line concise description (recommended)
description = "Send email to specified recipients. Uses SMTP protocol, non-idempotent operation, requires mail server configuration."

# Format 2: Structured brief description (suitable for complex modules)
description = """Send email to specified recipients.
Sends text/HTML emails via SMTP, non-idempotent operation. Use cases: notifications, verification codes, reports."""

YAML format:

module_id: "executor.email.send_email"
description: "Send email to specified recipients. Uses SMTP protocol, non-idempotent operation, requires mail server configuration."

4.8.3 Documentation Field

The documentation field is optional, used to provide detailed module documentation. Simple modules can use only the description field.

SHOULD use documentation scenarios: - Module has complex configuration requirements - Need to explain important usage constraints or limitations - Have multiple usage scenarios to explain - Need to provide detailed error handling explanation

Format Requirements: - Supports Markdown format - Recommended length: ≤5000 characters. Not enforced unless validation.binding.documentation_max_length is set (§9.1.2) - Recommend using structured format (headings, lists, etc.)

Recommended Content Structure:

## Functionality
Brief explanation of module's detailed functionality

## Configuration Requirements
- Required configuration items
- Dependent external services

## Usage Scenarios
- Scenario 1: ...
- Scenario 2: ...

## Limitations and Constraints
- Performance limits (e.g., rate limits)
- Data size limits
- Other constraints

## Notes
Important usage considerations

Example:

class SendEmailModule(Module):
    description = "Send email to specified recipients. Uses SMTP protocol, non-idempotent operation, requires mail server configuration."

    documentation = """
# Functionality
Sends emails via SMTP protocol, supports plain text and HTML formats.

## Configuration Requirements
- Must configure SMTP server info in apcore.yaml
- Need to provide valid SMTP authentication credentials

## Usage Scenarios
- Send notification emails
- Send verification codes
- Send reports

## Limitations
- Gmail: 500 emails/day
- Attachment size: ≤25MB
- Timeout: 30 seconds

## Error Handling
Email send failures throw EmailSendError exception with detailed error info.
"""

YAML format:

module_id: "executor.email.send_email"
description: "Send email to specified recipients. Uses SMTP protocol, non-idempotent operation, requires mail server configuration."
documentation: |
  # Functionality
  Sends emails via SMTP protocol, supports plain text and HTML formats.

  ## Configuration Requirements
  - Must configure SMTP server info in apcore.yaml
  - Need to provide valid SMTP authentication credentials

  ## Usage Scenarios
  - Send notification emails, verification codes, reports

  ## Limitations
  - Gmail: 500 emails/day
  - Attachment size: ≤25MB

4.8.4 Relationship with Docstring

apcore modules can use three forms of documentation simultaneously:

Location Purpose Audience Format
description Quick module understanding AI module discovery phase Plain text, ≤200 chars recommended
documentation Detailed usage documentation AI invocation decision phase Markdown, ≤5000 chars
Python docstring Code-level documentation Developers, IDE reStructuredText/Markdown

Priority and Usage Recommendations:

  1. description (required): All modules must define
  2. documentation (recommended): Complex modules should define
  3. docstring (optional): For developer reading, IDE can display

Example:

class SendEmailModule(Module):
    """Email sending module (Python docstring, for developers to read)

    This is Python docstring for developers to view in IDE.
    Can include more detailed technical implementation notes, source code comments, etc.
    """

    # Used in AI module discovery phase
    description = "Send email to specified recipients. Uses SMTP protocol, non-idempotent operation, requires mail server configuration."

    # Used in AI invocation decision phase (optional)
    documentation = """
    # Functionality
    Sends emails via SMTP protocol, supports plain text and HTML formats.

    ## Configuration Requirements
    ...
    """

4.8.5 Backward Compatibility

A module that declares only description is complete: documentation is optional and absent unless declared. A description longer than the recommended 200 characters is kept as declared. An implementation MAY log a warning suggesting that the detail move to documentation; whether a long description is rejected is governed by §9.1.2 alone.

Migration Recommendations:

For existing long descriptions (>200 chars): 1. Extract first 200 chars as new description 2. Move complete content to documentation field 3. Or manually rewrite as brief description + detailed documentation

4.8.6 AI Usage Flow Example

User request: "Send a welcome email to new user"

Step 1: Module Discovery (read all descriptions)
  → Scan 100 modules' descriptions (total ~20,000 characters)
  → Identify candidate module: executor.email.send_email
  → description: "Send email to specified recipients. Uses SMTP protocol, non-idempotent operation..."

Step 2: Invocation Decision (read Schema + Annotations + documentation)
  → input_schema: {to, subject, body}
  → output_schema: {success, message_id}
  → annotations: {requires_approval: true, open_world: true}
  → documentation: "# Functionality\nSends emails via SMTP protocol..."
  → Decision: User confirmation needed

Step 3: Execution Preparation
  → Learn configuration requirements: Need SMTP server configuration
  → Learn limitations: Gmail 500 emails/day
  → Prepare parameters: {"to": "[email protected]", ...}

4.8.7 Performance Impact

Token consumption comparison:

Approach Module Discovery Phase Invocation Decision Phase Total
Progressive Disclosure (recommended) ~20K tokens
(100 modules × 200 chars)
~5-10K tokens
(1-2 candidate modules × 5000 chars)
~25-30K
Load all full docs ~500K tokens
(100 modules × 5000 chars)
0 ~500K

Advantages: - Reduce 94% of initial token consumption - Speed up module discovery (load only necessary info) - Load detailed info on-demand (load only candidate modules' documentation) - Better AI performance and response speed


4.9 Schema Loading Strategy

# apcore.yaml
schema:
  # Loading strategy
  strategy: "yaml_first"  # yaml_first | native_first | yaml_only

  # yaml_first: Load from YAML first, native implementation can override
  # native_first: Prefer native implementation, YAML as fallback
  # yaml_only: Only use YAML (pure cross-language scenario)

  # Directory the YAML schema files are resolved against
  root: "./schemas"

  # Maximum $ref resolution depth
  max_ref_depth: 32

These three keys are the whole of the schema namespace: apcore/schemas/defaults.schema.json declares it additionalProperties: false, so any other key is a configuration error.

Strictness and type coercion are not configurable here. Whether an undeclared property is rejected is a property of the contract (additionalProperties, §4.15), not of the host's configuration — a module's input contract must mean the same thing regardless of who loads it.

4.10 Language-specific Schema Implementations

Each language SDK MUST provide a native schema implementation that supports JSON Schema Draft 2020-12 validation and YAML schema loading. The specific library choices are left to SDK implementers.

4.11 Schema References ($ref)

Implementations MUST support $ref references and MUST resolve according to the following algorithm. Implementations MUST reject circular references — a $ref → $ref chain that never reaches a schema body — and MUST preserve self-references as lazy $ref nodes rather than inlining or rejecting them. §4.15 defines the distinction; it is the sole authority on which re-entry is which.

Algorithm: resolve_ref(ref_string, current_file, schemas_dir, visited_refs,
                       depth, from_ref_chain)

Input:
  ref_string     — $ref value (e.g., "./common/error.schema.yaml#/definitions/ErrorDetail")
  current_file   — Current Schema file path
  schemas_dir    — schemas root directory
  visited_refs   — Set of refs already on the resolution stack. Seeded by the
                   caller with the aliases of the document being resolved
                   ("#", "#/", and the document's own $id), so a reference
                   naming that document is lazy from the FIRST encounter
  depth          — Number of $ref hops taken so far (starts at 0)
  from_ref_chain — True when this call was reached because the previous node
                   was itself a bare $ref, i.e. no schema body was traversed
                   between the two. False on any structural descent
                   (properties / items / additionalProperties / a combinator
                   branch)

Output:
  resolved_schema — Resolved Schema object, or the $ref node unchanged when
                    the reference is a self-reference (see §4.15)

Preconditions:
  - ref_string is not empty

Steps:
  1. If ref_string ∈ visited_refs:
     a. If from_ref_chain → Throw SCHEMA_CIRCULAR_REF error
        (a $ref → $ref chain consumes no instance and cannot terminate)
     b. Otherwise → Return { "$ref": ref_string } unchanged, preserving any
        sibling keys. This is a legal self-reference; the schema-to-native
        converter MUST bind it lazily against the document root at
        validation time (§4.15)
  2. If depth >= schema.max_ref_depth → Throw SCHEMA_MAX_DEPTH_EXCEEDED error
  3. visited_refs ← visited_refs ∪ {ref_string}
  4. Parse ref_string into (file_part, json_pointer):
     a. If starts with "#" → file_part = current_file, json_pointer = ref_string[1:]
        Resolve the pointer against the FILE ROOT first; if it does not resolve
        there, fall back to the schema node being resolved (the `input_schema` /
        `output_schema` document itself). BOTH layouts are addressable, and an
        implementation MUST support both (D-104). The fallback is available ONLY
        while resolution is still inside the document the schema node belongs to;
        once a reference has been followed into another document, a local
        pointer that does not resolve in THAT document MUST throw
        SCHEMA_NOT_FOUND (D-124).
     b. If contains "#" → Split by "#" into file_part and json_pointer
     c. If starts with "apcore://" → Convert to file path under schemas_dir
     d. Otherwise → file_part is path relative to current_file directory
  5. schema_doc ← Load and parse YAML/JSON file for file_part
  6. resolved ← Locate target node in schema_doc using json_pointer
  7. If resolved is itself a bare $ref → Recursively call resolve_ref(...) with
     depth + 1 and from_ref_chain = True
  8. Walk resolved's children. For each nested $ref reached by structural
     descent, call resolve_ref(...) with depth + 1 and from_ref_chain = False
  9. Return resolved

Complexity: O(d), where d is reference depth (bounded by schema.max_ref_depth,
default 32)

The base document for a local #/… pointer (D-104, D-124). Two layouts are addressable: a definitions: / $defs: block at the top level of the schema file, beside input_schema (as in the example below), and a $defs block nested inside the schema node itself. The file root is tried first. The two lookups cannot collide, since a pointer either resolves at the file root or it does not. The node fallback is scoped to the document the schema node belongs to: a local pointer inside an external document resolves in that document or raises SCHEMA_NOT_FOUND, and never falls back to the calling module's schema node. Rationale: a cross-document fallback binds a reference to a definition its author never wrote, and because §10.6 reads x-sensitive from the resolved schema, it can replace a field marked sensitive with one that is not, so the value is logged in plaintext.

Depth is consumed by $ref hops only. Steps 7 and 8 both increment depth because both follow a reference; ordinary structural descent into properties or items does not. Exhausting the cap is a distinct condition from an actual cycle and MUST raise SCHEMA_MAX_DEPTH_EXCEEDED, not SCHEMA_CIRCULAR_REF.

Supports cross-file references for Schema reuse:

schema_reference:
  # Reference formats
  formats:
    # Local reference (same file)
    local: "#/definitions/ErrorDetail"

    # Cross-file reference (relative path)
    relative: "./common/error.schema.yaml#/definitions/ErrorDetail"

    # Cross-file reference (Canonical ID)
    canonical: "apcore://common.types.error/ErrorDetail"

  # Reference resolution rules
  resolution:
    - "Local references look up in current file first"
    - "Relative paths are relative to current schema file directory"
    - "Canonical ID references look in schemas/ directory"

  # Example
  example:
    # schemas/executor/validator/db_params.schema.yaml
    input_schema:
      type: object
      properties:
        table:
          type: string
        options:
          $ref: "./common/db_options.schema.yaml#/definitions/DBOptions"

    # Common definitions
    definitions:
      ErrorDetail:
        type: object
        properties:
          field: { type: string }
          code: { type: string }
          message: { type: string }

4.12 Schema Version Evolution

schema_evolution:
  # Compatibility rules
  backward_compatible:
    allowed:
      - "Add optional field (with default value)"
      - "Relax field constraints (e.g., reduce minLength)"
      - "Add enum options"
    forbidden:
      - "Remove required field"
      - "Change field type"
      - "Tighten field constraints"
      - "Remove enum options"

  # Version declaration
  versioning:
    in_schema: true
    format: "semver"
    example:
      version: "1.1.0"
      previous_version: "1.0.0"
      changes:
        - type: "added"
          field: "options.retry_count"
          description: "Added retry count configuration"

  # Deprecated field marking
  deprecation:
    marker: "x-deprecated"
    format:
      x-deprecated:
        since: "1.1.0"
        removal: "2.0.0"
        replacement: "options.max_retries"
        message: "Please use options.max_retries instead"

4.13 Annotation Conflict Rules

When both YAML metadata file (*_meta.yaml) and code define Annotations, conflicts MUST be resolved by the following priority:

  1. YAML metadata file (highest priority) — Operations teams can override behavior annotations without modifying code
  2. Explicit definition in code (secondary priority) — Developer defines on module class
  3. Default values (lowest priority) — Default values provided by framework

Implementations MUST merge rather than replace when loading: If YAML only defines readonly: true, other fields MUST retain values from code or defaults.

4.14 Schema Validation Error Format

When Schema validation fails, implementations MUST serialize SCHEMA_VALIDATION_ERROR with the details.errors structure defined in §8.1. The error_details_shape conformance fixture exercises this format through the SDKs' public execution entry points.

4.15 Edge Case Handling

Implementations MUST handle Schema edge cases according to the following table:

Scenario Behavior Level
$ref depth exceeds schema.max_ref_depth Throw SCHEMA_MAX_DEPTH_EXCEEDED MUST
$ref target path doesn't exist (404) Throw SCHEMA_NOT_FOUND MUST
Empty Schema {} Treat as type: object, allow any properties MUST
YAML/JSON syntax error Throw SCHEMA_PARSE_ERROR MUST
Unknown JSON Schema keyword (e.g., x-custom) Ignore (forward compatible) MUST
Self-reference — a $ref re-entered after descending through properties / items / a combinator Preserve the $ref as a lazy reference; MUST NOT throw MUST
Circular reference — a $ref → $ref chain that re-enters itself without reaching a schema body (A → B → A) Throw SCHEMA_CIRCULAR_REF MUST
required field is empty array [] Treat as no required fields MUST
enum value contains null Allow, null is valid enum value MUST
Cross-file $ref loading timeout Throw SCHEMA_PARSE_ERROR (cause: timeout) SHOULD
A value does not satisfy a recognised format Accept the value. Raising SCHEMA_VALIDATION_ERROR is forbidden; emitting a warning is SHOULD MUST
format names a term the implementation does not recognise Collect as an annotation and pass silently MUST

format is an annotation, and type-mapping §11.1 is its sole authority. The two rows above restate its consequence for edge-case handling: an unsatisfied format does not behave like an unsatisfied pattern. §11.1 carries the recognised-format list, the warning requirement, and the rule that a binding is expressed with pattern or enum rather than with format.

Self-reference vs. circular reference

A $ref that re-enters a reference already on the resolution stack is not automatically an error. JSON Schema 2020-12 §8.2.3 uses exactly that shape to express recursive data structures — tree nodes, nested comment threads, linked lists — and the Schema System hardening requirement "Recursive Schema Support" (features/schema-system.md) requires implementations to support them. The two cases MUST be distinguished by how the reference was re-entered:

  • Self-reference (legal). The reference was re-entered after descending through a schema body — a properties entry, items, additionalProperties, or a combinator branch. Every hop consumes one level of the instance, so resolution terminates as soon as the data does. The resolver MUST leave the $ref node in place rather than inlining the target again, and the schema-to-native converter MUST bind it lazily (resolving it at validation time against the document root). Implementations MUST NOT throw SCHEMA_CIRCULAR_REF for this case.
  • Circular reference (illegal). The reference was re-entered along a chain in which every hop is itself a bare $ref, so resolution never reaches a schema body and consumes no instance. Such a chain cannot terminate and asserts nothing. Implementations MUST throw SCHEMA_CIRCULAR_REF.

A reference naming the document being resolved — #, #/, or the document's own $id — is a self-reference by definition and MUST be treated as lazy from the first encounter, so a recursive schema is never inlined even once.

Example — legal self-reference (lazy $ref, no error):

$id: TreeNode
type: object
required: [value]
properties:
  value: { type: string }
  children:
    type: array
    items:
      $ref: "#"      # re-entered through properties → items: a recursive structure

Resolution returns the schema unchanged: items still holds {$ref: "#"}, which the converter binds to the root at validation time.

Example — illegal circular reference (SCHEMA_CIRCULAR_REF):

# schemas/user.schema.yaml
$ref: "./team.schema.yaml#/definitions/team"

# schemas/team.schema.yaml
definitions:
  team:
    $ref: "./user.schema.yaml"  # $ref → $ref, no schema body in between

Behavior: maintain a reference path stack in resolve_ref(). On a duplicate entry, throw SCHEMA_CIRCULAR_REF when the duplicate was reached along a $ref → $ref chain, and emit a lazy $ref otherwise.

4.16 Strict Mode Export

OpenAI and Anthropic's strict: true mode requires JSON Schema to satisfy additional constraints. apcore defines to_strict_schema() conversion to transform standard apcore Schema to Strict Mode compatible format.

Strict Mode Requirements:

Requirement Description
additionalProperties: false All nested object schemas MUST set this. A node counts as an object schema when it carries properties and either has no type keyword or has a type declaring "object" — see the object-detection rule below
All fields required All fields in properties MUST appear in required array
Optional fields expressed with nullable Originally optional fields become required + type: ["original_type", "null"]; a field with no type keyword or with constraints that can independently reject null is wrapped as {anyOf: [<original>, {type: "null"}]} instead
No x-* extension fields All x-* fields MUST be stripped
No default values default fields MUST be removed

Object detection. properties alone identifies an object schema; a missing type keyword does not make the node any less of one. A node MUST be hardened when it carries properties and either has no type keyword at all, or has a type declaring "object" in the string form ("object") or the array form (["object", "null"]). properties sitting beside a non-object type is inert (TYPE_MAPPING §17.1 R2) and MUST NOT be hardened. Rationale: a type-less {"properties": {…}} node left unhardened produces a schema that OpenAI structured outputs rejects under strict: true.

to_strict_schema() Conversion Rules:

Input: apcore_schema (standard JSON Schema + x-* extensions)
Output: strict_schema (Strict Mode compatible JSON Schema)

Rules:
  1. Recursively traverse all object-schema nodes (see "Object detection" above —
     `properties` present, and `type` either absent or declaring "object"):
     a. Set additionalProperties: false
     b. Replace required with every name in properties, sorted by Unicode code
        point (not insertion order — the output must be byte-identical across
        SDKs whose object types iterate differently)
     c. For newly added required fields, change their type to [original_type, "null"];
        a field with no `type` keyword or with enum, const, $ref, allOf, anyOf,
        oneOf, not or if is wrapped as {anyOf: [<original>, {type: "null"}]}.
        Preserve every constraint inside the original branch. Required fields
        are not widened; a type already equal to "null" is not duplicated.
  2. Remove all fields starting with "x-" (x-llm-description, x-examples, x-sensitive, x-constraints, etc.)
  3. Remove all default fields
  4. Recursively process nested schemas: `properties` values, `items`, every
     `prefixItems` entry, every oneOf/anyOf/allOf branch, and every
     `definitions` / `$defs` entry

The normative statement of these rules is ALGORITHMS A23; conformance/fixtures/schema_strict_conversion.json pins the exact output every implementation must emit.

Example — Before/After Conversion:

# Before conversion (apcore standard Schema)
type: object
properties:
  to:
    type: string
    description: "Recipient email"
    x-examples: ["[email protected]"]
  cc:
    type: array
    items: { type: string }
    description: "CC list"
    default: []
required: [to]

# After conversion (Strict Mode)
type: object
properties:
  to:
    type: string
    description: "Recipient email"
  cc:
    type: ["array", "null"]
    items: { type: string }
    description: "CC list"
required: [cc, to]        # every property, sorted (see ALGORITHMS A23 step 2f)
additionalProperties: false

Registry export_schema() Integration:

export_schema() accepts optional strict parameter. When strict=true, automatically applies to_strict_schema() conversion before export.

# Standard export
schema = registry.export_schema("executor.email.send_email")

# Strict Mode export (for OpenAI / Anthropic)
strict_schema = registry.export_schema("executor.email.send_email", strict=True)

For detailed algorithm pseudocode, see algorithms.md A23.

4.17 Export Profiles

apcore defines standard export Profiles for adapter developers to follow. Profiles are adapter layer configuration, not core implementation—apcore framework itself doesn't implement adapters but provides unified conversion specifications.

Profile Characteristics Typical Users
mcp Preserve schema extensions and project input and output schemas and annotation hints MCP Server adapters
openai Chat Completions and Responses envelopes, with the same tool names and strict schemas by default OpenAI adapters
anthropic Strip x-*; map examples → input_examples; contains input_schema Anthropic Claude Tool adapters
generic Full JSON Schema + all extensions (default) Generic scenarios, debugging

Conversion Details for Each Profile:

mcp Profile: - Schema: Preserve as-is (with x-* extension fields) - ID: Use as-is (executor.email.send_email) - Annotations: readonly → readOnlyHint, destructive → destructiveHint, idempotent → idempotentHint, open_world → openWorldHint - requires_approval and streaming have no MCP ToolAnnotations equivalent. They travel in the tool's _meta as requiresApproval and streaming, each present only when the annotation is true, and never in annotations (D-140) - MCP clients negotiating 2025-06-18 or later can receive a tool outputSchema derived from the module's output_schema and the matching result structuredContent (Appendix D.1). - See Appendix D.1 MCP Mapping

openai Profile: - Apply to_strict_schema() by default (§4.16), promoting schema-node x-llm-description strings before stripping extension keywords. - Replace . with - in the module ID (for example, executor-email-send_email). - Wrap the function in function for Chat Completions, or place its fields beside type: function for Responses. The Responses representation includes explicit strict: false when the caller opts out. - See Appendix D.3 OpenAI Mapping

anthropic Profile: - Schema: Strip every x-* keyword, at any depth of input_schema. Only keywords are stripped: a property name beginning with x- (a key of properties) is data, and the property is kept (D-140) - Replace . with - in the module ID. - Promote schema-node x-llm-description strings to description before stripping extension keywords. - Examples: module.examples[*].inputs → input_examples - See Appendix D.4 Anthropic Mapping

generic Profile: - Schema: Full output, no conversions - For apcore internal use, debugging, documentation generation


5. Module Specification

5.1 Module File Structure

Each module consists of the following parts:

extensions/{layer}/{type}/{module_name}.{ext}      # Module implementation
extensions/{layer}/{type}/{module_name}_meta.yaml  # Module metadata (optional)
schemas/{canonical_id}.schema.yaml              # Schema definition

5.2 Metadata File and Entry Point Resolution

Implementations MUST resolve module entry points according to the following algorithm:

Algorithm: resolve_entry_point(meta_yaml, file_path, language)

Input:
  meta_yaml  — Metadata file content (may be null)
  file_path  — Module file path
  language   — File language (determined by extension)

Output:
  entry_point — { file: string, class_name: string }

Steps:
  1. If meta_yaml exists and contains entry_point field:
     a. Parse format "filename:ClassName"
     b. Return { file: filename, class_name: ClassName }
  2. Otherwise, auto-infer:
     a. file ← filename from file_path (without extension)
     b. class_name ← Convert file from snake_case to PascalCase
     c. If the language loads module files at runtime: candidates ← the classes the
        file provides that satisfy the Module interface (§5.6 — duck-typed, no base
        class is required)
     d. If exactly one candidate → Return that class
     e. If more than one candidate → Throw MODULE_LOAD_ERROR (ambiguous entry point)
     f. If no candidate → Throw MODULE_LOAD_ERROR (no module class in the file)
  3. Return entry_point

The entry_point field. The value has the form "<file_stem>:<ClassName>"; schemas/module-meta.schema.json constrains it to ^[a-z][a-z0-9_]*:[A-Z][a-zA-Z0-9]*$. The class is looked up by the name after the : in the module file being loaded. When an implementation that loads module files at runtime finds no class of that name in the file, the load MUST fail with MODULE_LOAD_ERROR, naming the class and the file.

An implementation for a language that cannot load a module file at runtime (Rust) resolves only the entry-point name — from entry_point, or by converting the file stem from snake_case to PascalCase (step 2b) — and obtains the module instance from an application-supplied factory keyed by that name. A discovered file for which the factory supplies no module is skipped.

# extensions/executor/validator/db_params_meta.yaml

# Note: module_id and group are auto-generated from directory, no manual specification needed

# Module description
description: "Database parameter validator"

# Entry point (optional, defaults to inference from filename)
entry_point: "db_params:DbParamsValidator"

# Allowed callers to this module (ACL)
allowed_callers:
  - "orchestrator.engine.*"        # Wildcard
  - "api.handler.task_submit"      # Exact match

# Dependencies on other modules (see 5.3 Dependency Management)
dependencies:
  - module_id: "common.util.sql_parser"
    version: ">=1.0.0"             # Version constraint (optional)
    optional: false                 # Whether optional dependency

# Tags (for categorization and search)
tags:
  - database
  - validation
  - security

# Version (optional)
version: "1.0.0"

# Behavior annotations (optional, help AI make invocation decisions)
annotations:
  readonly: false
  destructive: false
  idempotent: true
  requires_approval: false
  open_world: false

# Usage examples (optional, help AI understand complex modules)
examples:
  - title: "Validate SELECT statement"
    inputs:
      table: "user_info"
      sql: "SELECT * FROM user_info WHERE id = 1"
    output:
      valid: true
      message: "Validation passed"

  - title: "Detect dangerous SQL"
    inputs:
      table: "user_info"
      sql: "DROP TABLE user_info"
    output:
      valid: false
      errors:
        - field: "sql"
          code: "DANGEROUS_SQL"
          message: "SQL contains dangerous keyword: DROP"

# Extension metadata (optional, free dict)
metadata:
  owner: "database-team"
  avg_latency_ms: 5

# Deprecation marking (optional)
deprecated: false
deprecated_message: null
replacement: null
sunset_date: null                    # ISO 8601 date after which module MAY be removed (e.g., "2026-06-01")

# Resource limits (optional, for sandbox isolation)
resources:
  timeout: 30000                   # Execution timeout (ms)
  memory_limit: null               # Memory limit (bytes), null=no limit

5.3 Dependency Management

Implementations MUST use topological sorting to resolve dependency order and MUST detect circular dependencies.

Algorithm: resolve_dependencies(modules)

Input:
  modules — Module set, each module contains { id, dependencies[] }

Output:
  load_order — List of module IDs sorted by dependency order

Steps:
  1. Build dependency graph: Map<module_id, Set<dependency_id>>
  2. Calculate in-degree: Map<module_id, int>
  3. queue ← All modules with in-degree 0
  4. load_order ← []
  5. While queue is not empty:
     a. current ← queue.dequeue()
     b. load_order.append(current)
     c. For each dependent of current:
        - in_degree[dependent] -= 1
        - If in_degree[dependent] == 0 → queue.enqueue(dependent)
  6. If len(load_order) < len(modules):
     - remaining ← Modules not added to load_order
     - cycle ← a dependency cycle among remaining (back-edge search), or null
     - If cycle is not null → Throw CIRCULAR_DEPENDENCY with cycle_path = cycle
     - Otherwise → Throw MODULE_LOAD_ERROR naming remaining; MUST NOT report
       CIRCULAR_DEPENDENCY and MUST NOT fabricate a cycle_path (D-79)
  7. Return load_order

Complexity: O(V + E), where V is number of modules, E is number of dependencies
dependency_management:
  # Dependency declaration format
  declaration:
    simple: "common.util.sql_parser"           # Simple format: any version
    with_version:
      module_id: "common.util.sql_parser"
      version: ">=1.0.0,<2.0.0"                # Version constraint
      optional: false                           # Required dependency

  # Version constraint syntax (similar to npm/pip)
  version_constraints:
    - "1.0.0"        # Exact version
    - ">=1.0.0"      # Greater than or equal
    - "<2.0.0"       # Less than
    - ">=1.0.0,<2.0.0"  # Range
    - "^1.0.0"       # Compatible version (1.x.x)
    - "~1.0.0"       # Approximate version (1.0.x)

  # Dependency resolution rules
  resolution:
    strategy: "highest"            # highest | lowest | locked
    conflict_resolution: "error"   # error | use_highest | use_lowest

  # Circular dependencies
  circular_dependency: "error"     # Error when circular dependency detected

  # Optional dependencies
  optional_dependency:
    behavior: "skip_if_missing"    # Skip if missing, don't error
    check_method: "has_module(module_id) -> bool"

5.4 Multi-version Coexistence

multi_version:
  # Whether to allow multiple versions of same module
  enabled: true

  # Version identification method
  identification:
    method: "file_suffix"          # Filename suffix
    pattern: "{name}_v{major}"     # e.g., db_params_v2.py

  # Version selection
  selection:
    default: "latest"              # Use latest version by default
    explicit: "module_id@version"  # Explicit specification: executor.validator.db_params@2

  # Examples
  examples:
    - file: "db_params.py"
      id: "executor.validator.db_params"
      version: "1.0.0"

    - file: "db_params_v2.py"
      id: "executor.validator.db_params_v2"
      version: "2.0.0"
      alias: "executor.validator.db_params@2"

Version hints (D-126). Resolving a registry lookup by version is OPTIONAL, as multi-version coexistence is. An implementation that accepts a version_hint it does not resolve by MUST make that visible to the caller. Refusing the argument at compile time satisfies this; so does a deprecation warning, emitted once per module ID per registry instance because get is called in loops (D-89). Deprecating an unresolved hint, rather than removing it, keeps existing callers compiling while telling them the same thing (D-121).

Rationale: a caller writing get(id, "1.0.0") believes it has pinned a version. A hint that is silently discarded is a declared surface that reaches no mechanism (§9.1.3).

5.5 Module Isolation (Optional)

module_isolation:
  # Isolation levels
  levels:
    none: "No isolation, shared process space"
    process: "Separate process"
    container: "Container isolation"

  # Resource limits
  resource_limits:
    timeout:
      type: integer
      unit: "ms"
      default: 30000
    memory:
      type: integer
      unit: "bytes"
      default: null              # null = no limit
    cpu:
      type: number
      unit: "cores"
      default: null

  # Sandbox configuration
  sandbox:
    network: true                # Allow network access
    filesystem: "readonly"       # readonly | readwrite | none
    allowed_paths: []            # Allowed access paths

5.6 Module Interface Protocol

All modules MUST provide the following interface. Modules can be defined via a decorator (primary approach), a class-based pattern (no ABC inheritance required), or a function call. Implementations MUST NOT require modules to inherit from an abstract base class.

Primary approach: Decorator

The @module decorator (or module() function call) is the recommended way to define modules. It wraps a callable and auto-generates Schema from type annotations:

from apcore import module

@module(id="email.send", tags=["email"])
def send_email(to: str, subject: str, body: str) -> dict:
    """Send email to specified recipient"""
    return {"success": True, "message_id": "msg_123"}

Alternative: Class-based modules

Class-based modules provide an execute() method and input_schema / output_schema / description attributes. No ABC inheritance is required:

class SendEmailModule:
    input_schema = SendEmailInput
    output_schema = SendEmailOutput
    description = "Send email to specified recipient"

    def execute(self, inputs: dict, context: Context) -> dict:
        return {"success": True, "message_id": "msg_123"}

Module Interface Contract (language-agnostic pseudocode):

Interface: Module

  Required implementations:
    execute(inputs: Map<String, Any>, context: Context) → Map<String, Any>
      Precondition: inputs has passed input_schema validation
      Postcondition: Return value must conform to output_schema
      Exception: ModuleError

  Optional implementations:
    validate(inputs: Map<String, Any>) → ValidationResult
    preflight(inputs: Map<String, Any>, context: Context) → List<String>
      # Advisory pre-execution warnings. Returning warnings does NOT block execution.
      # If preflight() raises, the exception is caught and reported as a warning.
    preview(inputs: Map<String, Any>, context: Context) → PreviewResult?
      # Structured prediction of state changes the call would produce.
      # Returns null if prediction is unavailable (e.g., target not found).
      # Called by Executor.validate() after preflight(); result is folded into
      # PreflightResult.predicted_changes. If preview() raises, treated as
      # advisory warning (mirrors preflight semantics).
      # See §12.8 for PreviewResult / Change schema.
    on_load() → void
    on_unload() → void
    on_suspend() → Map<String, Any>?
      # Called before hot-reload. Returns serializable state to preserve.
      # Returns null if no state needs preservation.
    on_resume(state: Map<String, Any>) → void
      # Called after hot-reload. Restores state from on_suspend().
      # Only called if on_suspend() returned non-null state.

  Required definitions:
    input_schema: SchemaDefinition    // Input Schema
    output_schema: SchemaDefinition   // Output Schema
    description: String               // Module description

  Optional definitions:
    name: String?                     // Human-readable name
    tags: List<String>                // Tag list
    version: String                   // Semantic version
    annotations: ModuleAnnotations?   // Behavior annotations
    examples: List<ModuleExample>     // Usage examples
    metadata: Map<String, Any>        // Extension metadata

Cross-language Implementation Mapping:

Pseudocode Interface Python Rust Go Java TypeScript
Module definition @module decorator or class with execute() trait Module or struct type Module interface or struct interface Module or class @module decorator or class with execute()
execute() def execute(self, inputs, context) fn execute(&self, inputs, context) func (m) Execute(inputs, ctx) Map execute(Map, Context) execute(inputs, context)
input_schema ClassVar[Type[BaseModel]] type InputSchema: Serialize InputSchema struct Class<? extends Schema> static inputSchema: ZodSchema
Map<String, Any> dict[str, Any] HashMap<String, Value> map[string]any Map<String, Object> Record<string, unknown>

All modules MUST implement the following interface:

module_interface:
  # Required methods
  required_methods:
    - name: "execute"
      description: "Execute module main logic"
      input: "Defined by input_schema"
      output: "Defined by output_schema"
  # Required attributes (mirrors the "Required definitions" block in the
  # pseudocode interface above; every module MUST expose these)
  required_attributes:
    - name: "input_schema"
      type: "SchemaDefinition"
      description: "JSON Schema (or language-native equivalent) for the inputs accepted by execute()"

    - name: "output_schema"
      type: "SchemaDefinition"
      description: "JSON Schema (or language-native equivalent) for the value returned by execute()"

    - name: "description"
      type: "string"
      description: "Human/AI-readable summary of what the module does (≤200 chars recommended)"

  # Optional attributes
  optional_attributes:
    - name: "name"
      type: "string"
      description: "Human-readable module name"
      default: "Auto-generated from class name"

    - name: "tags"
      type: "list[string]"
      description: "Tags for categorization and search"
      default: "[]"

    - name: "version"
      type: "string"
      description: "Module version"
      default: "1.0.0"

    - name: "annotations"
      type: "ModuleAnnotations"
      description: "Behavior annotations, help AI make invocation decisions"
      default: "Default values (readonly=false, destructive=false, ...)"

    - name: "examples"
      type: "list[ModuleExample]"
      description: "Usage examples, help AI understand complex modules"
      default: "[]"

    - name: "metadata"
      type: "dict[str, Any]"
      description: "Free extension metadata"
      default: "{}"

  # Optional implementations
  optional_methods:
    - name: "validate"
      description: "Validate input only, don't execute"
      input: "Defined by input_schema"
      output: "{ valid: bool, errors: array }"

    - name: "describe"
      description: "Return module description (for LLM)"
      input: "None"
      output: "{ description: string, input_schema: object, output_schema: object, annotations: object, examples: array }"

    - name: "preflight"
      description: "Domain-specific pre-execution warnings (called by Executor.validate() Check 7)"
      input: "(inputs: dict, context: Context)"
      output: "list[str] — warning messages, or empty list if no warnings"
      note: "Advisory only — returning warnings does NOT block execution. If preflight() raises, the exception is caught and reported as a warning."

    - name: "preview"
      description: "Structured prediction of state changes the call would produce (called by Executor.validate() after preflight)"
      input: "(inputs: dict, context: Context)"
      output: "PreviewResult | null — { changes: List<Change> } or null if prediction unavailable"
      note: "Optional. Modules that don't implement it leave PreflightResult.predicted_changes empty. If preview() raises (sync throw or async reject), treated as advisory warning via a `module_preview` check entry — does NOT fail validation. See §12.8 for the PreviewResult / Change schema."

  # Lifecycle hooks
  lifecycle_hooks:
    - name: "on_load"
      description: "Called when module loads"
    - name: "on_unload"
      description: "Called when module unloads"
    - name: "on_suspend"
      description: "Called before hot-reload to export serializable state"
      return: "dict | null — serializable state to preserve, or null"
    - name: "on_resume"
      description: "Called after hot-reload to restore previously exported state"
      input: "state: dict — state returned by on_suspend() of the previous instance"

preview() contract. preview() lets a module report what a call would change before it is made. It complements preflight(), which reports warnings; neither replaces the other.

  1. preview() is optional. A module that does not implement it, or whose preview() returns null (prediction unavailable, e.g. the target record does not exist), contributes no changes, and PreflightResult.predicted_changes stays empty.
  2. preview() MUST NOT have side effects.
  3. Executor.validate() invokes preview(inputs, context) after preflight(), and only when the acl check did not fail (§12.8.5.1). In Python and TypeScript preview() may be synchronous or asynchronous.
  4. The changes of the returned PreviewResult become PreflightResult.predicted_changes, in the order the module returned them. PreviewResult and Change are defined in §12.8.
  5. If preview() raises (throws, rejects, or panics), validate() MUST NOT fail: the failure is reported as a warning on a module_preview check result with passed: true, and predicted_changes stays empty — the same semantics as preflight().

5.7 Context Parameter Specification

Each module invocation passes a context parameter containing runtime context information. In cross-process scenarios, Context MUST support serialization for transport.

Design Principle: Only fields that the framework execution engine depends on are independent fields, everything else goes in data (referencing Go context.Context, OpenTelemetry Context design philosophy).

context_schema:
  type: object
  properties:
    # ====== Framework engine dependencies (breaks if removed) ======

    trace_id:
      type: string
      pattern: "^[0-9a-f]{32}$"
      description: "Request trace ID, 32-char lowercase hex (W3C Trace Context compatible)"
      required: true
      example: "4bf92f3577b34da6a3ce929d0e0e4736"

    caller_id:
      type: [string, "null"]
      description: "Caller's Canonical ID (null for top-level calls)"
      example: "orchestrator.engine.task_flow"

    call_chain:
      type: array
      items:
        type: string
      description: "Complete call chain (for loop detection, depth limiting, ACL)"
      example: ["api.handler.task_submit", "orchestrator.engine.task_flow"]

    executor:
      description: "Executor reference (for calling other modules, runtime injected)"

    # ====== Almost all users need, semantically stable ======

    identity:
      type: [object, "null"]
      description: "Caller identity (ACL engine depends on)"
      properties:
        id:
          type: string
          description: "Unique identifier"
        type:
          type: string
          examples: [user, service, agent, api_key, system, ai]
          default: "user"
          description: "Identity type (free-form string; well-known values shown in examples)"
        roles:
          type: array
          items:
            type: string
          description: "Role list (ACL depends on)"
        attrs:
          type: object
          description: "Extension attributes (tenant_id, email, etc. business fields)"
        scopes:
          type: array
          items:
            type: string
          description: "Optional effective scope set; an empty set grants no scoped authority (§6.11)"
        on_behalf_of:
          type: object
          description: "Optional parent identity with the same shape, pointing toward the root subject (§6.11)"
        issuer:
          type: string
          description: "Optional trusted issuer qualifier for the actor's identity namespace (§6.11)"

    # ====== Everything else ======

    data:
      type: object
      description: "Shared pipeline state (reference passing, readable/writable along call chain)"

    # ====== Optional extension fields (MAY be provided by implementations) ======

    cancel_token:
      description: "Cooperative cancellation token. During a call it is that call's own token, a child of its caller's (§12.7.5)"

    services:
      type: [object, "null"]
      description: "Dependency injection container for sharing services across the call chain (MAY)"

    redacted_inputs:
      type: [object, "null"]
      description: "Copy of inputs with x-sensitive fields replaced by REDACTED_VALUE, for safe logging (MAY)"

Field Classification Rationale:

Field Classification Reason
trace_id Framework engine dependency Executor generates, middleware/logging depends on across chain
caller_id Framework engine dependency ACL engine determines "who is calling whom"
call_chain Framework engine dependency Loop detection, depth limiting, ACL path matching
executor Framework engine dependency Only channel for inter-module calls
identity Widely needed ACL is framework first-class citizen, needs standardized "who"
data Universal bag span_id, locale, pipeline intermediate state, etc. all mutable data
cancel_token Optional extension Cooperative cancellation; a timeout cancels the timed-out call's own token (§12.7.5)
services Optional extension DI container for framework integrations
redacted_inputs Optional extension Safe logging of sensitive inputs

Note on external correlation IDs:

The trace_id field is owned by the apcore framework and follows the strict 32-char lowercase hex format for W3C Trace Context interoperability. Existing projects that already emit their own request or correlation identifiers (e.g., X-Request-ID, X-Correlation-ID, ULID, AWS X-Ray trace headers) SHOULD preserve those values in context.data["x-correlation-id"] and MUST NOT overwrite trace_id with them. Framework integrations SHOULD populate both at the context boundary so distributed tracing and legacy business logs remain correlatable side-by-side. See the Integrating into Existing Projects guide for examples.

Context Serialization Specification (Cross-process Scenarios):

In cross-process/cross-network invocation scenarios, Context MUST be serializable to JSON format:

context_serialization:
  format: "JSON"
  rules:
    - "trace_id: MUST serialize as string"
    - "caller_id: MUST serialize as string | null"
    - "call_chain: MUST serialize as string[]"
    - "executor: MUST NOT serialize (runtime injected)"
    - "identity: MUST serialize as JSON object"
    - "data: SHOULD serialize, but MUST exclude non-serializable values"
    - "When data contains functions/connections etc. non-serializable values, MUST silently skip and log warning"
    - "cancel_token: MUST NOT serialize (runtime object)"
    - "services: MUST NOT serialize (runtime injected)"
    - "redacted_inputs: MAY serialize as JSON object"

5.7.1 In-process invocation attachments

SDKs MUST provide derivation methods to attach a call budget, progress reporter, or elicitation handler to a Context without changing the D-24 constructor. Child calls MUST inherit the attachments unless the host explicitly replaces them. The attachments MUST NOT be serialized.

A progress report carries a finite progress value and optional finite total and message. Reporting without a reporter completes without sending a report. An elicitation request carries a message and an optional JSON Schema object. Without a handler, elicitation returns an empty optional result. A reply indicates accept with object content, decline, or cancel. The invocation's cancellation and deadline MUST bound the wait for either callback. The adapter owns transport authorization, capability negotiation, and the association with the active caller.

5.8 Async Module Specification

Async module state transitions MUST follow this state machine:

                    ┌──────────────────────────────────────────┐
                    │                                          │
                    ▼                                          │
  ┌──────┐    ┌─────────┐    ┌─────────┐    ┌───────────┐    │
  │ idle │───▶│ pending │───▶│ running │───▶│ completed │    │
  └──────┘    └─────────┘    └────┬────┘    └───────────┘    │
                                  │                            │
                                  ├───▶ ┌────────┐             │
                                  │     │ failed │             │
                                  │     └────────┘             │
                                  │                            │
                                  └───▶ ┌───────────┐          │
                                        │ cancelled │──────────┘
                                        └───────────┘
                                        (can resubmit)

  State transition rules:
    idle → pending       : When submit() is called on AsyncTaskManager
    pending → running    : When executor starts processing
    running → completed  : When execution succeeds
    running → failed     : When execution throws exception
    running → cancelled  : When cancel() is called
    cancelled → pending  : When resubmitted (MAY support)
    failed → pending     : When retrying (MAY support)

  Forbidden transitions:
    completed → *        : Completed tasks MUST NOT transition to other states
    idle → running       : MUST NOT skip pending state

For long-running modules, async execution mode is supported:

async_module:
  # Async execution methods
  methods:
    # Start async task (framework invokes execute() asynchronously via AsyncTaskManager.submit())
    submit:
      input: "Defined by input_schema"
      output:
        type: object
        properties:
          task_id:
            type: string
            description: "Async task ID"
          status:
            type: string
            enum: [pending, running]

    # Query task status
    get_status:
      input:
        task_id: string
      output:
        type: object
        properties:
          status:
            type: string
            enum: [pending, running, completed, failed, cancelled]
          progress:
            type: number
            minimum: 0
            maximum: 100
          result:
            description: "Result when task completes (per output_schema)"
          error:
            description: "Error info when task fails"

    # Cancel task
    cancel:
      input:
        task_id: string
      output:
        type: object
        properties:
          success: boolean

  # Callback mechanism (optional)
  callbacks:
    on_progress:
      description: "Progress update callback"
    on_complete:
      description: "Task completion callback"
    on_error:
      description: "Task failure callback"

5.9 Inter-module Communication

Modules call other modules through Executor:

module_communication:
  # Invocation methods
  methods:
    # Sync call
    sync_call:
      signature: "executor.call(module_id, inputs, context)"
      returns: "output or raises ModuleError"

    # Async call
    async_call:
      signature: "executor.call_async(module_id, inputs, context)"
      returns: "Future[output]"

  # Invocation constraints
  constraints:
    - "Must go through Executor, direct instantiation not allowed"
    - "Invocations subject to ACL rules"
    - "Call chain automatically recorded to context.call_chain"
    - "Avoid circular calls (framework detects and errors)"

  # Example (Python)
  example: |
    class MyModule(Module):
        def execute(self, inputs: dict, context: Context) -> dict:
            # Call other module
            result = context.executor.call(
                module_id="common.util.sql_parser",
                inputs={"sql": inputs["sql"]},
                context=context
            )
            return {"parsed": result}

5.10 Module Implementation Example (Python)

# extensions/executor/validator/db_params.py

from apcore import Module
from pydantic import BaseModel, Field
from typing import Optional

class DBParamsInput(BaseModel):
    """Input Schema - Keep consistent with YAML"""
    table: str = Field(..., pattern=r"^[a-z][a-z0-9_]*$")
    sql: str
    timeout: int = Field(default=30, ge=1, le=300)

class DBParamsOutput(BaseModel):
    """Output Schema"""
    valid: bool
    message: Optional[str] = None
    errors: list[dict] = []
    warnings: list[str] = []

class DbParamsValidator(Module):
    """Database parameter validator"""

    # Schema declaration (optional if using YAML)
    input_schema = DBParamsInput
    output_schema = DBParamsOutput

    # Behavior annotations: AI knows this is readonly check, idempotent, no side effects
    annotations = ModuleAnnotations(
        readonly=True,
        destructive=False,
        idempotent=True,
        requires_approval=False,
        open_world=False
    )

    # Usage examples
    examples = [
        ModuleExample(
            title="Validate safe SQL",
            inputs={"table": "user_info", "sql": "SELECT * FROM user_info"},
            output={"valid": True, "message": "Validation passed", "errors": [], "warnings": []}
        )
    ]

    def execute(self, inputs: dict, context: Context) -> dict:
        """Execute validation"""
        # Input already validated by Schema
        params = DBParamsInput(**inputs)

        errors = []
        warnings = []

        # Business logic: Check dangerous SQL
        dangerous_keywords = ['DROP', 'TRUNCATE', 'DELETE']
        sql_upper = params.sql.upper()
        for kw in dangerous_keywords:
            if kw in sql_upper:
                errors.append({
                    "field": "sql",
                    "code": "DANGEROUS_SQL",
                    "message": f"SQL contains dangerous keyword: {kw}"
                })

        return DBParamsOutput(
            valid=len(errors) == 0,
            message="Validation passed" if not errors else "Validation failed",
            errors=errors,
            warnings=warnings
        ).model_dump()

5.11 Function-based Module Definition (Function-based Module Definition)

Section name uses "Function-based Module Definition" rather than "Decorator Module Definition" because Decorator is language-specific syntax, while the core requirement is semantic capability—wrapping existing callables as standard modules.

5.11.1 Normative Statement

Implementations MUST provide module() mechanism to wrap existing callables (functions or methods) as standard modules, auto-generating Schema from type information.

module() is the only core concept, available in both Decorator and function call forms:

  • In languages supporting Decorator syntax (Python, TypeScript, Java annotations), SHOULD provide as Decorator form
  • In languages not supporting Decorator (Go, C), MUST provide as function call form
  • Both forms share the same parameter set, producing modules that MUST be completely equivalent in Registry/Executor/Schema behavior

5.11.2 Cross-language Syntax Reference

Language Decorator Form Function Call Form (Register Existing Code)
Python @module(id="email.send") def send(...) module(service.send, id="email.send")
TypeScript @module({id: "email.send"}) function send(...) module(service.send, {id: "email.send"})
Java @Module(id="email.send") public Map send(...) Apcore.module(service::send, "email.send")
Rust #[module(id = "email.send")] fn send(...) apcore::module("email.send", \|inputs\| { ... })
Go — None apcore.Module("email.send", sendEmail) / apcore.Module("email.send", service.Send)
C — None apcore_module("email.send", &send_email)

5.11.3 module() Parameter Signature

Both forms share the same parameter set (language-agnostic pseudocode):

module(callable?, options?) → Module

options:
  id: String?              // Module ID (optional, auto-generate if absent)
  description: String?     // Module description (optional, extract from docstring/comment if absent)
  annotations: Annotations? // Behavior annotations (optional)
  tags: List<String>?      // Tags (optional)
  version: String?         // Version (optional, default "1.0.0")
  metadata: Map?           // Extension metadata (optional)
  • Decorator form: callable implicitly provided by decorator target, options as decorator parameters
  • Function call form: callable explicitly passed (first parameter), options as subsequent parameters

5.11.4 Type Inference and Schema Auto-generation

Implementations MUST auto-generate JSON Schema from function signatures according to the following algorithm:

Algorithm: generate_schema_from_function(callable)

Input:
  callable — Target function or method

Output:
  schema — { input_schema: JSONSchema, output_schema: JSONSchema, description: String }

Steps:
  1. Extract function parameter list params (exclude self/cls and context: Context)
  2. For each param:
     a. Get type annotation type_hint
     b. If type_hint missing → Throw FUNC_MISSING_TYPE_HINT error
     c. Map type_hint to JSON Schema type (see §5.11.5)
     d. Extract constraints from Annotated metadata, default values, etc.
     e. Extract description from docstring parameter comments
  3. Construct input_schema:
     a. type: "object"
     b. properties: Schema mapping of all parameters
     c. required: List of parameters without defaults
  4. Extract return type annotation return_type
     a. If return_type missing → Throw FUNC_MISSING_RETURN_TYPE error
     b. Map return_type to output_schema
  5. Extract description:
     a. docstring/comment first line → description
     b. Parameter comments → Each field's description
  6. Return { input_schema, output_schema, description }

Complexity: O(n), where n is number of parameters

5.11.5 Language Type → JSON Schema Mapping Table

Language Type JSON Schema Description
str / String { "type": "string" } String
int / Integer / i32 { "type": "integer" } Integer
float / Double / f64 { "type": "number" } Float
bool / Boolean { "type": "boolean" } Boolean
list[T] / Vec<T> / []T { "type": "array", "items": <T> } Array
dict[str, T] / Map<String, T> { "type": "object", "additionalProperties": <T> } Map
Optional[T] / T \| None / Option<T> { "anyOf": [<T>, { "type": "null" }] }, or <T> with "null" added to its type array Nullable type (JSON Schema has no nullable keyword)
BaseModel / struct / @dataclass { "type": "object", "properties": {...} } Struct/object
Literal["a", "b"] / enum { "type": "string", "enum": ["a", "b"] } Enum
Annotated[T, Field(...)] <T> + constraint fields Constrained type

5.11.6 Module ID Generation Rules

When module() doesn't specify id parameter, MUST auto-generate from function full path:

Rule: generate_module_id(callable)

Steps:
  1. Get callable's module path (e.g., "myapp.services.email")
  2. Get callable's name (e.g., "send_email")
  3. Combine as "{module_path}.{name}"
  4. Normalize to Canonical ID format (§2.7)
  5. If ID already exists → Throw duplicate_id error (§2.6)

5.11.7 Description Extraction Rules

Implementations MUST extract module description by the following priority:

  1. module()'s description parameter (highest priority)
  2. Function docstring / comment first line
  3. If neither above → Generate default description from function name

Parameter-level description: - Extract from docstring's Args/Parameters section - Extract from Annotated[T, Field(description="...")] - Extract from language comments

5.11.8 Sync/Async Function Support

Function Type Mapping
def func(...) execute()
async def func(...) execute()

Implementations SHOULD support both sync and async functions. The framework auto-detects whether a function is sync or async and handles invocation accordingly. Both map to the module's execute() method.

5.11.9 Context Injection

When function parameters include context: Context type annotation, framework MUST auto-inject Context object, and this parameter MUST NOT appear in generated input_schema.

# context parameter auto-injected, doesn't appear in Schema
@module(id="email.send")
def send_email(to: str, subject: str, body: str, context: Context) -> dict:
    print(f"trace_id: {context.trace_id}")
    return {"success": True}

# Generated input_schema only contains to, subject, body

5.11.10 Equivalence Guarantee

Function-defined modules and class-defined modules MUST be completely equivalent in:

  • Registration and discovery behavior in Registry
  • Executor's invocation flow (Schema validation → ACL → Middleware → Execution)
  • Schema format and validation logic
  • Error handling and error codes
  • Observability (tracing, logging, metrics)

5.11.11 Error Codes

Error Code Description Trigger Condition
FUNC_MISSING_TYPE_HINT Function parameter missing type annotation Parameter has no type annotation and can't be inferred
FUNC_MISSING_RETURN_TYPE Function missing return type annotation Return type has no annotation and can't be inferred

5.11.12 Examples

Python — Decorator Form:

from apcore import module, Context
from typing import Annotated
from pydantic import Field

@module(id="email.send", tags=["email", "notification"])
def send_email(
    to: Annotated[str, Field(description="Recipient email")],
    subject: Annotated[str, Field(description="Email subject", max_length=200)],
    body: Annotated[str, Field(description="Email body")],
    context: Context
) -> dict:
    """Email sending module"""
    # Original business logic
    return {"success": True, "message_id": "msg_123"}

Python — Function Call Form (Register Existing Code):

from apcore import module

class EmailService:
    def send(self, to: str, subject: str, body: str) -> dict:
        """Send email"""
        return {"success": True}

service = EmailService()
module(service.send, id="email.send")

Go — Function Call Form:

package main

import "github.com/apcore/apcore-go"

func sendEmail(to string, subject string, body string) map[string]any {
    return map[string]any{"success": true}
}

func main() {
    apcore.Module("email.send", sendEmail)

    // Register existing struct method
    service := &EmailService{}
    apcore.Module("email.send_template", service.SendTemplate)
}

5.12 External Schema Binding (External Schema Binding)

5.12.1 Normative Statement

Implementations MUST support external Schema binding files, allowing existing functions to be mapped as apcore modules through YAML configuration, achieving zero-code-modification integration.

5.12.2 Binding File Format

Binding files MUST be in YAML format, containing a bindings array:

# bindings/email.binding.yaml
spec_version: "1.0"
bindings:
  - module_id: "email.send"
    target: "myapp.services.email:send_email"
    description: "Send email"
    input_schema:
      type: object
      properties:
        to:
          type: string
          description: "Recipient email"
        subject:
          type: string
          description: "Email subject"
        body:
          type: string
          description: "Email body"
      required: [to, subject, body]
    output_schema:
      type: object
      properties:
        success:
          type: boolean
        message_id:
          type: string

  - module_id: "email.send_template"
    target: "myapp.services.email:EmailService.send_template"
    description: "Send email using template"
    auto_schema: true  # Auto-generate Schema from type annotations

Top-level Keys (schemas/binding.schema.json):

Key Type Required Description
spec_version string MAY Binding-file format version. "1.0" is the only version defined.
bindings array MUST Binding entries

When spec_version is absent, implementations treat the file as "1.0" and log a warning. Any other value is logged as a warning and loading proceeds.

A binding file that cannot be read or parsed, whose top level is not a mapping, that has no bindings key or whose bindings value is not a list, or that contains an entry without module_id or target, MUST fail with BINDING_FILE_INVALID. So MUST a file whose top level carries a key other than spec_version and bindings, and a file with an entry that carries a field not in the table below: an unknown key is a typo until proven otherwise, and ignoring it can turn a misspelled schema field into a module with no schema (D-139).

Binding Item Field Definitions:

Field Type Required Description
module_id string MUST Module Canonical ID
target string MUST Target callable (format: module.path:callable_name or module.path:ClassName.method_name, §5.12.3)
description string SHOULD Module description
documentation string MAY Extended documentation (§4.8.3)
input_schema object Conditional Input Schema (explicit mode, together with output_schema)
output_schema object Conditional Output Schema (explicit mode, together with input_schema)
auto_schema boolean | string Conditional Infer Schema from the target (§5.12.5)
schema_ref string MAY External Schema file, relative to the binding file's directory (§5.12.4)
annotations object MAY Behavior annotations (§4.4)
tags array MAY Tags
version string MAY Version (default "1.0.0")
metadata object MAY Extension metadata
display object MAY Surface-facing presentation overlay (§5.13)

Implementations MUST carry every field of an entry's annotations — the full §4.4 set, including extra (§4.4.1) — onto the registered module. Length and format limits on description, documentation, tags and version are opt-in (§9.1.2).

Schema Source. Each entry takes its schemas from exactly one source:

  1. Explicit — input_schema and output_schema. An entry that sets one without the other MUST fail with BINDING_FILE_INVALID; the missing side is never defaulted (D-139).
  2. External file — schema_ref (§5.12.4).
  3. Auto — auto_schema (§5.12.5).
  4. Implicit auto — none of the fields above; the schemas are inferred from the target as in auto mode (§5.12.5).

An entry that sets fields of more than one of sources 1–3 MUST fail with BINDING_SCHEMA_MODE_CONFLICT.

5.12.3 Target Resolution Algorithm

Implementations MUST resolve target field according to the following algorithm:

Algorithm: resolve_target(target_string)

Input:
  target_string — Target callable path (e.g., "myapp.services.email:send_email")

Output:
  callable — Callable object

Preconditions:
  - target_string conforms to "module.path:callable_name" format

Steps:
  1. Split target_string by ":" into (module_path, callable_name)
     If no ":" → Throw BINDING_INVALID_TARGET error
  2. import module_path
     If import fails → Throw BINDING_MODULE_NOT_FOUND error
  3. If callable_name contains ".":
     a. Split by "." into (class_name, method_name)
     b. Find class_name in module
     c. Find method_name on class instance
     d. If any step fails → Throw BINDING_CALLABLE_NOT_FOUND error
  4. Otherwise:
     a. Find callable_name in module
     b. If not found → Throw BINDING_CALLABLE_NOT_FOUND error
  5. Validate result is callable
     If not callable → Throw BINDING_NOT_CALLABLE error
  6. Return callable

Complexity: O(1) (not counting module loading time)

In step 3 the class is instantiated with no arguments, and method_name is looked up on that instance.

module_path is resolved by the host language's own module resolution (Python importlib, ECMAScript dynamic import()). It is never resolved relative to the binding file's directory, and an implementation MUST NOT join it against that directory. A binding file declares capabilities the host already has; resolving code relative to the file would make the reachable code depend on where the file sits. Making the target importable — an installed package, a module on the import path, a specifier the bundler resolves — is the binding author's responsibility.

An implementation whose module loader accepts filesystem paths or URLs MUST reject a module_path that contains .. or is a file: URL, with BINDING_INVALID_TARGET. An implementation MAY restrict targets to an allowlist of trusted package prefixes; a target outside the allowlist fails with BINDING_INVALID_TARGET before anything is imported.

An implementation for a language without runtime import (Rust) treats target as an opaque key into a map of handlers the application supplies at registration; the binding file itself is the same in every language. A binding whose target has no handler in that map MUST fail with BINDING_MODULE_NOT_FOUND.

5.12.4 Schema Reference Support

Binding items may reference external Schema files via schema_ref, avoiding inlining complete Schema in binding file:

bindings:
  - module_id: "email.send"
    target: "myapp.services.email:send_email"
    schema_ref: "../schemas/email.send.schema.yaml"

schema_ref is resolved relative to the directory of the binding file that contains it — unlike target, it names data, not code. The referenced file is YAML with top-level input_schema and output_schema keys; a key it omits yields an empty schema object. A referenced file that does not exist or does not parse MUST fail with BINDING_FILE_INVALID.

5.12.5 auto_schema Mode

When auto_schema enables inference, implementations MUST infer the schemas from the target. An implementation whose language exposes type annotations at runtime MUST reuse the generate_schema_from_function algorithm from §5.11.4. One whose language does not infers from schema values associated with the target instead: schemas the target's module exports beside it, or schemas carried by the handler supplied for the target (§5.12.3).

If target callable lacks sufficient type information, MUST throw BINDING_SCHEMA_INFERENCE_FAILED error. BINDING_SCHEMA_MISSING is a deprecated alias of this code, retained only for decoding serialized payloads.

auto_schema takes these values:

Value Meaning
true, "true", "permissive" Permissive: the inferred schemas reflect the target's types as they are.
"strict" As permissive; in addition the implementation MUST check each inferred schema against OpenAI/Anthropic structured-output strict mode (the keyword set pinned by conformance/fixtures/openai_strict_compat.json) and fail an incompatible one with BINDING_STRICT_SCHEMA_INCOMPATIBLE.
false Disables inference. With no other schema source the entry MUST fail with BINDING_SCHEMA_INFERENCE_FAILED.

Any other value MUST fail with BINDING_FILE_INVALID (D-139).

An entry in implicit auto mode (§5.12.2) is inferred as under auto_schema: true. When inference cannot produce a schema — in any mode, implicit included — the entry MUST fail with BINDING_SCHEMA_INFERENCE_FAILED. Implementations MUST NOT substitute a permissive schema: it would register a module whose inputs are never validated (D-139).

5.12.6 Discovery Mechanism

Binding file discovery is controlled via apcore.yaml configuration:

# apcore.yaml
bindings:
  dir: "./bindings"          # Default scan directory
  pattern: "*.binding.yaml"  # File matching pattern (default)

The bindings section has exactly these two keys (schemas/apcore-config.schema.json $defs/BindingsConfig, additionalProperties: false).

The subject of this requirement is the binding loader, and its trigger is an invocation that does not name a directory. Discovery is a user-invoked operation, not a lifecycle event.

  1. When a binding loader (load_binding_dir / loadBindingDir / the equivalent public entry point) is invoked without an explicit directory argument, it MUST resolve the scan directory from bindings.dir following §9.2's precedence — environment variable (APCORE_BINDINGS_DIR) > configuration file > default "./bindings" — and it MUST match candidate files in that directory against bindings.pattern, resolved through the same precedence chain with the default "*.binding.yaml". The match is A25 (§9.2.3), applied to each entry's filename — not its path, and not recursively into subdirectories.
  2. When a binding loader is given an explicit directory argument, that argument wins. The full order is: explicit argument > bindings.dir (env > file > default). bindings.pattern follows the same order against its own explicit argument. An implementation MUST NOT read APCORE_BINDINGS_DIR directly at the loader; the environment tier arrives through the ordinary APCORE_* override mechanism of §9.2, so that one precedence chain governs the key.
  3. Implementations MUST NOT scan a binding directory automatically as part of client or framework initialisation. Loading bindings is an action the application takes, and an implicit startup scan would add filesystem I/O to every client and change behaviour for every deployment that merely happens to have a ./bindings directory.
  4. A relative bindings.dir is a path-typed value (§9.2.1); what it is resolved against is governed by §9.2.2 and is not decided here.
  5. When the resolved directory does not exist, the loader MUST fail, raising the implementation's binding-file error and naming the resolved directory in the message. It MUST NOT return an empty result. This holds whether the directory came from an explicit argument, from bindings.dir, or from the "./bindings" default.
  6. A pattern is never rejected. Every string is a valid A25 pattern (§9.2.3 requirement 2), so a loader MUST NOT raise on bindings.pattern for syntactic reasons; a pattern matching no file yields no modules, which is not an error in itself.

Rationale for clause 1: two matchers can both claim "glob" and still disagree on every pattern other than a leading * followed by a literal suffix, so the clause names the algorithm (A25), not the syntax.

Rationale for clause 5: a missing acl.root attaches nothing and MUST NOT synthesize an empty default-deny ACL (D-64), because ACL discovery is automatic and runs for every client, so a missing directory is the ordinary case. Binding loading is user-invoked (clause 3): an application that calls the loader expects bindings, so a missing directory is a mistake it has to be told about, not an empty result.

5.12.7 Validation Rules

Implementations MUST perform the following validations when loading binding files:

  1. module_id conforms to Canonical ID format (§2.7)
  2. target can be resolved to valid callable
  3. Schema is valid (explicitly defined or auto_schema can generate)
  4. module_id doesn't conflict with registered modules (§2.6)
  5. Binding file itself conforms to binding.schema.json (see schemas/binding.schema.json)

5.12.8 Error Codes

Error Code Description Trigger Condition
BINDING_INVALID_TARGET target format invalid target doesn't conform to module.path:callable_name format
BINDING_MODULE_NOT_FOUND Module path can't be imported import module_path fails; without runtime import, no handler supplied for target (§5.12.3)
BINDING_CALLABLE_NOT_FOUND Can't find target callable Can't find specified function/method in module
BINDING_NOT_CALLABLE Target not callable Resolved object is not callable
BINDING_SCHEMA_INFERENCE_FAILED Schema inference failed No explicit Schema and auto_schema can't generate, or auto_schema: false with no other schema source (deprecated alias: BINDING_SCHEMA_MISSING)
BINDING_SCHEMA_MODE_CONFLICT Conflicting schema sources An entry sets fields of more than one schema source (§5.12.2)
BINDING_STRICT_SCHEMA_INCOMPATIBLE Inferred schema not strict-compatible auto_schema: "strict" and an inferred schema fails the strict-mode check (§5.12.5)
BINDING_FILE_INVALID Binding file invalid File unreadable or malformed; bindings missing or not a list; entry without module_id / target; only one of input_schema / output_schema; invalid auto_schema value; schema_ref file missing or malformed; resolved binding directory missing (§5.12.6)

5.13 Display Overlay (Surface-Facing Presentation)

5.13.1 Normative Statement

Implementations MUST support an optional display section in binding entries, allowing users to override how modules are presented across different surfaces (CLI, MCP, A2A) without changing the canonical module_id or registry behavior.

The display overlay is a sparse override mechanism: binding files need only declare overrides for a subset of scanned modules. Modules without a display entry MUST use the scanner-provided values unchanged.

5.13.2 Motivation

Scanner-generated module IDs and descriptions are derived from source code artifacts (operationId, function names, docstrings) that are often too verbose, too technical, or inconsistent for AI/LLM consumption across CLI commands, MCP tool names, and A2A skill names. Different surfaces have different naming constraints:

Surface Name Constraints Example
CLI Shell-friendly, ≤40 chars recommended, no spaces pay-status
MCP Tool name, ≤64 chars, no spaces, alphanumeric + _- check_payment_status
A2A Skill name, natural language allowed, no hard limit Payment Status Checker

Without display, users must choose one module_id format that compromises across all surfaces. With display, each surface gets its optimal presentation while the canonical module_id remains stable for programmatic use.

5.13.3 Display Section Schema

bindings:
  - module_id: "credit_purchase.get_purchase_status_by_payment_intent.get"
    target: "myapp.purchase:get_purchase_status"
    description: "Auto-generated from docstring"

    # Display overlay — does NOT change module_id or registry behavior
    display:
      # Default overrides (apply to all surfaces unless surface-specific override exists)
      alias: "purchase-status"
      description: "Check purchase payment status by Stripe PaymentIntent ID"
      documentation: |
        Query Stripe PaymentIntent to get purchase status.
        Returns payment state, amount, and creation timestamp.
      guidance: |
        Use when the user asks about payment status or purchase confirmation.
        Do NOT use for refunds — use payment.refund instead.
        Always pass the Stripe PaymentIntent ID (pi_xxx), not the charge ID (ch_xxx).
        Returns null if the PaymentIntent has no associated purchase record.
      tags: ["billing", "payment"]

      # Surface-specific overrides (optional, take precedence over defaults above)
      cli:
        alias: "pay-status"
        description: "Check Stripe payment"
      mcp:
        alias: "check_payment_status"
        description: "Look up purchase payment status by Stripe PaymentIntent ID"
      a2a:
        alias: "Payment Status Checker"
        description: "I can check the status of any purchase payment"

Display Section Field Definitions:

Field Type Required Description
display object MAY Display overlay container
display.alias string MAY Default display name for all surfaces
display.description string MAY Override description for all surfaces
display.documentation string MAY Override extended documentation
display.guidance string MAY Usage guidance for humans and AI — when to use, when NOT to use, common mistakes, parameter tips. Read by both describe command and AI tool context injection. No length limit.
display.tags array MAY Override tags
display.cli object MAY CLI-specific overrides
display.cli.alias string MAY CLI command name. Shell-safe (^[a-z][a-z0-9_-]*$). Recommended ≤40 chars, not enforced.
display.cli.description string MAY CLI help text
display.cli.guidance string MAY CLI-specific guidance, overrides display.guidance for CLI surface
display.mcp object MAY MCP-specific overrides
display.mcp.alias string MAY MCP tool name. Hard limit: 64 chars (OpenAI function name spec). Pattern: ^[a-zA-Z_][a-zA-Z0-9_-]*$
display.mcp.description string MAY MCP tool description
display.mcp.guidance string MAY MCP-specific guidance injected into tool context for AI tool selection
display.a2a object MAY A2A-specific overrides
display.a2a.alias string MAY A2A skill name. Natural language allowed, no hard length limit.
display.a2a.description string MAY A2A skill description
display.a2a.guidance string MAY A2A-specific guidance for agent routing decisions

5.13.4 Sparse Overlay Semantics

The display section is a sparse overlay, not a full declaration:

  1. Module-level sparsity: If a binding file covers 2 out of 10 scanned modules, only those 2 get display overrides; the remaining 8 use scanner-provided values.

  2. Field-level sparsity: Within a display section, only specified fields override. Unspecified fields inherit from the next level in the resolve chain.

  3. Surface-level sparsity: Surface-specific sections (cli, mcp, a2a) only need to declare fields that differ from display.* defaults. Missing surface sections inherit the display.* defaults.

bindings:
  # Only override alias, everything else uses scanner values
  - module_id: "order.create_order.post"
    display:
      alias: "create-order"

  # Only override CLI description, MCP and A2A use display.description
  - module_id: "user.get_profile.get"
    display:
      description: "Retrieve user profile by ID"
      cli:
        description: "Get user profile"  # shorter for CLI help text

5.13.5 Resolve Priority Chain

Implementations MUST resolve display fields using the following priority chain (highest to lowest):

Algorithm: resolve_display(module_id, surface, binding_map, scanned_module)

For alias:
  1. binding_map[module_id].display.{surface}.alias    (surface-specific)
  2. binding_map[module_id].display.alias               (cross-surface default)
  3. scanned_module.metadata.suggested_alias             (scanner auto-alias)
  4. scanned_module.module_id                            (canonical ID)

For description:
  1. binding_map[module_id].display.{surface}.description
  2. binding_map[module_id].display.description
  3. binding_map[module_id].description                  (binding-level description)
  4. scanned_module.description                          (scanner-provided)

For documentation:
  1. binding_map[module_id].display.documentation
  2. binding_map[module_id].documentation                    (binding-level)
  3. scanned_module.documentation                            (scanner-provided)

For guidance:
  1. binding_map[module_id].display.{surface}.guidance
  2. binding_map[module_id].display.guidance
  3. null                                                (no scanner fallback — guidance is user-authored)

For tags:
  1. binding_map[module_id].display.tags
  2. binding_map[module_id].tags                         (binding-level)
  3. scanned_module.tags                                 (scanner-provided)

If binding_map[module_id] does not exist (no binding entry for this module), all fields resolve to the scanned_module values directly. guidance resolves to null.

5.13.6 Surface Alias Naming Constraints

Implementations MUST enforce the MCP alias constraint and SHOULD warn on CLI pattern violations:

Surface Pattern Max Length Level
CLI ^[a-z][a-z0-9_-]*$ Recommended ≤40, not enforced SHOULD warn
MCP ^[a-zA-Z_][a-zA-Z0-9_-]*$ 64 (hard limit, OpenAI spec) MUST enforce
A2A Free-form UTF-8 No hard limit No constraint
Default (display.alias) ^[a-z][a-z0-9_-]*$ 64 SHOULD warn

If a surface-specific alias violates a MUST constraint, implementations MUST reject it with a validation error. For SHOULD constraints, implementations SHOULD log a warning and continue.

5.13.7 Scanner suggested_alias Field

Framework scanners (e.g., OpenAPIScanner, NestJS decorator scanner) MAY produce a suggested_alias in ScannedModule.metadata as a hint for the display resolver. A simplified name goes into suggested_alias while module_id stays canonical (§5.13.8, §5.13.11):

Scanner behavior when simplify_ids=True:
  module_id                = canonical_name
  metadata.suggested_alias = simplified_name

This ensures the canonical module_id is always stable and predictable, while the simplified name is available as a fallback alias when no explicit display.alias is configured.

5.13.8 Architectural Layering

The display overlay system is structured as three layers. Each layer has a clear responsibility and MUST NOT leak concerns to adjacent layers.

Integration with the registry flow:

Scanner
  │ ScannedModule[]
  ▼
DisplayResolver (apcore-toolkit)          ← runs BEFORE RegistryWriter
  │ ResolvedModule[]
  ├──→ RegistryWriter
  │       │ registers FunctionModule into Registry
  │       │ stores display fields in FunctionModule.metadata["display"]
  │       ▼
  │    Registry (module_id → FunctionModule)
  │
  └──→ Surface (CLI / MCP / A2A)
          │ registry.get_definition(module_id)
          │   → reads display fields from metadata["display"]
          ▼
        Surface-specific formatting

DisplayResolver runs once, before RegistryWriter. The resolved display fields travel alongside the module through the registry as metadata["display"], and surfaces read them from there. This avoids surfaces needing direct access to the binding files at runtime.

Layer responsibilities:

┌─────────────────────────────────────────────────────────┐
│  Layer 1: Scanner (framework-specific)                  │
│  fastapi-apcore / nestjs-apcore / axum-apcore / ...    │
│                                                         │
│  Produces: ScannedModule with canonical module_id       │
│  Optionally: metadata.suggested_alias                   │
│  MUST NOT: modify module_id for display purposes        │
└─────────────────────┬───────────────────────────────────┘
                      │ ScannedModule[]
                      ▼
┌─────────────────────────────────────────────────────────┐
│  Layer 2: Display Resolver (apcore-toolkit)             │
│  Implemented once per language SDK                      │
│                                                         │
│  Inputs: ScannedModule[] + binding.yaml (optional)      │
│  Process: Parse display section, apply resolve chain    │
│  Produces: ResolvedModule[] (ScannedModule + display.*) │
│                                                         │
│  Pure data transformation — no framework dependency     │
│  Called by: RegistryWriter, YAMLWriter, surface init   │
└─────────────────────┬───────────────────────────────────┘
                      │ ResolvedModule[]
                      ▼
┌─────────────────────────────────────────────────────────┐
│  Layer 3a: RegistryWriter (apcore-toolkit)              │
│                                                         │
│  Stores display fields in FunctionModule.metadata       │
│  Key: "display" → serialized ResolvedDisplay struct     │
│  Registry key remains: canonical module_id              │
└─────────────────────┬───────────────────────────────────┘
                      │ Registry lookup: get_definition(module_id)
                      ▼
┌─────────────────────────────────────────────────────────┐
│  Layer 3b: Surface Formatter (per surface)              │
│  apcore-cli / apcore-mcp / apcore-a2a                  │
│                                                         │
│  Reads: descriptor.metadata["display"]                  │
│  CLI:  display.cli.alias → command name                 │
│  MCP:  display.mcp.alias → tool name                   │
│  A2A:  display.a2a.alias → skill name                  │
│                                                         │
│  Applies surface-specific formatting only               │
│  MUST NOT: re-resolve display fields                    │
└─────────────────────────────────────────────────────────┘

5.13.9 ResolvedModule Type Definition

Implementations MUST define a ResolvedModule type (or equivalent) that carries both the canonical module data and resolved display fields:

ResolvedModule:
  # Canonical fields (from ScannedModule, unchanged)
  module_id: string                           # Canonical ID, used for registry key
  target: string                              # Callable reference
  input_schema: object                        # JSON Schema
  output_schema: object                       # JSON Schema
  version: string
  annotations: ModuleAnnotations | null

  # Resolved display fields (per-surface)
  display:
    alias: string                             # Resolved default alias
    description: string                       # Resolved default description
    documentation: string | null              # Resolved default documentation
    guidance: string | null                   # Resolved guidance (null if not authored)
    tags: string[]                            # Resolved tags

    cli:
      alias: string                           # Resolved CLI alias
      description: string                     # Resolved CLI description
      guidance: string | null                 # Resolved CLI guidance
    mcp:
      alias: string                           # Resolved MCP alias
      description: string                     # Resolved MCP description
      guidance: string | null                 # Resolved MCP guidance (injected into tool context)
    a2a:
      alias: string                           # Resolved A2A alias
      description: string                     # Resolved A2A description
      guidance: string | null                 # Resolved A2A guidance

Fields with a resolve chain fallback to scanner data are always non-null after resolution: alias, description, tags. Fields that are user-authored with no scanner fallback may be null: documentation, guidance.

5.13.10 Implementation Responsibility Matrix

Who implements what:

Component Repo Responsibility
DisplayResolver apcore-toolkit-{lang} Parse binding.yaml display section; apply resolve priority chain (§5.13.5); produce ResolvedModule[]; validate aliases (§5.13.6)
RegistryWriter apcore-toolkit-{lang} Accept ResolvedModule[]; store display.* in FunctionModule.metadata["display"]
YAMLWriter apcore-toolkit-{lang} Run DisplayResolver before writing .binding.yaml; embed resolved display fields
Framework scanners fastapi-apcore, nestjs-apcore, axum-apcore, etc. Emit metadata.suggested_alias rather than modifying module_id; simplify_ids is deprecated (§5.13.11)
CLI surface apcore-cli-{lang} Read descriptor.metadata["display"].cli.alias for command name; display.cli.description for help text; display.cli.guidance for describe output
MCP surface apcore-mcp-{lang} Read display.mcp.alias for tool name; display.mcp.description; inject display.mcp.guidance into tool description context
A2A surface apcore-a2a-{lang} Read display.a2a.alias for skill name; display.a2a.description; display.a2a.guidance for agent card
apcore core apcore-{lang} None specific to display: Registry, Executor and FunctionModule carry the resolved fields in metadata, which accepts arbitrary keys.

apcore-toolkit implementation checklist (per language):

  1. Define ResolvedModule type (§5.13.9)
  2. Implement DisplayResolver: a. Parse display section from binding YAML entries b. Build binding_map: dict[module_id → DisplayConfig] c. For each ScannedModule, apply resolve priority chain (§5.13.5) d. alias, description, tags always non-null; documentation, guidance may be null e. Validate surface aliases per §5.13.6; MUST error on MCP >64 chars, SHOULD warn on CLI pattern violation
  3. RegistryWriter accepts ResolvedModule[] and stores display in metadata["display"]
  4. YAMLWriter embeds resolved display fields in output binding files

Surface checklist (CLI / MCP / A2A, per language):

  • Read display fields from descriptor.metadata["display"] (populated by RegistryWriter)
  • Fall back to descriptor.module_id / descriptor.description if metadata["display"] is absent (backward compatibility with modules registered without DisplayResolver)
  • Never call DisplayResolver at surface time — display resolution is a one-time operation at registration

Conformance tests — display_resolve.json in the apcore-toolkit conformance suite (apcore-toolkit/conformance/fixtures/) covers:

Test ID Scenario
001 No binding entry → all fields use scanner values
002 display.alias only → all surfaces use it
003 Surface-specific override takes precedence
004 Field-level sparsity
005 suggested_alias fallback
006 Full chain, surface-specific wins
007 Binding-level description fallback
008 display.alias overrides suggested_alias
009 display.tags override
010 10 modules, only 2 have binding entries
011 guidance resolve chain
012 guidance is null when not authored
013 MCP alias >64 chars → MUST error
014 CLI alias with spaces → SHOULD warn, fallback

5.13.11 Migration from simplify_ids

The simplify_ids parameter on framework scanners is DEPRECATED in favor of the display overlay system. Migration path:

Deprecated Preferred
OpenAPIScanner(simplify_ids=True) OpenAPIScanner() produces canonical ID + metadata.suggested_alias
create_cli(simplify_ids=True) create_cli() + binding.yaml display.cli.alias
create_mcp_server(simplify_ids=True) create_mcp_server() + binding.yaml display.mcp.alias

Implementations SHOULD support simplify_ids as a convenience parameter during a transition period, mapping it to metadata.suggested_alias internally. Implementations MUST log a deprecation warning when simplify_ids=True is used.

5.14 Convention Module Discovery (Zero-Decorator Modules)

5.14.1 Normative Statement

Implementations MAY support a convention-based module discovery mechanism that allows plain functions (without decorators or imports) to be automatically registered as apcore modules. This provides the lowest possible barrier for users who want to add custom CLI commands, MCP tools, or A2A skills.

Convention Module Discovery is an optional capability. Implementations that do not support it MUST still accept modules registered via @module decorators, YAML bindings, or class-based definitions.

5.14.2 Motivation

Without it, adding a custom command to an apcore-based CLI requires learning the @module decorator API or writing YAML binding files. For users who just want to add a simple deploy script or utility command, this is unnecessary friction. Convention Module Discovery lets users drop a plain function file into a designated directory and have it auto-discovered as a module — with schema inference from type annotations and description extraction from docstrings.

5.14.3 Commands Directory Convention

Implementations that support Convention Module Discovery MUST scan a designated directory (default: commands/) for source files containing plain functions.

commands/                    ← convention directory
  deploy.py                  ← one file = one or more modules
  backup.py
  monitoring/                ← subdirectories become group prefixes
    health.py
    metrics.py

5.14.4 Function Discovery Rules

Implementations MUST apply the following rules when scanning a convention source file:

Rule Description
Public functions only Functions starting with _ are ignored.
Top-level only Nested functions and class methods are not discovered.
Type annotations required Functions without parameter type annotations SHOULD be skipped with a warning.
Docstring → description The first line of the function's docstring becomes the module description. Functions without docstrings SHOULD use "(no description)".
Return type If the function has a return type annotation, it is used to generate output_schema.

5.14.5 Module ID Generation

The module ID for a convention-discovered function is generated as:

module_id = "{prefix}.{function_name}"

Where: - prefix is derived from the file path relative to the commands directory: commands/deploy.py → deploy, commands/monitoring/health.py → monitoring.health - function_name is the Python/TypeScript/Rust function name

If the source file contains a module-level MODULE_PREFIX constant, it MUST override the file-path-derived prefix:

MODULE_PREFIX = "ops"  # overrides file-path prefix

If the source file contains a module-level CLI_GROUP constant, it is stored in metadata["display"]["cli"]["group"] for grouped CLI commands:

CLI_GROUP = "ops"  # sets display.cli.group for all functions in this file

5.14.6 Schema Inference

Implementations MUST generate input_schema from the function's parameter type annotations using the same type-to-JSON-Schema mapping defined in §5.11.5.

# commands/deploy.py
def deploy(env: str, tag: str = "latest", replicas: int = 3) -> dict:
    """Deploy application to target environment."""
    ...

Inferred input_schema:

{
  "type": "object",
  "properties": {
    "env": {"type": "string"},
    "tag": {"type": "string", "default": "latest"},
    "replicas": {"type": "integer", "default": 3}
  },
  "required": ["env"]
}

Parameters with default values are not included in required. The self and ctx parameters (if present) are always excluded.

5.14.7 Metadata Conventions

Convention source files MAY define module-level constants to provide additional metadata:

Constant Type Maps to Example
MODULE_PREFIX str Module ID prefix (overrides file path) MODULE_PREFIX = "ops"
CLI_GROUP str metadata["display"]["cli"]["group"] CLI_GROUP = "ops"
TAGS list[str] Module tags field TAGS = ["devops", "deploy"]

Function-level constants are not supported; use @module decorator for per-function metadata control.

5.14.8 Cross-language Syntax Reference

Language File Extension Function Pattern Type System
Python .py def func(param: type) -> type: PEP 484 type hints
TypeScript .ts export function func(param: type): type TypeScript types
Rust .rs pub fn func(param: Type) -> Type Rust types + #[derive(JsonSchema)]

5.14.9 Integration with Display Overlay (§5.13)

Convention-discovered modules are subject to the same display overlay system as any other module. A binding.yaml file MAY reference convention-discovered modules by their generated module_id to apply display overrides:

bindings:
  - module_id: deploy.deploy
    display:
      alias: deploy
      cli:
        group: ops
        alias: deploy
        description: Deploy app to production

This allows users to start with zero-config convention discovery, then progressively add display customizations without changing the function code.

5.15 Edge Case Handling

Implementations MUST handle module edge cases according to the following table:

5.15.1 execute() Return Value Edges

Scenario Behavior Level
execute() returns None Throw MODULE_EXECUTE_ERROR ("Return value cannot be None") MUST
execute() returns non-Map/dict type Throw MODULE_EXECUTE_ERROR ("Return value must be Map") MUST
Return value doesn't match output_schema Throw SCHEMA_VALIDATION_ERROR MUST
execute() throws non-ModuleError exception Wrap as MODULE_EXECUTE_ERROR (cause points to original exception) MUST
execute() returns object with non-serializable objects SHOULD log warning but don't enforce check SHOULD

5.15.2 Module Dependency Loading Failures

Scenario Behavior Level
Module in dependencies.requires doesn't exist Throw DEPENDENCY_NOT_FOUND, refuse loading MUST
Module in dependencies.optional doesn't exist Log INFO, continue loading MUST
Module in dependencies.requires fails to load Throw MODULE_LOAD_ERROR, refuse loading MUST
Module in dependencies.optional fails to load Log WARN, continue loading MUST
Module in dependencies.requires exists but its registered version does not satisfy the declared version constraint Throw DEPENDENCY_VERSION_MISMATCH, refuse loading MUST
Module in dependencies.optional exists but its registered version does not satisfy the declared version constraint Log WARN, skip the dependency edge, continue loading MUST
Reverse dependency (A depends on B, B also depends on A) Throw CIRCULAR_DEPENDENCY MUST
Indirect circular dependency (A → B → C → A) Throw CIRCULAR_DEPENDENCY MUST
Load order cannot be completed but no cycle exists (e.g. a batch member depends on a module that is registered but not part of this batch, so its in-degree never reaches zero) Throw MODULE_LOAD_ERROR naming the blocked modules — MUST NOT report CIRCULAR_DEPENDENCY MUST

A stalled topological sort is not a cycle (D-79). A Kahn-style sort that ends with nodes remaining has two causes: a dependency cycle, or a dependency missing from the batch. They need opposite fixes — a cycle means breaking a dependency edge, a stall means supplying the missing dependency — so the two rows above report them with different codes. An implementation MUST NOT emit a fabricated cycle_path.

5.15.3 Module Lifecycle Edges

Scenario Behavior Level
on_load() hook throws exception Throw MODULE_LOAD_ERROR (cause points to original exception), terminate loading MUST
on_unload() hook throws exception Log ERROR, continue unload process MUST
Module called before load completion Wait for load completion or throw MODULE_NOT_FOUND SHOULD
Module called after unload Throw MODULE_NOT_FOUND MUST
Repeated discover() of same module If metadata.yaml unchanged, skip (idempotent) MUST
Hot reload while module executing See §12.7.4 Hot Reload Race Conditions MUST

Note: - Dependency topological sorting uses algorithm A07 (§5.3) - Circular dependency detection should complete in discover() phase, avoiding runtime failures

5.16 Pipeline Control Flow Requirements

Implementations MUST enforce the following control flow invariants on the execution pipeline (see §5.6 and docs/features/core-executor.md).

  1. Fail-fast on step error. When a pipeline step raises an error, implementations MUST stop pipeline execution immediately and propagate the error wrapped in a PipelineStepError carrying the failing step name and the original error. Implementations MUST NOT continue to the next step unless that step is explicitly configured with ignore_errors: true.

  2. O(1) step name resolution. Implementations MUST use a hash map (dictionary) keyed by step name for all step lookups during execution. Implementations MUST NOT perform linear scans over a step list to locate a step by name. This requirement MUST be enforced at code review time.

  3. Replace semantic for step configuration. When configure_step targets a step name that already exists in the current pipeline strategy, implementations MUST replace the existing step definition entirely with the step supplied. The declarative configure: directive (§5.16.1) instead overrides only the fields it names; the step keeps its implementation and every field not named. In both cases implementations MUST NOT create a duplicate step entry or append a second handler under the same name, and the step MUST retain its original position in the execution order.

  4. run_until termination predicate. Implementations MUST support a run_until option of the pipeline engine — supplied to the engine's run or set on the pipeline context, not an Executor.call() option — that accepts a predicate receiving the current PipelineState (step name, accumulated outputs, context) and returning a boolean. When the predicate returns true after step N completes, implementations MUST skip all remaining steps and return the accumulated result from steps 1 through N. If the predicate never returns true, the pipeline runs to completion normally.

  5. Step-level middleware ordering. Implementations SHOULD support middleware scoped to individual pipeline steps. When both global middleware and step-level middleware are registered, global middleware MUST execute before step-level middleware in the before-phase, and after step-level middleware in the after-phase.

  6. A configured pipeline: section MUST be applied. When the loaded configuration carries a pipeline section (remove / configure / steps, §5.16.1) and the caller supplied no explicit strategy, implementations MUST build the execution strategy from it. An implementation MUST NOT accept the section, validate it, and then execute the default pipeline.

Rationale: failing to remove a configured step is fail-safe, but failing to insert one is not — a declared audit, rate-limiting or authorization step would silently never run, and the pipeline read in configuration would not be the pipeline that executes.

  1. Removing a security step MUST warn. When applying remove, an implementation MUST emit a diagnostic naming each removed step that belongs to the security set — acl_check and approval_gate — once for each configuration load that removes them. Removing either step withdraws a protection rather than a convenience, so the operator is told. The diagnostic is a load-time notice, not a refusal: the configuration is valid, the operator wrote it deliberately, and an implementation MUST NOT reject it.

5.16.1 Declarative Pipeline Configuration (pipeline:)

The pipeline section of apcore.yaml (schemas/apcore-config.schema.json $defs/PipelineConfig) customizes the standard strategy (context_creation … return_result, execution-pipeline.md). It has three keys, all optional, and implementations MUST apply them to the standard strategy in this order:

  1. remove — names of steps to take out of the strategy.
  2. configure — a map from step name to field overrides for a step already in the strategy.
  3. steps — custom step entries to insert.
pipeline:
  remove: [approval_gate]
  configure:
    call_chain_guard:
      timeout_ms: 2000
  steps:
    - name: rate_limit
      type: rate_limit              # key into the step-type registry
      after: acl_check              # or: before: <step name>
      match_modules: ["api.*"]
      config:
        max_per_minute: 100         # constructor arguments for the step factory
    - name: custom_audit
      handler: "my_app.steps:CustomAuditStep"   # dynamic import, where supported
      before: return_result

remove. A name that identifies no step in the strategy MUST fail the load with PIPELINE_CONFIGURATION_ERROR. A step the strategy marks non-removable cannot be removed (STEP_NOT_REMOVABLE). Removing acl_check or approval_gate is valid and warns (requirement 7).

configure. Each key is a step name; each value overrides fields of that step, which keeps its position (requirement 3). The configurable field set is closed — exactly match_modules, ignore_errors, pure and timeout_ms ($defs/ConfigurableStepFields) — and it applies to any step present, built-in steps included. Implementations MUST fail the load with PIPELINE_CONFIGURATION_ERROR, naming every offending key, when an entry carries any other key or names a step not present in the strategy.

Governance gates cannot be weakened by configure (D-130). On the built-in gate steps acl_check and approval_gate, implementations MUST fail the load with PIPELINE_CONFIGURATION_ERROR, naming the step and the key, for ignore_errors: true and for any match_modules (an empty list included), and on approval_gate for pure: true. The same values MUST be rejected when set through a programmatic step-configuration API. timeout_ms remains configurable, and writing a field's default value is accepted. Rationale: ignore_errors turns a denial into a warning and runs the call, match_modules exempts every module it does not match, and pure: true makes validate() run the approval gate and consult the ApprovalHandler during a dry run (§12.8). Removing a gate step stays possible and warns (requirement 7) — an explicit removal is visible in governance_state(), a weakened gate is not. Pinned by ../../conformance/fixtures/gate_step_configure.json.

The other step-entry fields are structural (name, type, handler, after, before) or constructor arguments (config), and none of them means anything for a step that already exists. A step's requires / provides capability contract is declared by its implementation and is not configurable: configuration able to rewrite it would disable the PIPELINE_DEPENDENCY_ERROR check (execution-pipeline.md § ExecutionStrategy).

The canonical spelling of every field is snake_case, as in the schema. An implementation MAY additionally accept its idiomatic spelling (for example camelCase) at its programmatic API boundary, but MUST accept the canonical spelling; a configuration file carries the canonical spelling only.

steps. Each entry is a $defs/PipelineStep object:

Field Type Description
name string Step name; replaces the name the step factory gives the step. Required by the schema.
type string Key into the step-type registry (register_step_type / registerStepType).
handler string "module.path:Name" reference resolved by dynamic import.
config object Constructor arguments for the step factory. Default {}.
match_modules array of string Module-ID patterns (algorithm A08, §6.2) restricting the step to matching modules.
ignore_errors boolean Log step errors instead of aborting the pipeline (requirement 1). Default false.
pure boolean Marks the step side-effect-free. Default false.
timeout_ms integer Per-step timeout in milliseconds; 0 means none. Default 0. A step that runs past it fails with MODULE_TIMEOUT, and the caller of call() receives that code (D-142).
after string Insert immediately after the named step.
before string Insert immediately before the named step.
  1. An entry carrying a key outside these ten MUST fail the load with PIPELINE_CONFIGURATION_ERROR before that step is constructed.
  2. A schema-valid configuration entry contains exactly one of type and handler ($defs/PipelineStep). type resolves against the step-type registry. handler resolves through the host language's dynamic import, with config passed to the resolved factory. An entry that cannot resolve its factory fails the load. An implementation that cannot load code at runtime MUST reject every entry carrying handler with PIPELINE_HANDLER_NOT_SUPPORTED.
  3. The entry's name, match_modules, ignore_errors, pure and timeout_ms apply to the constructed step.
  4. A schema-valid configuration entry contains exactly one of after and before ($defs/PipelineStep). An entry with neither, or whose anchor names no step in the strategy, MUST fail the load with PIPELINE_CONFIGURATION_ERROR.
  5. Entries are inserted in declaration order, after remove and configure have been applied. Each anchor is resolved against the strategy as it stands when its entry is inserted, so an entry may anchor on a step inserted by an earlier entry and cannot anchor on a removed one. A step whose name is already in the strategy fails the load with STEP_NAME_DUPLICATE.

SDK builder compatibility. A raw mapping passed directly to a strategy builder can bypass configuration Schema validation. Python and TypeScript first try a registered type when such a mapping supplies both factory fields, then fall back to handler if the type is unknown. Rust rejects any handler. All three builders use after when supplied with both anchors. Use one factory field and one anchor in portable configuration. Code that constructs a step instance can insert it directly through the strategy's insert_before or insert_after API.

The optional validation.pipeline.* limits bound the step names and timeouts the section declares (§9.1.2).

Errors:

Error Code Trigger Condition
PIPELINE_CONFIGURATION_ERROR remove or configure names a step not in the strategy; a configure key outside the four configurable fields; ignore_errors: true or match_modules configured on acl_check / approval_gate, or pure: true on approval_gate; a steps key outside the ten; an entry with no anchor; an anchor naming no step
PIPELINE_HANDLER_NOT_SUPPORTED handler in an implementation that cannot load code at runtime
STEP_NOT_REMOVABLE remove names a step the strategy marks non-removable
STEP_NAME_DUPLICATE An inserted step's name is already in the strategy

6. ACL Specification

6.1 ACL Files

# acl/global_acl.yaml

$schema: "https://apcore.dev/acl/v1"
version: "1.0.0"

# Global rules (evaluated in order, first-match-wins)
rules:
  # Rule 1: System internal modules unrestricted
  - callers: ["@system"]
    targets: ["*"]
    effect: allow
    description: "System calls are always allowed"

  # Rule 2: API layer can only call orchestration layer
  - callers: ["api.*"]
    targets: ["orchestrator.*"]
    effect: allow
    description: "API layer calls orchestration layer"

  # Rule 3: Orchestration layer can call executor layer
  - callers: ["orchestrator.*"]
    targets: ["executor.*"]
    effect: allow
    description: "Orchestration layer calls executor layer"

  # Rule 4: Forbid executor layer calling API layer
  - callers: ["executor.*"]
    targets: ["api.*"]
    effect: deny
    description: "Block reverse calls from executor to API"

  # Rule 5: Everyone can call common modules
  - callers: ["*"]
    targets: ["common.*"]
    effect: allow
    description: "Common modules accessible to all"

  # Rule 6: Conditional access to payment modules
  - callers: ["api.*"]
    targets: ["executor.payment.*"]
    effect: allow
    description: "Payment access restricted to admin/finance"
    conditions:
      identity_types: ["user"]
      roles: ["admin", "finance"]
      max_call_depth: 5

# Default policy
default_effect: deny

# Audit configuration
audit:
  enabled: true
  log_level: info
  include_denied: true

ACL Rule Fields:

Field Required Type Description
callers MUST list[string] Caller patterns, at least one (OR logic: any match is sufficient). Arity is closed — §6.2.1.
targets MUST list[string] Target patterns, at least one (OR logic: any match is sufficient). Arity is closed — §6.2.1.
effect MUST "allow" \| "deny" Access decision
approval MAY "required" \| "not_required" Whether a call this rule allows must be put to a human; absent means not_required (§6.1.6)
description SHOULD string Human-readable rule description
conditions MAY object Additional conditions (all must pass, AND logic)

Conditions sub-fields:

Field Type Description
identity_types list[string] The current actor type must be in the list
roles list[string] At least one current actor role must overlap
scopes Nonempty list[string] The current actor must have every listed effective scope (§6.11)
subject_types Nonempty list[string] The root subject type must be in the list (§6.11)
subject_roles Nonempty list[string] At least one root subject role must overlap (§6.11)
max_delegation_depth integer (0–8) The number of active delegation links must not exceed the threshold (§6.11)
max_call_depth integer Call chain length must not exceed threshold
arguments object Predicates over the call's argument keys (§6.1.7)
$or list[object] Compound: passes if any sub-condition object passes (each sub-object's keys are AND-ed internally). Sub-objects MAY contain further compound operators.
$not object Compound: passes if the wrapped condition object fails. An empty object MUST evaluate to false (fail-closed).

Compound operators and async sub-conditions. Implementations MUST evaluate $or / $not sub-conditions using the same evaluator mode (sync or async) as the enclosing call. An async-only sub-condition under a sync evaluator MUST be treated as unevaluable per §6.1.1 — not as unsatisfied — and SHOULD emit a warning. Handlers SHOULD therefore be registered for both sync and async paths.

The table above lists the conditions every implementation provides. It is not a closed set: implementations MUST expose a registration API (register_condition / registerCondition and their async counterparts) so a deployment can add its own condition keys. A key outside the table is therefore not invalid by construction — it is valid exactly when a handler has been registered for it, which is a runtime property, not a document property.

6.1.1 Unevaluable conditions

A condition that is false and a condition that cannot be evaluated are different outcomes and MUST NOT be represented the same way.

  • A condition is false when a registered handler ran to completion and returned false, having understood the value it was given. This is an ordinary non-match: the rule does not apply to this call, and evaluation continues with the next rule.
  • A condition is unevaluable when the implementation cannot obtain an answer to the condition as written.

"Unevaluable" is a principle, not a closed list. The situations below are the ones every implementation meets; an implementation that encounters another MUST classify it by the principle, and MUST NOT default it to UNSATISFIED because it is unlisted:

  1. the condition key has no registered handler resolvable on the evaluation path in use (§6.1.3);
  2. the handler raised, threw, or panicked;
  3. the handler was asynchronous and could not be resolved on the synchronous check() path (§6.1.3);
  4. the condition's value is malformed for its key — $or whose value is not a list, an element of $or that is not a condition object, $not whose value is not an object, or any value a handler cannot interpret as an instance of what that key means;
  5. conditions itself is not a mapping.

Why 4 and 5 are unevaluable and not merely false

A handler handed $or: "not-a-list" can return false, run to completion, and look from the outside exactly like a handler that answered "no". It has not answered the author's question — there is no question to answer, because the rule is malformed. Recording that as UNSATISFIED would leave a deny rule carrying $or: "typo" silently inert. The same holds for a conditions value that is not a mapping, which a YAML load rejects but direct construction and runtime rule insertion do not.

Treating an unevaluable condition as a plain non-match is unsafe, and unsafe asymmetrically. A rule's effect decides which direction "does not match" points:

Rule effect Condition is false Condition is unevaluable
allow rule does not match → continue rule does not match → continue (MUST NOT grant); a carried approval: required becomes pending (rule 5)
deny rule does not match → continue rule MUST take effect → the call is denied

Stated normatively:

  1. When a rule's conditions are unevaluable, the implementation MUST resolve the rule toward refusing access: a deny rule MUST match and deny; an allow rule MUST NOT match and MUST NOT grant.
  2. The implementation MUST record the failure in the audit entry: handler_error (§6.3.1) MUST be non-null and MUST name the offending condition's path (§6.1.4) and the reason. When more than one condition in a single check() is unevaluable, handler_error MUST report every one it determined, ordered lexicographically by condition path and separated by "; ". Ordering by path rather than by evaluation order is required because the two are not the same across languages — serde_json's map is ordered while Python dict and JavaScript objects preserve insertion order — and by path rather than by key because a key may occur more than once at different points in a nested $or / $not tree, which leaves ordering by key undefined. Which failures are guaranteed to be determined is §6.1.4's subject.
  3. The implementation MUST emit a warning naming the condition path, the rule's index, and the rule's effect. The effect is required in the message because a misconfigured deny rule is the consequential case.
  4. An unevaluable condition MUST NOT raise out of check(). §6.3's return contract holds: check() returns a boolean.
  5. An unevaluable allow rule's approval requirement is pending, not discarded. Rule 1's "MUST NOT grant" means the rule steps aside from the authorization decision. A rule carries a second, independent axis — its approval requirement (§6.1.6) — and that axis MUST NOT be lost when the first resolves to unevaluable:

    • Record and continue. When an allow rule carrying approval: required is unevaluable, the implementation MUST record a pending approval requirement and continue scanning. The rule itself still MUST NOT grant, per rule 1.
    • Compose on grant. When authorization is subsequently granted — by a later allow rule or by default_effect: allow — the reported requirement MUST be the disjunction of the pending requirement and the granting rule's own. matched_rule_index names the rule that decided access, which is the granting rule and not the unevaluable one that raised the requirement: the same call therefore reports a different index depending on whether the projection was available, and that is correct rather than an inconsistency to reconcile. A pending requirement carried through default_effect yields approval_required: true with matched_rule_index: null, which is a legal combination.
    • A denial clears it. When the final decision is deny, the approval requirement MUST be reported as false, and matched_rule_index MUST continue to name the rule that actually decided rather than the unevaluable one. "Denied and put it to a human" is the same meaningless state §6.1.6 rule 2 rejects on a single rule, and it is no more meaningful assembled from two.
    • Scope is required, and the existing classification already supplies it. A rule whose callers / targets patterns do not match this call raises no pending requirement: a rule written about one caller MUST NOT attach a human to calls it was never written about. This needs no pattern test at the point the requirement is raised, and an implementation MUST NOT add one — §6.1.4 rule 4 already resolves a well-formed non-matching rule to UNSATISFIED without consulting its conditions, so it never reaches this rule at all, while §6.1.4.1 resolves a malformed-pattern rule to UNEVALUABLE before any pattern is read, so it does. Re-reading a malformed pattern field here is precisely the fail-open §6.1.4.1 exists to prevent.
    • Unknowable scope counts as scope. A rule that is unevaluable because its own callers / targets field is malformed (§6.1.4.1) MUST raise the pending requirement. Its scope cannot be read, so it cannot be shown not to apply here. This is the one point at which a requirement attaches without a demonstrated pattern match, and it is consistent in severity with what the same malformed rule already does under deny, where an unreadable scope denies every call.

    A pending requirement does not alter the audit record of the failure: handler_error still records the unevaluable condition per rule 2, and a pending requirement neither suppresses nor substitutes for it. Rule 3's warning MUST additionally name the requirement as pending when one is raised. A warning that says only "the allow rule does not match and MUST NOT grant" reads as "this rule had no further effect", which is wrong on a call that a later rule then grants with the requirement attached.

Why the requirement outlives the rule that carried it

The shape §6.1.7 is written for is a narrow approval rule ahead of a broad allow — git push --force needs a human, git push does not. If an unevaluable narrow rule merely stepped aside, the broad rule would grant with no requirement of its own: allow with approval_required: false on exactly the call the operator gated, and a matched_rule_index pointing at a rule that never mentioned approval. default_effect: allow would reach the same end with no second rule at all. §6.9 rule 4 applies the same principle one layer out: a policy may add a requirement and MUST NOT remove one the ACL set.

Requiring a human, rather than denying outright, is the right resolution: the condition that could not be evaluated is the one that decides whether this call is the dangerous one, so refusing would turn every ordinary git push into a hard failure — the over-refusal §6.1.7 exists to eliminate.

Propagation through AND and the compound operators. A conditions object combines its keys with AND, and $or / $not nest further objects, so the three outcomes need composition rules. They are three-valued (Kleene) logic, and they are normative — without them the same rule set resolves differently in different implementations:

Combination Result
AND (a conditions object's keys) — any child UNSATISFIED UNSATISFIED (an outright "no" wins, even if a sibling was unevaluable)
AND — no child UNSATISFIED, at least one UNEVALUABLE UNEVALUABLE
AND — every child SATISFIED SATISFIED
$or — any child SATISFIED SATISFIED (an outright "yes" wins, even if a sibling was unevaluable)
$or — no child SATISFIED, at least one UNEVALUABLE UNEVALUABLE
$or — every child UNSATISFIED UNSATISFIED
$not — child SATISFIED UNSATISFIED
$not — child UNSATISFIED SATISFIED
$not — child UNEVALUABLE UNEVALUABLE

$not of an unevaluable condition MUST NOT yield SATISFIED. Negating "no answer" into "yes" would let a misspelled key inside a $not satisfy the very rule it was meant to gate — the bypass this section exists to close, reintroduced one nesting level down.

An implementation MAY short-circuit AND on the first UNSATISFIED child and $or on the first SATISFIED child, and is then not required to evaluate the remaining children. It MUST NOT short-circuit on UNEVALUABLE: the remaining children may still produce the decisive outcome.

Short-circuiting applies to handler execution only, never to the precheck: §6.1.4 requires the whole conditions tree to be examined for structural and registry faults before any handler runs, so a misspelled key or a malformed operator is found and recorded whether or not a sibling would have short-circuited past it.

What remains order-dependent is narrow and stated deliberately. {"roles": ["admin"], "flaky": true}, where flaky is registered but its handler throws, evaluated for a caller with no admin role: the precheck passes both keys, and an implementation that reaches roles first short-circuits AND on UNSATISFIED and never runs flaky. It therefore reports no handler_error, while an implementation that reaches flaky first reports one. Both are conformant — the decision is identical, and only an execution-origin diagnostic differs. An implementation that prefers fully deterministic diagnostics MAY evaluate every child; §6.1.4's guarantee covers configuration faults either way.

Why an unevaluable condition cannot simply be a non-match

If an unevaluable condition only made the rule not match, deny rules would be the ones that fail open: a single misspelled key — role: for roles: — would turn a rule its author believed was blocking into decoration, and the call would fall through to the next rule or to default_effect. §7.9.4(4) requires that a typo cannot silently disable an execution policy; this section extends the same guarantee to ACL rules.

6.1.2 Load-time validation of condition keys

Condition handlers are registered at runtime into a process-wide registry, and an ACL can legitimately be loaded before a deployment registers its custom handlers — configuration-driven discovery (acl.root, §9.1.1) commonly runs during framework bootstrap, ahead of application code. Load-time validation therefore MUST NOT be fatal:

  1. Loading or constructing an ACL MUST NOT fail because a rule references a condition key that has no registered handler at that moment.
  2. Loading or constructing an ACL MUST emit a warning for each such key, naming the rule index, the key, and the rule's effect.
  3. Implementations MUST provide an explicit validation entry point — named validate_rules (validateRules), not validate_conditions, because it reports structural faults in callers and targets as well (§6.1.4.1), returning findings of a type named RuleValidationFinding in every SDK — that reports every rule failing §6.1.4's precheck, so a deployment can assert on the result once registration is complete. It MUST NOT mutate the ACL, and MUST report, per finding, at least: rule index, fault path (§6.1.4), the offending key where one exists, rule effect, and the two resolvability flags of §6.1.3. Findings MUST be ordered by rule index, then lexicographically by path — by path and not by key, because a nested $or may carry the same key at several positions and ordering by key alone is then undefined.
  4. Every ACL entry point that accepts rules is covered — file loading, direct construction, and runtime rule insertion alike. An implementation MUST NOT validate only the file-loading path.

6.1.3 Sync and async handler registries

"Registered" is not one property. Implementations keep two condition-handler registries, and async_check() consults the async registry first and then falls back to the sync one, while check() consults only the sync registry. The asymmetry is therefore one-directional:

Registered as check() (sync) async_check()
sync only — the built-in identity_types, roles, max_call_depth, arguments resolves resolves (falls back)
both — the built-in $or, $not resolves resolves
async only does not resolve → UNEVALUABLE (§6.1.1) resolves
neither UNEVALUABLE UNEVALUABLE

An async-only key is thus a live rule on one path and an unevaluable condition on the other. Four consequences are normative:

  1. §6.1.2's validator MUST report sync_resolvable and async_resolvable as separate flags per finding, and MUST NOT collapse them into a single boolean. Without this, the same ACL validates differently depending on which registry an implementation consults, and an operator cannot tell an unregistered key from a key that is merely unusable on the path their application calls.
  2. Both flags mean resolvable on that evaluation path, not "present in that registry". async_resolvable is therefore the union of the two registries, because async_check() falls back to the sync one — a key registered only synchronously is async_resolvable. They are named *_resolvable rather than *_registered for exactly this reason: async_registered would read as a lookup in the async registry and be false for every built-in leaf handler, which resolves on both paths.
  3. For a fault that has no condition key — a malformed pattern field, a non-mapping conditions, a malformed $or element — both flags MUST be false and the finding's key field MUST be null. A malformed operator value is the other case and is not keyless: $or: "nope" is a fault attached to the $or key, so the finding MUST carry $or as its key, at path $or, with both flags still false. The flags describe the fault, not the key's registration — $or is always registered, and reporting it resolvable would say the malformed rule is fine. The flags answer "can this fault be resolved by evaluating on that path", and a structural fault resolves on neither. They MUST NOT be read as "is the key registered", which would report a malformed $or value as resolvable on both paths because $or itself has a handler.
  4. A finding MUST be emitted whenever sync_resolvable is false, including when async_resolvable is true — an application calling check() has a condition it cannot evaluate. A caller that only ever uses async_check() may choose to ignore such a finding; that choice belongs to the caller, not to the validator.

A key that resolves on both paths is not a finding.

This is diagnostics, not enforcement. The guarantee that a broken deny rule cannot silently pass traffic is §6.1.1's, and holds whether or not anyone calls the validator.

The executor's ACL step MUST take the async path (D-105). An implementation whose ACL exposes an async evaluation entry point MUST use it from the executor's ACL step (acl_check), falling back to the synchronous one only when no async entry point exists. On the sync path a condition registered through register_async_condition is async only — the third row of the table above — and resolves to UNEVALUABLE, so an allow rule carrying it would stop granting and a deny rule carrying it would deny unconditionally rather than when the handler says so. Both directions are wrong, and the async condition registry would be unreachable from the only path that enforces.

6.1.4 Structural and registry precheck

Two requirements pull against each other unless the work is split. §6.1.1 rule 2 wants handler_error to be deterministic across implementations; the composition rules permit short-circuiting, which makes evaluation order — and therefore which failures are even reached — implementation-defined. And §6.5 keeps "conditions present, no context supplied" a non-match, which would let a misspelled key on a context-less call escape §6.1.1 entirely.

Both are resolved by separating what can be decided without a context and without running anything from what cannot.

The precheck. Before evaluating a rule, an implementation MUST examine that rule's structure — including its entire conditions tree, every branch nested inside $or and $not — and determine:

  • whether callers and targets are each a list of strings (§6.1.4.1);
  • whether conditions is a mapping (§6.1.1 case 5);
  • for each condition key, whether a handler is resolvable on the evaluation path in use (§6.1.1 case 1, §6.1.3);
  • for each compound operator, whether its value has the required shape (§6.1.1 case 4).

The precheck is context-independent and MUST NOT invoke any handler. It examines structure and the registries only.

Ordering, normatively:

  1. The precheck MUST run before §6.5's "conditions present but no context provided" check. A rule that fails the precheck is unevaluable whether or not the call supplied a context: a misspelled key is misconfigured regardless of who is calling. Otherwise conditions: {mispelled: true} on a deny rule would pass traffic whenever the caller carried no identity.
  2. A rule that passes the precheck and then finds no context still takes §6.5's path and does not match. A registered, context-dependent condition — roles, identity_types, max_call_depth — MUST NOT be treated as unevaluable merely because this call carried no context. It is answerable in principle; this caller just did not supply the input. §6.5 governs this case.
  3. The precheck MUST NOT short-circuit. It has no decisive outcome to short-circuit on, and its completeness is what makes §6.1.1 rule 2 achievable.
  4. The precheck decides whether a rule can be evaluated; it MUST NOT enlarge the set of calls a rule applies to. A rule that a well-formed pattern field definitively excludes from this call does not participate in the decision, and its faults elsewhere MUST NOT affect it. In order:

    a. Precheck the structure of callers and targets (§6.1.4.1). b. If a pattern field is malformed, the rule's scope is unknowable, so the rule MUST be unevaluable and resolve per §6.1.1's effect table. c. If both pattern fields are well-formed and either fails to match, the rule does not apply to this call. Evaluation continues with the next rule, and any fault in the rule's conditions MUST NOT be consulted, reported in handler_error, or allowed to change this call's decision. d. Only a rule whose patterns matched reaches the conditions precheck.

  5. A precheck fault gates the rule; it does not enter the composition table. §6.1.1's table says an outright "yes" wins an $or even when a sibling is unevaluable. That governs conditions the implementation actually evaluated. A fault the precheck found is different in kind: the rule is not well-formed enough to evaluate, so it is UNEVALUABLE as a whole and no sibling can rescue it.

    {"$or": [{"mispelled": true}, {"roles": ["dev"]}]} for a caller who has dev is the discriminating case: the composition table alone would make the $or SATISFIED, and gating makes the rule unevaluable. Gating is what the principle demands — otherwise a typo is silent for exactly as long as some sibling keeps matching. Gating is also required for consistency with rule 1: a precheck fault must resolve a context-less call, where no condition is ever evaluated and the table has nothing to operate on.

    The split is precheck versus execution, not structural versus everything. A registered handler that throws is execution-origin, so the table does apply: {"$or": [{throwing_key: true}, {"roles": ["dev"]}]} for a dev caller is SATISFIED, and an allow rule carrying it grants. Both directions are pinned by ../../conformance/fixtures/acl_handler_error.json.

    Without (c), one misspelled key in a narrowly scoped rule would decide calls that rule was never written about: callers: ["api.*"] with conditions: {mispelled: true} and effect: deny would deny a worker.* caller, which breaks first-match-wins. The fault is still real — validate_rules() (§6.1.2) reports every fault in every rule regardless of any call, and that is where a scoped rule's typo is meant to surface.

Determinism. Because the precheck is context-independent, handler-free and exhaustive, its findings are a pure function of the rule. Every conforming implementation MUST therefore produce the same set of precheck-origin handler_error entries for the same rule, in the same order (§6.1.1 rule 2's path ordering). Diagnostics that originate in handler execution — a registered handler that throws, an async handler unresolvable on the sync path — carry no such guarantee, because execution may short-circuit.

Condition paths. A finding names the position of the offending condition in the tree, not merely its key, because a key may appear at several positions:

Position Path
a key k at the root of conditions k
a key k inside the i-th element of $or (0-based) $or[i].k
a key k inside $not $not.k
the conditions object itself $
the rule's callers / targets (§6.1.4.1) callers / targets
an $or element that is not a condition object $or[i]

Paths nest, so a key inside $not inside the second $or branch is $or[1].$not.k. A fault that is not attached to a key — a malformed $or element, a non-mapping conditions, a malformed pattern field — is reported at the position of the malformed value itself and MUST NOT be skipped: skipping is how a whole $or branch disappears without anyone being told. Implementations MUST use this form; it is what handler_error orders by and what §6.1.2's validator reports.

6.1.4.1 Malformed callers / targets

callers and targets are lists of patterns, and both the element type and the arity are constrained (§6.2.1). A value that is not a list of strings, or a list whose shape is outside §6.2.1's closure, is a malformed rule, and the precheck MUST classify it as unevaluable — resolving per §6.1.1's effect table, so an allow rule does not grant and a deny rule takes effect. It MUST NOT raise out of check(), and it MUST NOT be treated as a pattern set.

Rationale: the failure is a fail-open. A bare string is iterable in several host languages, so callers: "admin.*" written where callers: ["admin.*"] was meant would iterate the string character by character; the * character is a valid pattern that matches everything, so an allow rule carrying that typo would grant access to every caller.

ACL.load rejects a non-list callers / targets, so a YAML file cannot reach the type fault; direct construction and runtime rule insertion can, which is the same route §6.1.1 case 5 exists for. An implementation whose type system makes the value unrepresentable (for example a Vec<String> field) satisfies this half by construction and needs no runtime check.

The shape half is different: no type system exempts an implementation from it, because a list type constrains the element type but not length or element content. §6.2.1 closes every entry point against a malformed shape, so what remains for this precheck is a value assigned onto a rule after it has already been accepted by an entry point — installed inside a live ACL (via load, direct construction, or add_rule) and mutated afterward through an accessor the caller already holds a reference to. That is the one route no entry point runs again to intercept. A rule mutated before it is ever offered to an entry point — including a rule handed to ACL's own constructor as part of a list of already-built rule objects — is still being offered to an entry point for the first time, and MUST be rejected there like any other malformed rule reaching that entry point (§6.1.6 rule 3); construction cannot exempt a rule from the check every other rule in the same list gets merely because the rule object predates the ACL it is being handed to.

Special patterns:

Pattern Description
@external Matches calls with no caller_id (external entry points)
@system Matches calls where identity type is system
* Wildcard, matches all module IDs

6.1.5 The rule key set is closed

callers, targets, effect, approval, description and conditions are the complete set of keys an ACL rule may carry (approval is defined in §6.1.6). Loading a rule with any other key MUST fail with ACLRuleError, naming the rule index and the offending key.

This is the same principle §6.1.2 applies to condition keys, in the other half of the rule, and it can be stricter: an unknown condition key cannot fail the load, because register_condition writes to a runtime registry that discovery may legitimately precede. A rule key has no such excuse — the set is fixed by this section and by schemas/acl-config.schema.json, which declares additionalProperties: false on a rule.

A dropped key widens an allow rule, silently

If an unrecognised key were discarded, the rule would apply unnarrowed. On a deny rule that is over-broad and therefore safe. On an allow rule it is a privilege escalation: an operator who writes a key intending to restrict a rule gets a rule with no restriction and no warning. This is the §6.1.1 defect class — a silent fail-open produced by a key nothing evaluates — on the pattern side rather than the condition side.

The effect value set is closed too, at every entry point. effect accepts "allow" and "deny" and nothing else — §6.1's field table says MUST and schemas/acl-config.schema.json declares the enum. A rule carrying any other value MUST be rejected with ACLRuleError naming the offending value, and the rule index wherever the entry point has one — a rule under construction has no position yet, and an implementation MUST NOT invent one; it names the value alone. It MUST be rejected at every entry point that accepts a rule — file loading, direct construction, and runtime insertion — on §6.1.6 rule 3's reasoning, which applies here unchanged. default_effect is closed on the same terms, at every entry point that accepts one; its rejection names the offending value, there being no rule index to name. §6.2.1 closes a pattern array's shape on the same terms.

An implementation MUST NOT resolve an unrecognised effect to a decision, nor pass it through as one. Closing the entry points is the mechanism: once every entry point rejects, no evaluation-time branch for an unrecognised value is reachable through any API this specification defines, and the decision read becomes total over the closed set rather than a fallback with a default arm. A value that arrives by some route outside those entry points — assigning the field on an already-constructed rule, which no constructor can intercept — is outside what this section can require: an implementation MAY guard it and MUST NOT silently normalise it.

Rationale: reading an unrecognised value as deny is a fallback that looks safe and is not — under default_effect: allow a rule the operator wrote to permit becomes a rule that denies everything it matches, with no error and no warning, and the reading is only ever accidentally right on a deny rule. Passing the value through is worse: effect: "Allow" would surface as a verdict string no consumer parses, in AccessDecision.access and in the audit entry's decision, and the same literal comparison that decides whether the rule carries an approval requirement would silently drop the approval: required attached to it.

Reserved names. id, actions and priority are reserved for future specification versions and are evaluated by no implementation. They are rejected at load like any other unknown key, and an implementation SHOULD name them as reserved in the error rather than merely unknown, because an operator who wrote actions: ["describe"] intended a restriction and deserves to be told the key does not exist yet rather than that they mistyped something. The schema does not declare them among a rule's properties, so additionalProperties: false catches them.

6.1.6 Authorization and approval are two results, not one

An ACL rule answers two independent questions, and folding them into one enumeration makes a meaningless state representable while forcing a real one to be spelled badly.

  • Authorization — may this caller reach this target at all? allow / deny.
  • Approval requirement — must this particular call be put to a human before it runs? true / false.

"Denied and needs approval" is not a state that means anything, and "allowed but ask first" is not a third kind of denial. A rule therefore carries effect plus an orthogonal optional field:

rules:
  - callers: ["*"]
    targets: ["cli.git_push"]
    effect: allow
    approval: required          # required | not_required (default)
    conditions:
      arguments: { has_key: ["force"] }
  1. approval is optional; its absence means not_required. not_required is the absence of a requirement, never the suppression of one. Writing it explicitly on a rule asserts that this rule asks for no human; it does not cancel a requirement another rule raised, including a pending one under §6.1.1 rule 5. There is no way to spell "and cancel anything else" on a rule, deliberately — §6.9 rule 4 refuses that power to a module-scoped policy, and a rule further down the same file is not a better place to grant it.
  2. approval: required on a deny rule MUST be rejected at load with ACLRuleError. The combination has no meaning, and silently ignoring one half of a governance rule is the failure mode §6.1.5 exists to prevent.
  3. The combination MUST be rejected at every entry point that accepts a rule — file loading, direct construction, and runtime insertion. An add_rule that returns nothing by its own contract is not exempt: an implementation MUST either provide a fallible variant beside it or fail loudly, in whatever way that language already signals an unconstructable value. A deny rule never reaches the approval gate, so a requirement attached to one can only ever mislead the operator who wrote it, and accepting it through one entry point while rejecting it at the others is worse than either.
  4. The field depends on the closed rule key set (§6.1.5). An implementation that dropped unknown keys would read a deny-with-approval rule as a bare rule and act on half of what the operator wrote.

Why this cannot be expressed with the other mechanisms. Without this field, the ACL can refuse on arguments and ApprovalHandler can wave a call through on arguments, but neither can ask on arguments, and asking is the entire purpose of the approval gate — a refusal is not a question. Every other decision point that can read a call's arguments is unable to escalate it to a human, and the one point that decides whether to ask a human (§7.9's policy resolution) is forbidden by rule 2 of §7.9.6 from consulting them.

6.1.7 The arguments condition

One built-in condition key, part of the condition language §6.1 defines rather than beside it:

Predicate Passes when
has_key any of the named keys is present in the call's arguments
has_all_keys every named key is present
has_none_of none of the named keys is present

No predicate reads a value, and that is a design constraint rather than a first cut. Three reasons, in order of weight:

  1. Argument values may contain secrets. Access rules operate on key presence so argument values stay out of governance decisions and handler_error diagnostics. Observability capture applies the configured redaction rules in §10.6.1 when the module has no input schema.
  2. The arguments are unvalidated. The ACL check is Step 4 and input schema validation is Step 7, so a value may be absent, of the wrong type, or malformed. Key presence is the one question that is well-defined on unvalidated input.
  3. Key presence answers the driving requirement. "Did this call carry --force?" is a presence question.

Value-level predicates (equals, matches, ordering comparisons) are deliberately not specified. If they are added later they MUST carry a precondition that the module declares an input_schema, or resolve as unevaluable under §6.1.1.

It is built-in and requires no registration. register_condition writes runtime code into a process-wide registry; a deployment-registered argument handler would be exactly the unauditable host code §7.9.6 rule 2 exists to keep out of a governance verdict. A fixed vocabulary keeps the decision reproducible from the ACL document. This says the condition needs no registration, not that register_condition is forbidden from replacing it: that call can already replace roles, which is equally consequential, and special-casing one built-in would be arbitrary. A deployment that replaces a built-in condition owns the consequence. Being built-in also means §6.1.4's precheck covers it: argument: written for arguments: is an unregistered condition key, so the rule is unevaluable rather than silently inert.

6.1.8 The governance projection

The arguments condition reads a governance projection of the call's arguments, not the arguments themselves and not redacted_inputs.

  1. Implementations MUST compute the projection during module lookup (Step 3) and make it available to the ACL check (Step 4). The ordering is normative.
  2. The projection MUST carry the argument key set, and MAY carry each key's JSON type. It MUST NOT carry any argument value. A projection that structurally cannot hold a value cannot leak one, whatever a future predicate does with it.
  3. The projection MUST be computed by the framework and MUST NOT be accepted from caller-supplied input. Where an implementation carries it on a context object that is also deserialized from the wire, the field MUST be transient — excluded from serialization and ignored on deserialization. A caller that could supply its own projection could satisfy has_none_of for a call whose arguments say otherwise, which turns the condition into a caller-controlled switch.
  4. How the projection reaches the condition is idiomatic and unconstrained: carrying it on the execution context and passing it as an argument to the check are both conforming, as long as rules 1–3 hold. What is fixed is that the condition sees it and that a caller cannot forge it.
  5. Implementations MUST NOT substitute redacted_inputs. It carries the observability values captured under §10.6.1. Rule 2 defines the input to a governance decision.

Well-formedness and availability. Four cases, all resolving to UNEVALUABLE under §6.1.1's principle rather than to a boolean. The direction matters: every one of them is a shape where "false" would be safe on a deny rule and fail open on an allow rule, which is the defect class §6.1.1 exists to close.

  1. No projection available. check() is public API and a caller that is not the Executor may invoke it without one. The condition is UNEVALUABLE. It MUST NOT be evaluated against an empty stand-in: has_none_of over an empty key set is satisfied, so an allow rule would grant for a call whose arguments were never seen.
  2. arguments: {} — an empty predicate object. UNEVALUABLE, not vacuously satisfied, for the same reason §6.1's table gives for an empty $not.
  3. An unrecognised predicate name inside arguments (has_keys for has_all_keys). UNEVALUABLE. The predicate vocabulary is closed exactly as the rule key set is (§6.1.5), and for the same reason: a name nothing evaluates would otherwise be dropped and leave the rule wider than written.
  4. A malformed predicate value — not a list of strings. UNEVALUABLE, per §6.1.1 case 4.

Empty predicate arrays are well-formed and carry ordinary set semantics: has_key: [] is unsatisfied, has_all_keys: [] and has_none_of: [] are satisfied. They are not misconfigurations, merely vacuous.

§6.1.4's precheck covers the predicate structure, not only the arguments key's registry status. Cases 2–4 are decidable without a context and without running a handler, so they are precheck faults and validate_rules() MUST report them — which is what makes a malformed predicate visible at deploy time rather than at the first call that trips it.

The condition path of an arguments fault descends to the offending predicate. §6.1.4 descends into structure — a fault beneath $or is reported at $or[1].k, not at $or — and the reason carries over unchanged: arguments: { has_key: ["a"], has_keys: ["b"] } has one bad predicate among good ones, and a finding that says only arguments does not say which.

  1. A fault attributable to one predicate — an unrecognised name (case 3) or a malformed value (case 4) — MUST be reported at arguments.<predicate>, using the name as written: arguments.has_keys for the misspelling, so the finding names the string the author typed and can be searched for.
  2. A fault with no predicate to name — a non-mapping arguments value, or the empty object of case 2 — MUST be reported at arguments. These two are terminal: a value that is not a mapping of predicates has no predicates to walk.
  3. Every faulty predicate in one arguments block MUST be reported, one finding each, and the walk MUST NOT stop at the first. §6.1.4 requires the precheck to walk the whole rule structure so that a fault is always found and always reported, and a block is part of that structure. Reporting only the first would also make the choice of which one to report observable, and "the first" is not a pure function of the rule: { has_key: "force", zzz: [...] } has both a malformed value and an unrecognised name, and an implementation that checks names before values would report a different path from one that walks predicate by predicate. Reporting both removes the question rather than answering it.
  4. Both forms compose under $or / $not exactly as any other path does: $or[1].arguments.has_keys.

This is a path rule, not a message rule. Findings order by path (§6.1.4), which orders a block's own findings by predicate name.

_approval_token is excluded from the projection. It is framework-owned protocol machinery, not caller input — §7.9.6 rule 5 strips it before policy resolution for the same reason. Including it would make a Phase B resume present a different argument shape to governance than the original call, so has_none_of would decide differently on the two halves of one logical call.

6.2 Rule Matching

Implementations MUST perform pattern matching according to the following algorithm:

Algorithm: match_pattern(pattern, module_id)

Input:
  pattern   — ACL pattern (e.g., "api.*", "*.validator.*", "executor.email.send_email")
  module_id — Module Canonical ID to match

Output:
  matched — boolean

Steps:
  1. If pattern == "*" → Return true
  2. If pattern doesn't contain "*":
     → Return pattern == module_id (exact match)
  3. Split pattern by "*" into segments
  4. Use greedy matching algorithm:
     a. pos ← 0
     b. For each segment (non-empty):
        - Find segment in module_id[pos:]
        - If not found → Return false
        - pos ← Found position + len(segment)
     c. If pattern doesn't end with "*" → module_id must end with last segment
  5. Return true

Complexity: O(m × n), where m is pattern length, n is module_id length

A08 has exactly one metacharacter. * is a wildcard; every other character is a literal, ?, [, ], {, } and \ included. A08 is deliberately not A25 (§9.2.3), which is the matcher for every other pattern-valued value in this specification and which also honours ?. The two surfaces do not overlap: A08 matches module IDs in ACL rules and in match_modules (§5.16); A25 matches filenames, field names, event types and path_filter. Keeping A08 narrow is a security decision, not an oversight — see §6.2.2 for the one observable consequence and the diagnostic that closes it.

rule_matching:
  # Wildcard support
  wildcards:
    - "*"           # Match any
    - "api.*"       # Match all under api
    - "*.validator.*"  # Match validator in any layer

  # Evaluation order: first-match-wins
  order: "Rules are evaluated in definition order; the first matching rule determines the decision"

6.2.1 Compound Operators in Pattern Arrays

The callers and targets pattern arrays MAY use the compound operators $or and $not as the first element to alter the default OR-of-patterns semantics.

Form Operands Semantics
[p1, p2, ...] at least 1 The default. MUST match the module ID if any of p1, p2, … matches.
["$or", p1, p2, ...] at least 1 MUST match the module ID if any of p1, p2, … matches. Observably equivalent to a flat list (which is also OR-ed) but documents intent explicitly.
["$not", p] exactly 1 MUST match the module ID if p does not match.

A pattern array is FLAT. The operators do not nest and there is no precedence. An operand is always a plain pattern string, never a nested array and never another operator. There is exactly one operator position — index 0 — and everything after it is an operand. $or and $not therefore have two different grammars in this specification, and only one of them nests:

in conditions (§6.1.1) in a pattern array (this section)
operand a condition object a pattern string
nesting arbitrary — $or[1].$not.k is a defined path (§6.1.4) none
how many operators per expression any number, at any depth exactly one, at index 0

A reserved token at any index other than 0 is therefore not a nested operator and not a usable pattern: ["$or", "$not", "a"] is not "or-of-not", and ["a", "$not", "b"] is not "a, but not b". Both are rejected — see the closure below. Rejecting the token outside index 0 is what makes the reserved-token guarantee hold by construction: no pattern array can carry "$or" or "$not" as a literal pattern.

Not every intent is expressible in one pattern array, and that is deliberate. NOT (a OR b) has no single-array form: $not takes exactly one operand and the array's own combinator is OR, so there is no way to write "neither a nor b" as one field. Use a glob when the excluded patterns share a prefix, and otherwise first-match-wins with two rules, which is the idiom §6.3 already provides:

rules:
  # "everything except executor.secrets.a and executor.secrets.b"
  - callers: ["*"]
    targets: ["$or", "executor.secrets.a", "executor.secrets.b"]
    effect: deny
    description: "Excluded targets, refused first"
  - callers: ["*"]
    targets: ["*"]
    effect: allow
    description: "Everything else"
default_effect: deny

audit:
  enabled: true
  include_denied: true
  log_level: info

The two-rule form is not a drop-in replacement inside an existing rule list

The two forms differ in what happens to the excluded calls. ["$not", p] makes the rule not match p, so evaluation continues and a later rule may still decide it. A leading deny on p ends the scan for p. They agree only when nothing after the rule could have matched p and default_effect would have refused it anyway — which is true of the complete policy above and is not true in general. Inserting a leading deny into an existing rule list changes the decision for every call that a later rule was written to allow. Rewriting a rule into this form is a change to the policy's order, not a local substitution.

Worked examples. Every legal form, and every form that looks legal and is not:

# ---- legal ----
targets: ["executor.*"]                       # one pattern
targets: ["api.*", "worker.*"]                # OR, implicitly
targets: ["$or", "api.*", "worker.*"]         # OR, explicitly — same meaning, states intent
targets: ["$or", "api.*"]                     # one operand under $or is legal, if pointless
targets: ["$not", "executor.secrets.*"]       # "anything that is not executor.secrets.*"

# ---- rejected: arity (§6.2.1 closure) ----
targets: []                                   # no operands — matches nothing, so the rule is no rule
targets: ["$or"]                              # OR over nothing
targets: ["$not"]                             # negation of nothing
targets: [""]                                 # the empty pattern matches no legal module ID
targets: ["$not", "a", "b"]                   # $not takes EXACTLY one operand — write two rules

# ---- rejected: a reserved token outside index 0 (there is no nesting) ----
targets: ["$or", "$not", "a"]                 # NOT "or-of-not"
targets: ["api.*", "$not", "cli.*"]           # NOT "api.* but not cli.*". No such form exists.

# ---- legal, but reported by validate_rules() as matching nothing (§6.2.1 tier 2) ----
targets: ["$not", "*"]                        # "not everything" is well-formed and matches nothing

Arity is part of the form, and the set of arities is closed. A pattern array MUST carry at least one operand and every element MUST be a non-empty string: callers and targets MUST NOT be empty, no element MUST be the empty string, $or at index 0 MUST be followed by at least one pattern, $not at index 0 MUST be followed by exactly one, and $or / $not MUST NOT appear at any index other than 0. A rule violating any of these MUST be rejected with ACLRuleError, naming the field (callers / targets) and the rule index wherever the entry point has one — a rule under construction has no position yet, and an implementation MUST NOT invent one (§6.1.5). It MUST be rejected at every entry point that accepts a rule — file loading, direct construction, and runtime insertion — on §6.1.6 rule 3's reasoning, which applies here unchanged. Closing the entry points is the mechanism, exactly as it is for the effect value set. schemas/acl-config.schema.json declares the same closure ($defs/PatternArray).

A pattern array with no operands is not a narrow rule; it is no rule

Read as a scope decision, [], ["$or"] and ["$not"] match nothing, so the rule is inert and the decision tracks default_effect exactly. On an allow rule that is merely useless. On a deny rule under default_effect: allow it is a fail-open: the call the operator wrote the rule to block is permitted, by a rule that loaded without error. A YAML file reaches this shape — ACL.load rejects an omitted callers / targets as a missing field, and it is this closure that rejects an empty one.

No single non-match can be called fail-closed: which direction "does not match" points is decided by the rule's effect (§6.1.1).

$not takes exactly one operand. The only other available reading — consult p1 and ignore the rest — makes the form silently wider than written: targets: ["$not", "secrets.a", "secrets.b"] on an allow rule would read as "anything but secrets.a", and secrets.b — the second target the operator excluded — would be granted. A future version MAY define the multi-operand form as NOT (p1 OR p2 …), which is the reading an operator writing it already has; rejecting it now is what keeps that option open, because nothing can come to depend on another reading in the meantime.

A well-formed array that can still match nothing is reported, not rejected. Closing the arities above does not exhaust the shapes that make a rule inert, and an implementation MUST NOT read the closure as though it did. A pattern array that is well-formed under every rule above and that matches no legal module ID for any input is a rule that protects nothing, and validate_rules() (§6.1.2) MUST report it — with the same finding shape as a structural fault: path callers / targets, a null key, and both resolvability flags false. It MUST NOT be rejected and MUST NOT change any access decision.

The criterion is normative and the list is a minimum, not a closed set. Every implementation MUST detect at least:

  • ["$not", p] where p matches every module ID — *, **, or any pattern consisting only of wildcards. !true is false for every input, so the rule fires for nothing.
  • ["@external"] as a targets pattern. @external is the caller-side sentinel §6.5 substitutes for a null caller_id; no module ID is @external, so as a target pattern it matches nothing. It remains entirely legal in callers, which is what it is for.

The array is judged as a whole, never element by element. The criterion is that the array matches no legal module ID, so a flat or $or array is reported only when every operand is unmatchable: targets: ["@external"] is reported and targets: ["api.*", "@external"] is not, because api.* still matches. The MUST-detect list above names whole-array shapes and would otherwise be readable as "report any occurrence of the token", which would report a rule that works.

An implementation MAY report further shapes it can prove match nothing. Divergence in this finding set between implementations is acceptable and expected, and is the reason this is a validator finding rather than a rejection: §6.1.4's determinism guarantee binds precheck-origin diagnostics because they feed handler_error and the decision, and tier-2 findings feed neither. A rejection whose predicate differed between implementations would mean the same ACL file loads in one language and fails in another, which is the cross-language split §6.1.5 exists to prevent. §6.1.3's sentence governs: this is diagnostics, not enforcement.

The backstop, for the route no entry point covers. A value that arrives outside the entry points — assigning callers or targets on a rule that has already been accepted through an entry point: installed inside a live ACL and mutated afterward through an accessor the caller already holds a reference to — is outside what a rejection reaches, because no entry point runs again once that point is past. This is narrower than "any rule object currently holding a bad value": a rule mutated before it is first offered to an entry point — ACL's own constructor included, since it accepts a list of rule objects exactly as add_rule accepts one — MUST still be rejected there like any other malformed rule reaching that entry point. Only a rule already past every entry point is left to this backstop. Unlike an unrecognised effect, which once the entry points are closed is never read again, a mutated pattern array is read: the matcher consults it on the next check(). A pattern array that reaches evaluation violating any clause of the closure above is therefore a precheck fault under §6.1.4.1, on the same terms as a malformed type: the rule's scope is unreadable, the rule is UNEVALUABLE, and §6.1.1's effect table decides — a deny rule takes effect and denies, an allow rule does not match and MUST NOT grant. validate_rules() (§6.1.2) MUST report it as §6.1.3 rule 3's keyless structural fault: path callers / targets, a null key, and both resolvability flags false.

An arity fault is a malformed pattern field like any other, with no partially-readable tier. In particular §6.1.1 rule 5's "unknowable scope counts as scope" applies unchanged: a rule carrying approval: required whose pattern field is malformed MUST raise the pending requirement. targets: [] is legible as an empty scope in a way targets: 3 is not, and an implementation MUST NOT act on that difference — deciding per fault kind whether a field is "readable enough" is a per-implementation judgement call, and the direction it would resolve is toward asking a human less often.

Two points of order.

  1. add_rule re-validates the rule it is handed. A rule offered to runtime insertion MUST be validated at that moment, whatever its history — including a rule that was well-formed when constructed and has since had callers or targets assigned. An implementation MUST NOT rely on the rule type's own construction-time check to cover this entry point. §6.1.5 leaves mutation-then-use of effect to a MAY, which is sound there because a closed effect is never read again; a pattern array is read, by the matcher, on the next check().
  2. Validation order is effect → approval → callers / targets, and rule index dominates all three. A rule that is bad on more than one axis MUST be refused for the first axis it fails, and a rule set with more than one bad rule MUST be refused for the lowest-indexed bad rule — an implementation MUST NOT sweep one axis across every rule before looking at the next axis. "Axis" here means every per-rule check the entry point performs, not only the three named above. A loader has others that the other entry points cannot have — the rule key set (§6.1.5), a missing callers / targets, the value types — and each is an axis for this purpose: a file carrying effect: "Allow" on rule 0 and an unknown key on rule 1 is refused for rule 0. Both halves are required for the same reason: so one file produces one error, whichever entry point it arrives through and whichever implementation reads it.

    The pattern fields are one axis, covering §6.1.4.1's type fault and this section's shape closure together, and callers precedes targets throughout. Within the axis the type fault comes first — a value must be a list of strings before its arity means anything — wherever both can surface, which is a loader (it rejects both) and the precheck (it reports both). An entry point that accepts an already-built rule object rejects the shape fault and leaves the type fault to §6.1.4.1's precheck; that asymmetry is deliberate, and is why this sentence is scoped rather than absolute.

    default_effect is judged before any rule. It is not a rule and has no index, so the ordering above does not reach it — yet a file wrong in both default_effect and a rule is precisely the "one file, one error" case this paragraph exists for, and would otherwise name the rule at one entry point and default_effect at another. It MUST be validated first, at every entry point that accepts one — first meaning ahead of the file-level checks on the rules collection itself, not merely ahead of the individual rules. A document that is both missing rules and carrying an unrecognised default_effect is refused for the default_effect. That boundary is stated because it is the one place "first" is genuinely ambiguous; a doubly malformed document is refused either way, and only the message differs, which is exactly what this paragraph makes deterministic.

Reporting order is a separate question. validate_rules() (§6.1.2 rule 3) orders findings by rule index, then lexicographically by path, so a pattern fault interleaves with condition faults — $or[0].k before callers before roles before targets — rather than being grouped ahead of them. Point 2 above governs which single refusal a rejecting entry point raises; it does not regroup what a reporting validator returns.

At most one finding per field, and the closure wins. A field that fails the closure above is reported for that failure and MUST NOT also be reported as never-matching: the never-matching criterion presumes a well-formed array, so evaluating it against a malformed one is meaningless. Without this, implementations agree on every decision and disagree on finding counts.

6.2.2 ? in an ACL Pattern Is Dead, and MUST Be Reported

A08 (§6.2) has exactly one metacharacter, *. ? is a literal, and §2.7's grammar forbids ? in a module ID, so an ACL pattern containing ? matches nothing and can never match anything. In a deny rule that is a guard which protects nothing; in an allow rule it is a grant that never fires and sends its author looking elsewhere. Either way the author meant a wildcard — ? is a wildcard in every other pattern surface this specification defines (A25, §9.2.3) — and got a rule that is silently inert.

  1. Loading a rule set MUST NOT fail on such a pattern. It MUST emit a warning naming the rule index, the field (callers / targets) and the pattern as written.
  2. validate_rules() (§6.1.2 rule 3) MUST report it, at the path of the offending field, ordered with every other finding by rule index then path.
  3. The pattern's meaning is unchanged: ? stays a literal and the rule keeps matching nothing. This clause adds a diagnostic and changes no decision — deliberately, because the alternative (promoting ? to a wildcard in A08) would widen allow rules that are otherwise inert, and a change to an authorization matcher does not widen access without an operator's consent.

This is the same shape as §6.1.2's unregistered-condition-key rule: a policy statement that cannot do what its author intended is a deploy-time finding, never a silent one, and never a load-time failure that would break bootstrap ordering.

6.3 Rule Evaluation Algorithm

Implementations MUST evaluate ACL rules using a first-match-wins strategy. Rules are evaluated in definition order (not sorted by priority). The first rule whose patterns match the caller_id and target_id determines the access decision.

Naming Convention: - Wire Format (JSON): All data transfer structures (e.g., Audit Logs, Context sync) MUST use snake_case (e.g., caller_id, target_id). - SDK Surface: Implementations SHOULD use idiomatic naming (e.g., callerId in TypeScript, caller_id in Python).

Algorithm: evaluate_acl(caller_id, target_id, rules, default_effect, context)

Input:
  caller_id      — Caller module ID (null means external call, treated as "@external")
  target_id      — Called module ID
  rules          — Rule list (evaluated in definition order)
  default_effect — Default policy ("allow" | "deny")
  context        — Execution context (optional, used for condition evaluation)

Output:
  decision — { effect: "allow" | "deny", matched_rule: Rule | null }

Steps:
  1. effective_caller_id ← caller_id ?? "@external"
  2. For each rule ∈ rules (in definition order):
     a. caller_matched ← false
        For each pattern ∈ rule.callers:
          If pattern is "@external" and caller_id is null → caller_matched ← true; break
          If pattern is "@system" and context.identity.type == "system" → caller_matched ← true; break
          If match_pattern(pattern, effective_caller_id) → caller_matched ← true; break
     b. target_matched ← false
        For each pattern ∈ rule.targets:
          If match_pattern(pattern, target_id) → target_matched ← true; break
     c. If caller_matched and target_matched:
        If rule.conditions is not empty:
          verdict ← evaluate_conditions(rule.conditions, context)
              // verdict ∈ { SATISFIED, UNSATISFIED, UNEVALUABLE }   (§6.1.1)
          If verdict is UNSATISFIED → continue
          If verdict is UNEVALUABLE:
            record handler_error on the audit entry and warn (§6.1.1)
            If rule.effect == "deny" → Return { effect: "deny", matched_rule: rule }
            Else                     → continue          // an allow rule MUST NOT grant
        → Return { effect: rule.effect, matched_rule: rule }
  3. Return { effect: default_effect, matched_rule: null }

Complexity: O(R × P), where R is number of rules, P is average patterns per rule

evaluate_conditions returns three outcomes, not two. UNSATISFIED means a handler answered "no"; UNEVALUABLE means no answer was obtainable — see §6.1.1 for the principle that decides it and the situations it covers. An implementation whose evaluator returns a plain boolean MUST carry the distinction some other way (a sentinel, an out-parameter, a typed result); collapsing the two is the defect §6.1.1 exists to prevent.

6.3.1 Audit Entry

Every check() MUST emit exactly one audit entry through the configured audit logger, whatever the decision. The wire format is snake_case per §6.3; SDK surfaces MAY use idiomatic field names (callerId in TypeScript).

Field Type Description
timestamp string ISO 8601 timestamp of the decision
caller_id string Effective caller (@external when the call had none)
target_id string Module ID being accessed
decision "allow" \| "deny" The returned decision
reason "rule_match" \| "default_effect" \| "no_rules" Which branch of §6.3 produced the decision
matched_rule string \| null The matched rule's description, snapshotted
matched_rule_index integer \| null Index of the matched rule in definition order
identity_type string \| null Identity type from the context, when present
roles list[string] Identity roles from the context; empty when absent
actor_id string Current actor ID for a scope-enabled identity (§6.11)
subject_id string Root subject ID for a scope-enabled identity (§6.11)
delegation_depth integer Active delegation depth for a scope-enabled identity (§6.11)
call_depth integer \| null Length of context.call_chain, when present
trace_id string \| null Trace ID from the context, when present
handler_error string \| null Non-null if and only if a condition was unevaluable (§6.1.1). MUST name each unevaluable condition's path (§6.1.4) and the reason, ordered and separated as §6.1.1 rule 2 requires.
approval_required boolean Whether this call must be put to a human (§6.1.6): the deciding rule's own requirement, union any pending requirement an unevaluable allow rule raised (§6.1.1 rule 5). Always false when decision is deny. true with matched_rule_index: null when default_effect: allow carries a pending requirement (§6.9 row 2); otherwise false when no rule matched. Carried beside decision rather than as a third decision value, because decision is a string downstream consumers parse (§6.9 row 7).

handler_error is what makes §6.1.1's two outcomes distinguishable after the fact: a rule that did not match because a handler said "no" leaves it null; a rule that did not match — or that denied — because no answer was obtainable leaves it set. An implementation MUST NOT set it for an ordinary UNSATISFIED condition.

Two scoping notes, because the "if and only if" above binds to conditions, not to the decision:

  • handler_error is recorded per check(), while matched_rule / matched_rule_index describe the rule that produced the decision. When one rule is unevaluable and a later rule decides, a single audit entry legitimately carries a handler_error from one rule and a matched_rule_index from another. Read them as "what went wrong during this check" and "what decided this check" — they are not required to refer to the same rule.
  • A rule can end UNSATISFIED while a condition inside it was unevaluable, which is why the "if and only if" cannot be read as binding to the outcome. §6.1.4 guarantees precheck-origin entries are present regardless of short-circuiting; execution-origin entries depend on what was reached.

6.3.2 Audit Delivery (audit: in the ACL file)

§6.3.1 specifies the record. This section specifies delivery: which sink receives the record, what the ACL file's audit: block configures, and what happens when delivery fails (D-66).

The ACL file's audit: block is the one configuration home. acl.audit.* is deprecated under §9.2.4 and is removed at v2.0; its notice names this block as the migration target. Auditing is configured beside the rules it audits, and the ACL loader is the only code that parses the document the block lives in.

Requirements:

  1. There is exactly one effective sink, never two.
Condition Effective sink
ACL(audit_logger=…) supplied that callback
no callback, and the ACL file declares audit: with enabled: true the default sink (requirement 2)
otherwise none — no audit records are produced

A supplied callback receives every entry, allow and deny alike, and MUST NOT be narrowed, levelled or silenced by the audit: block: enabled, include_denied and log_level configure the default sink and nothing else. An API argument beats configuration, and the alternative is worse than inconsistent — include_denied: false in a file would silently truncate a compliance sink a developer installed deliberately.

When a callback is supplied and the ACL file declares an audit: block, implementations MUST emit one diagnostic per ACL construction naming every field that does not apply, not only the most visible one.

  1. Declaration activates the default sink, not the default value. enabled defaults to true, so a merged-view reading would switch on a log record per ACL check for every ACL file, on projects that asked for none. The default sink is active only when the document declares an audit: block, exactly as §9.2.4's notice is driven by the declared document and never by the merged view. An ACL file with no audit: block MUST produce no audit output unless a callback is supplied.

The default sink emits one record per decision, through the implementation's own logging facility, at log_level, under the stable event name apcore.acl.audit (§9.16.2's table). The record MUST carry all thirteen §6.3.1 fields as structured data under their snake_case wire names, not as an interpolated message string. Without that, each language's logging facility produces a different "structured record" from one specification, and nothing downstream can consume all of them. How the host renders the structured record is the host's business; which fields exist under which names is not.

  1. Delivery MUST NOT change the access decision. For every recoverable delivery failure, an implementation MUST return the AccessDecision it computed. A fatal process termination is outside this guarantee: a Rust callback is Fn(&AuditEntry) with no error channel, so only an unwinding panic can be contained and a build with panic = "abort" cannot be.

Auditing is a side channel and MUST NOT hold a veto over access, as is already required of the governance events beside it (§9.16.2).

  1. The callback MUST be synchronous. An async callback returns a coroutine or an unawaited Promise, so its failure surfaces after the decision has already been returned — outside the containment requirement 3 promises, and in TypeScript as an unhandled rejection. Implementations MUST treat a callback that returns an awaitable as an invalid delivery, emit one diagnostic, and continue. A callback that needs to do asynchronous work SHOULD enqueue the entry and return.

  2. Diagnostics for a failing sink are suppressed after the first, scoped to one ACL instance and one effective sink configuration. This keeps diagnostic volume independent of the check() rate while a sink is down. Replacing the sink or reloading a configuration that changes it starts a new scope, so a new failure is never hidden behind an old one.

  3. include_denied filters the default sink's deliveries. true (the default) delivers every entry; false withholds entries whose decision is deny. Because that withholds the security-relevant half, an ACL file setting it to false MUST emit a diagnostic once for each configuration load that sets it to false, for the same reason as §5.16 requirement 7. The setting remains valid.

  4. Reload refreshes the block and preserves the callback. reload() re-reads the ACL file and MUST apply the new audit: configuration to the default sink. It MUST NOT replace or remove a programmatic callback, which was never read from the file.

  5. The block is validated, and nothing else about the file becomes stricter. The audit: subtree MUST be validated against $defs/AuditConfig in schemas/acl-config.schema.json — types and unknown keys inside the block — and a violation is a load-time CONFIG_INVALID. Every other unrecognised root key in an ACL file MUST keep being ignored. This section wires one block; it is not unknown-key closure for ACL files, for the same reason §9.2.4.1's notice is scoped to audit alone.

6.4 Pattern Specificity Scoring

When further distinguishing rules within same priority is needed, implementations SHOULD calculate pattern specificity score:

Algorithm: calculate_specificity(pattern)

Input:
  pattern — ACL pattern string

Output:
  score — Specificity score (integer, higher = more specific)

Steps:
  1. If pattern == "*" → Return 0
  2. segments ← Split pattern by "."
  3. score ← 0
  4. For each segment:
     a. If segment == "*" → score += 0
     b. If segment contains "*" (partial wildcard) → score += 1
     c. If segment doesn't contain "*" (exact match) → score += 2
  5. Return score

6.5 Edge Case Handling

Scenario Behavior Level
caller_id is null Treat as @external MUST
rules is empty Use default_effect MUST
callers or targets shape is outside §6.2.1 — empty, an empty element, $or with no operands, $not with none or more than one, or a reserved token away from index 0 Rejected with ACLRuleError at every entry point (§6.2.1) — ACL's own constructor included, on whatever rule objects it is handed, regardless of when or how they were built; unevaluable → §6.1.4.1 only if assigned onto a rule already installed inside a live ACL and mutated after the fact MUST
Conditions present but no context provided Rule does not match; SHOULD warn (see below) MUST
callers or targets is not a list of strings Unevaluable → §6.1.4.1 — MUST NOT be read as a pattern set MUST
Condition key has no registered handler Unevaluable → §6.1.1 MUST
Condition handler raises / throws / panics Unevaluable → §6.1.1 MUST
Async condition handler unresolvable on sync check() Unevaluable → §6.1.1 MUST
Module calls itself Perform ACL check normally MUST

A conditional deny rule does not fire for a call that carries no context

"Conditions present but no context provided → rule does not match" is not an §6.1.1 unevaluable condition, and deliberately so: calling with no context is a legitimate, expected shape for external entry points, not a misconfiguration. Treating it as an evaluation failure would flip the decision for every @external call that meets a conditional deny rule.

This row applies only to a rule that passes §6.1.4's precheck. The precheck is context-independent and runs first, so a rule that is malformed — a misspelled key, a $or that is not a list, a conditions that is not a mapping — is unevaluable and takes §6.1.1's path even when the call carried no context. The distinction is between a question this caller did not supply the input for (§6.5, non-match) and a question nobody can answer (§6.1.1, resolve toward refusing access).

The consequence still has to be designed around. A rule such as effect: deny + conditions: {identity_types: [contractor]} blocks nothing at all when the caller supplies no identity — it is not a backstop. Express a backstop as an unconditional deny rule, or as default_effect: deny, and use conditional rules to carve exceptions out of it. Implementations SHOULD warn the first time a conditional rule is skipped for want of a context, naming the rule index and its effect.

6.6 System Module Permissions

The system.* namespace is a framework-reserved prefix (see §2.5). All built-in system modules (health, manifest, usage, control) are registered under this prefix. This section defines the permission semantics and defense-in-depth model for system modules.

6.6.1 Registration Restriction

System modules MUST only be registered via register_internal() (or equivalent privileged API). The standard register() method MUST reject any module_id starting with system. due to the reserved word system in §2.5.

This guarantees that user-defined modules cannot impersonate system modules.

6.6.2 Module Classification by Prefix

Adapters (MCP servers, HTTP gateways, Explorer UIs) SHOULD use module_id prefix to classify modules:

Prefix Classification Nature
system.health.* Observability Read-only, no side effects
system.usage.* Observability Read-only, no side effects
system.manifest.* Introspection Read-only, no side effects
system.control.* Administration Write operations — may reload, disable, or reconfigure modules

Adapters SHOULD NOT invent their own classification mechanisms (such as reserved tags or environment variables) — the module_id prefix is the canonical and unforgeable identifier.

6.6.3 Defense-in-Depth Model

System module access uses three independent layers. Configuration activates the modules, an attached ACL defines authorization, and the approval gate evaluates each call's effective requirements (§6.6.3.1).

Layer 1: Activation (Config) — two stages, not one
  sys_modules.enabled = false (default)
    → 0 modules registered. Nothing to call, nothing to list.
  sys_modules.enabled = true, sys_modules.events.enabled = false (default)
    → 7 read modules: system.health.*, system.usage.*, system.manifest.*
    → NO system.control.* — the write modules require the EventEmitter that
      carries their audit events (§6.7 cross-cutting requirement 3), so they
      are registered inside the events branch and not otherwise.
  both = true
    → 10 modules: the 7 above plus the 3 system.control.* write modules.

Layer 2: Authorization (ACL)
  When system modules ARE registered, ACL rules control who can call them.
  → Recommended default: deny external callers access to system.*
  → Example:
      rules:
        - callers: ["@external"]
          targets: ["system.*"]
          effect: deny
          description: "Block external access to system modules"

Layer 3: Approval (requires_approval annotation)
  Destructive system operations (e.g., system.control.reload_module)
  SHOULD set requires_approval = true for human-in-the-loop enforcement.

The 0 / 7 / 10 distinction matters to anything that reasons about exposure: a registry holding seven read-only modules and no ACL is an information-disclosure question, not a control-plane one. Treating "system modules are registered" as one state produces a warning that fires on a configuration with no write surface at all.

Adapters and UI layers SHOULD NOT introduce additional independent permission switches. The three layers above are sufficient — adding adapter-level switches creates shadow permission systems that can diverge from the actual ACL state.

6.6.3.1 Effects of an absent ACL or approval handler

Layer 2 — a missing acl/ path attaches nothing. When acl.root resolves to a path that does not exist, implementations MUST attach no ACL and MUST NOT synthesize an empty default_effect: deny ACL in its place. An empty default-deny ACL denies every inter-module call, so synthesizing one would break every project that has no acl/ directory — which is every project that has not opted in. default_effect: deny is the default within a ruleset that exists; it is not a default for the absence of one. Pinned by ../../conformance/fixtures/acl_root_discovery.json.

Layer 3 — a missing ApprovalHandler denies a call that requires approval. The default approval gate MUST reject such a call before module execution. An explicit ExecutionPolicy(strict = false) selects the compatible warn-and-continue behavior (§7.4, §7.9.4).

6.6.3.2 A configured layer is not necessarily an enforced one

Layers 2 and 3 are pipeline steps — acl_check and approval_gate (§5.16, execution-pipeline.md). An ExecutionStrategy that does not contain the step does not run the layer, even when the ACL object or the ApprovalHandler is attached to the executor.

Three of the five preset strategies (execution-pipeline.md) remove both; performance removes only middleware_before and middleware_after:

Preset acl_check approval_gate
standard present present
internal removed removed
testing removed removed
performance present present
minimal removed removed

So executor.set_acl(acl) followed by selecting the internal strategy leaves an ACL attached and never consulted. Implementations SHOULD warn at the moment the mismatch is created — when an ACL or handler is attached to an executor whose current strategy has no corresponding built-in step — and MUST expose the condition for reading through §6.6.5, so an adapter or a health endpoint can observe it rather than infer it from the presence of the object.

Consequently, for any consumer asking "what is gating this registry?", acl != null is not the answer. The two questions — is an object configured and is the gate wired into the running pipeline — are independent, and collapsing them into one boolean reports "protected" in precisely the configuration a conformant implementation is already warning about.

6.6.4 UI Adapter Guidelines

Explorer-style UIs that display module listings SHOULD:

  1. Classify by prefix: Use module_id.startswith("system.") to separate system modules from user modules in the UI.
  2. Reflect backend state: If no system.* modules appear in the listing, hide management UI elements. If they appear, show them.
  3. Not duplicate authorization: The UI should faithfully reflect what the backend exposes. If ACL blocks a call, the Executor returns ACL_DENIED — the UI handles this error gracefully, rather than pre-filtering modules with its own logic.

This "backend-driven visibility" approach ensures the UI always matches the actual permission state without maintaining a parallel authorization model.

6.6.5 Governance State Query

§6.6.3.2 establishes that configured and enforced are independent. This section defines the read-only accessor that lets a consumer observe both without guessing, and without each adapter re-deriving it from whatever the executor happens to expose.

Implementations MUST expose a public, read-only accessor returning the governance state of an executor.

Canonical signature (pseudocode):

executor.governance_state()
→ GovernanceState    # a value object of booleans; MUST NOT expose the ACL or handler itself

Method naming follows language idiom (governance_state() in Python and Rust, governanceState() in TypeScript). Field names are normative and identical across languages in their language-idiomatic casing — an adapter written against one SDK must read the same facts from the other two.

6.6.5.1 Fields

Eight observations, each a plain fact about the executor's current state, plus one derived flag.

Field Meaning
control_modules_registered At least one system.control.* module is in the registry. This is a fact about the registry, not about configuration: the two sys_modules flags of §6.6.3 are the usual cause, but internal or manual registration can produce one without them, and the accessor MUST report what is registered either way.
read_modules_registered At least one read-only system.* module (system.health.*, system.usage.*, system.manifest.*) is in the registry.
acl_configured An ACL is in force for this executor: the built-in ACL gate of the running strategy holds an ACL, or — when no built-in ACL gate is wired — an ACL is attached to the executor (§6.6.5.5).
builtin_acl_gate_wired The running strategy contains a step the executor recognises as the built-in ACL gate. See §6.6.5.2 — this is a type/capability test, never a name test.
approval_handler_configured An ApprovalHandler is in force: the built-in approval gate of the running strategy holds one, or — when no built-in approval gate is wired — one is attached to the executor (§6.6.5.5).
builtin_approval_gate_wired The running strategy contains a step recognised as the built-in approval gate.
policy_strict An ExecutionPolicy with strict = true (§7.9) is in force — held by the built-in approval gate of the running strategy, or attached to the executor when no such gate is wired (§6.6.5.5) — which makes the approval gate fail closed for a call the gate engages on.
all_control_modules_require_approval Every registered system.control.* module declares annotations.requires_approval = true. Read from module metadata; false when no control module is registered. See §6.6.5.1.1 — without this the approval half of the derived flag is unsound.
unprotected_control_surface Derived; defined below.

unprotected_control_surface MUST be computed exactly as:

unprotected_control_surface =
      control_modules_registered
   && !(acl_configured && builtin_acl_gate_wired)
   && !(builtin_approval_gate_wired
        && all_control_modules_require_approval
        && (approval_handler_configured || policy_strict))

Read it as: no built-in gate that this runtime knows how to recognise is standing in front of system.control.*.

Two things it does not claim, and implementations MUST NOT document it as claiming:

  1. That protection exists when it is false. A configured, wired ACL may permit every call. The flag reports the absence of a gate, never the presence of protection. Implementations MUST NOT name it is_secure, expose an inverse spelled as safety, or otherwise present it as a security verdict.
  2. That nothing will stop the call when it is true. A deployment may enforce through a custom pipeline step, custom middleware, or an upstream gateway. Those are invisible to this accessor by construction and are not negated by the flag.

The read modules are reported separately for the reason given in §6.6.3: seven read-only modules with no ACL is an information-disclosure question, and folding them into the control-surface flag makes it fire on a configuration with no write surface at all.

6.6.5.1.1 Why the two gates are not symmetric

The ACL gate and the approval gate look parallel and are not:

  • acl_check is unconditional. When the step is present and an ACL is attached, every call through the pipeline is evaluated against the rules. "Configured and wired" therefore does mean "this gate stands in front of system.control.*".
  • approval_gate is per-module conditional. The step resolves whether this module needs approval — from annotations.requires_approval, or from an ExecutionPolicy that forces it — and when it does not, the step returns immediately. The handler is never consulted and strict never fires.

So a wired approval gate with a handler attached, or with strict = true, gates nothing at all for a control module that does not declare requires_approval. And §6.7 cross-cutting requirement 3 states that requirement as a SHOULD, not a MUST, while §6.6.5.1 notes that control modules can reach the registry through internal or manual registration. A conformant deployment with ungated system.control.* modules is therefore ordinary, not exotic.

Treating "wired + (handler | strict)" as sufficient would make the flag report a gate that is not there — a false false — which is the direction §6.6.5.2 forbids.

What this observation deliberately does not cover. An ExecutionPolicy may force approval on a module that does not declare it (a policy rule, or gate_destructive). Resolving that per module would require the accessor to evaluate policy, which emits audit events and would break the pure-read requirement of §6.6.5.3. all_control_modules_require_approval therefore reads the annotation only, and a policy-forced gate is invisible here — failing in the conservative direction: the flag reports true (no recognised gate) where a policy may in fact gate. That is the same "invisible by construction" caveat the flag already carries for custom middleware and upstream gateways, and it is stated for the same reason.

6.6.5.2 Gate detection MUST be by type, not by name

StrategyInfo (see Execution Pipeline) carries name, step_count, step_names and description — names only. A custom step named acl_check that never consults an ACL satisfies a name test.

The *_gate_wired fields MUST therefore be determined by the step's type or an explicit capability marker, matching the test the executor performs when it wires a gate: attaching an ACL locates the step by both its name and its built-in type before injecting, and warns when no such step exists.

The direction of failure is the reason this is a MUST. A name test on a look-alike step produces builtin_acl_gate_wired = true, hence unprotected_control_surface = false — the accessor reporting a gate that is not there. A false true on the derived flag is merely conservative; a false false is not.

This is also why the accessor belongs on Executor, where the step objects are reachable, and MUST NOT be derived by adapters from describe_pipeline() or list_strategies() output. Extending StrategyInfo with a capability marker is a conforming alternative implementation, but it is a public-API change and is not required here.

6.6.5.3 Constraints
  1. Pure read. governance_state() MUST NOT enforce, warn, throw, or mutate any executor state. What to do about an unprotected control surface belongs to the caller — a serve-time adapter may warn or refuse, a test may assert, a health endpoint may report. Putting the reaction inside the accessor makes it unavoidable and untestable.
  2. Booleans only. The returned value MUST NOT contain the ACL object, the ApprovalHandler, the ExecutionPolicy, or any rule content. An SDK that already exposes those (for example as public struct fields) MAY keep doing so; this accessor answers a different question and does not replace them.
  3. No default changes. The accessor changes no behaviour. In particular the two invariants of §6.6.3.1 stand: a missing acl/ path still attaches nothing, and a missing ApprovalHandler still warns and continues under a non-strict policy.
  4. Live, not cached. The returned value MUST reflect the executor's state at the moment of the call. Swapping the strategy, attaching an ACL, or registering a control module after a previous call MUST be visible in the next one.
6.6.5.4 Conformance

Pinned by ../../conformance/fixtures/governance_state.json. Every field, the derived flag included, MUST be identical across implementations for every case, and the coverage MUST include at minimum:

  • no system modules registered;
  • read modules only;
  • control modules with an ACL attached but no acl_check step in the running strategy (the internal / testing / minimal presets of §6.6.3.2);
  • control modules with an ACL attached and the built-in step present;
  • control modules with an ApprovalHandler but no approval_gate step;
  • control modules that do NOT declare requires_approval, with the approval_gate step wired and an ApprovalHandler attached — unprotected_control_surface MUST be true, because the gate returns before consulting the handler (§6.6.5.1.1);
  • the same, with ExecutionPolicy(strict = true) instead of a handler — MUST also be true, for the same reason: strict never fires on a call the gate does not engage on;
  • control modules that all declare requires_approval, gate wired, handler attached — unprotected_control_surface MUST be false;
  • control modules where some but not all declare requires_approval — MUST be true; one ungated write module is a hole in the surface;
  • control modules with ExecutionPolicy(strict = true) and no handler;
  • control modules with none of the three;
  • control modules with a custom step named acl_check that is not the built-in gate — builtin_acl_gate_wired MUST be false.

The last case is the one that decides whether an implementation satisfies §6.6.5.2 or merely appears to.

6.6.5.5 Providers reach the gate they configure

An ACL, an ApprovalHandler and an ExecutionPolicy are providers; the built-in acl_check and approval_gate steps are where they take effect. The two MUST NOT drift apart (D-129):

  1. Binding. A provider given to an executor — through its constructor or through set_acl() / set_approval_handler() / the policy setter — MUST be bound into the corresponding built-in gate step of the running strategy, located by type (§6.6.5.2). This holds however the strategy was supplied: by default, by preset name, from a pipeline: section, or as a pre-built strategy instance. A provider given to the executor replaces the one the step already held. An executor given no provider leaves the step's provider unchanged.
  2. Strategy replacement. When the running strategy is replaced, the executor's providers MUST be bound into the new strategy's built-in gate steps by the same rule.
  3. Reporting. governance_state() MUST report what the running built-in gate step holds, not what the executor was given (§6.6.5.1). A gate enforcing a provider the executor never saw is reported as configured; a provider the executor holds that no running gate enforces is reported as configured and not wired.

Rationale: acl_configured && builtin_acl_gate_wired is read as "this gate stands in front of the call". If a provider can sit on the executor while the running gate holds nothing, the pair reports a gate that does not exist — the false false §6.6.5.2 forbids — and the call runs ungated.

Pinned by ../../conformance/fixtures/gate_provider_binding.json.

6.7 Canonical System Module Catalogue

This section documents the canonical system.* module catalogue. Conformant SDKs at the indicated level MUST ship modules with these exact Canonical IDs, equivalent semantics, and equivalent input/output schemas (verified by ../../conformance/fixtures/system_modules_hardening.json). This catalogue is the contract surface. Where this repository ships a canonical schema for a module, that schema is the source of truth and the SDK source MUST match it; every module in the catalogue is covered by a file in ../../schemas/ (sys-health-*, sys-manifest-*, sys-usage-*, sys-control-*).

Canonical ID Layer Read/Write Required at Description
system.health.summary Observability Read Level 1 Aggregated health overview (counts by status, per-module entries)
system.health.module Observability Read Level 1 Detailed health for a single module (latency p50/p99, error count, error rate)
system.manifest.module Introspection Read Level 1 Full manifest for one module (input_schema, output_schema, annotations, tags, dependencies, source path)
system.manifest.full Introspection Read Level 1 Full manifest for all registered modules
system.manifest.search Introspection Read Level 1 Paginated summaries visible to the requesting caller (§6.10)
system.usage.summary Observability Read Level 1 Aggregated usage statistics (calls, errors, latency)
system.usage.module Observability Read Level 1 Per-module usage statistics
system.control.update_config Administration Write Level 2 Update a runtime configuration value by dot-path key (audit-logged)
system.control.reload_module Administration Write Level 2 Hot-reload a module by module_id or path_filter glob (mutually exclusive); MAY cascade to dependents
system.control.toggle_feature Administration Write Level 2 Enable/disable a registered module via ToggleState; persists via OverridesStore if configured

Cross-cutting requirements:

  1. Registration MUST use register_internal() (or equivalent privileged API) per §6.6.1 — the public register() MUST reject any module_id starting with system..
  2. Read modules (system.health.*, system.usage.*, system.manifest.*) MUST NOT mutate framework state. Calling them with any inputs MUST be safe to repeat.
  3. Write modules (system.control.*) MUST emit audit events through the framework EventEmitter and SHOULD declare annotations.requires_approval = true to surface the Approval Gate (§7) for destructive operations.
  4. system.control.reload_module input MUST accept exactly one of module_id (exact match) or path_filter; supplying both or neither MUST raise a validation error. path_filter is a glob-dialect pattern matched with A25 (§9.2.3) against each registered module ID. Naming the algorithm is what makes one control-plane request reload the same set of modules in every implementation; "glob" alone names no dialect. The optional lifecycle object selects managed reload (§12.7.9).
  5. system.control.update_config MUST redact sensitive keys (per §10.6.1 obs.redaction.sensitive_keys) in both old_value and new_value fields of its output and audit event.
  6. system.control.toggle_feature state MUST persist via the configured OverridesStore so toggle state survives process restart; without persistence, toggle decisions revert to the registered defaults on reload.

Conformance note: SDKs declaring Level 1 conformance (Conformance §3) MUST register the 7 read modules. SDKs declaring Level 2 MUST additionally register the 3 control modules. Implementations MAY register additional modules under system.<vendor>.* namespaces — these are NOT covered by this canonical catalogue and MUST NOT collide with the names above.

6.7.1 Usage Module Output Contract

§6.7 requires system.usage.summary and system.usage.module to ship with "equivalent input/output schemas". This section states the parts of that contract an SDK cannot infer, and ../../schemas/sys-usage-summary.schema.json and ../../schemas/sys-usage-module.schema.json are the canonical shape.

Two of the requirements below are value semantics that no JSON Schema can assert — a wrong p99_latency_ms and a full-history call_count are both a number in the right place. Those are pinned by fixture (§6.7.1.6), not by schema.

6.7.1.1 period is a filter, not an echo

Both modules accept a period input, default "24h".

Grammar. period MUST match ^[1-9][0-9]*[hd]$ — a positive integer followed by h (hours) or d (days). Implementations MUST declare this pattern in the module's input_schema so a malformed value is rejected by input validation (§12.3 Step 7) with SCHEMA_VALIDATION_ERROR, uniformly, rather than by an implementation-private parser that raises a language-native error in one SDK and silently accepts in another.

The leading [1-9] is normative: "0h" is MUST-reject. A zero-width window is not a meaningful query, and accepting it produces an all-zero report that reads as "no traffic" rather than as "bad input". Signs ("+3h", "-5d"), fractions ("1.5h") and uppercase units ("24H") are likewise rejected.

Semantics. The window is [now − period, now] in UTC. Every statistic in the output MUST be computed over that window:

Module Fields that MUST honour period
system.usage.summary total_calls, total_errors, and every entry of modules[] — call_count, error_count, avg_latency_ms, unique_callers, trend
system.usage.module call_count, error_count, avg_latency_ms, p99_latency_ms, trend, every entry of callers[], and hourly_distribution

An implementation MUST NOT echo period in its output while computing any statistic over the full retained history. That failure mode is silent by construction — the response names the window it did not apply.

trend compares the requested window against the immediately preceding window of equal length ([now − 2·period, now − period]), per §6.7.1.5.

6.7.1.2 hourly_distribution

Emitted by system.usage.module only.

  1. Key format. hour MUST be the UTC hourly bucket key YYYY-MM-DDTHH — e.g. 2026-03-08T14. This is the key UsageCollector produces; a module layer that reformats it (to 2026-03-08T14:00:00Z, or to anything else) MUST NOT do so. One serialization, one place.
  2. Cardinality. The array MUST contain exactly 24 entries, covering the 24 hourly buckets ending at the current hour (now − 23h .. now). Gaps MUST be zero-filled (call_count: 0, error_count: 0) rather than omitted, so a consumer can index the array positionally without reconciling missing keys.
  3. Order. Entries MUST be sorted ascending by hour.
  4. Relationship to period. The 24-entry window is fixed and is not widened or narrowed by period; only the counts inside each bucket are filtered by it. A period shorter than 24h therefore yields leading zero buckets, and a longer one does not add entries. This is stated because it is the one place where "every statistic honours period" (§6.7.1.1) would otherwise read as licence to change the array length.
6.7.1.3 p99_latency_ms

p99_latency_ms MUST be the nearest-rank 99th percentile of the latency samples in the window, computed as:

Algorithm: p99(latencies)

Input:  latencies — list of latency samples in ms, in any order
Output: p99       — number

Steps:
  1. If latencies is empty → Return 0
  2. sorted ← ascending sort of latencies
  3. N      ← length(sorted)
  4. rank   ← ceil(0.99 × N)          // 1-based rank
  5. index  ← min(rank, N) − 1        // clamp, then convert to 0-based
  6. Return sorted[index]

Implementations MUST NOT interpolate between adjacent samples, and MUST NOT return the element after index.

Worked example, normative. For latencies = [1, 2, …, 100] (N = 100): rank = ceil(99.0) = 99, index = 98, so p99 = 99. An implementation returning 100 has read one element past the rank it computed. For N = 1 the result is the single sample; for N = 0 it is 0.

The empty-input result is 0 and not null: the field is required and typed number in sys-usage-module.schema.json, so a module with no samples in the window still emits a well-formed report.

6.7.1.4 caller_id in callers[]

A call recorded with no caller identity MUST be attributed to the literal string "unknown". Implementations MUST NOT omit the entry, use null, or substitute @external — @external is an ACL matching token (§6.2) and reusing it here would make an unattributed call indistinguishable from an externally-attributed one in a usage report.

6.7.1.5 trend

trend MUST be one of stable, rising, declining, new, inactive, decided by comparing the call count in the requested window (current) against the count in the immediately preceding window of equal length (previous):

Condition trend
current == 0 and previous == 0 stable
current == 0 and previous > 0 inactive
previous == 0 and current > 0 new
current / previous > 1.2 rising
current / previous < 0.8 declining
otherwise stable

The thresholds are normative so that the same traffic does not read as rising in one SDK and stable in another. The order of the rows is normative too — the zero cases are decided before the ratio, which is what keeps the ratio from dividing by zero.

6.7.1.6 output_schema and conformance
  1. Both modules' output_schema() MUST declare the full field contract — type, properties and required — matching the canonical schemas. A bare {"type": "object"} is MUST-reject: it satisfies §6.7's "equivalent output schemas" only in the sense that any two such declarations are equivalent to each other.
  2. Output from every conformant SDK MUST validate against sys-usage-summary.schema.json / sys-usage-module.schema.json. Both declare additionalProperties: false: a field one SDK emits and the others do not is a parity gap, and failing loudly is the intended behaviour.
  3. Schemas cannot assert §6.7.1.1 or §6.7.1.3. A full-history call_count and an off-by-one p99_latency_ms are both well-typed values in the right field. Those two, and only those two, are pinned by ../../conformance/fixtures/usage_contract.json with fixed inputs and expected outputs.

6.8 ACL Introspection

An ACL enforces two things: an ordered rule list and a default_effect. Both are decisions an operator made, and both MUST be readable back from the loaded object.

Accessor Returns Level
default_effect The effective default, "allow" or "deny" MUST
rules The current rule list, in definition order MUST
  1. Both MUST be reachable from application code through a documented public path. A field that is private, #-prefixed, or non-pub does not satisfy this, and neither does a leading-underscore name (see API Surface & Naming Conventions §3).
  2. Both MUST be pure reads: they MUST NOT emit an audit event and MUST NOT mutate state.
  3. Both MUST return without leaving the caller holding a lock. An accessor MAY acquire the ACL's lock internally, take its copy, and release it before returning — that is the intended implementation, not a violation. What is forbidden is handing the caller a guard, a borrow, or any value whose validity depends on a lock the caller must later release; a caller MUST be able to invoke either accessor from inside an audit logger or a condition handler without deadlocking.
  4. rules MUST NOT hand out a reference through which the caller can mutate the ACL's own list. Return an immutable view or a copy, taken under the same snapshot discipline check() uses (§6.3) — which is rule 3's brief internal acquisition, not a held lock.
  5. After reload(), both accessors MUST reflect the reloaded file. They read the live object, never a cached parse.

Rationale. Tooling that reports or audits the enforced policy — an admin surface, a preflight report, a linter for the rules §6.1.2 flags — would otherwise have to re-read and re-parse the ACL file to recover a value the loaded object already holds. That second copy can drift from the object across reload(), and where the field is private or non-pub, re-parsing is not merely wasteful but the only option available.

6.8.1 AccessDecision — the structured result

check() returns a boolean, which can carry authorization but not the second axis of §6.1.6. Implementations MUST provide a structured accessor alongside it, sync and async:

Member Meaning
access allow / deny — the authorization decision alone (§6.3)
approval_required whether this call must be put to a human before it runs
matched_rule_index index of the rule that decided access, as in §6.3.1
reason which branch of §6.3 produced the decision, as in §6.3.1

The noun is fixed across SDKs; the shape is idiomatic per API Surface & Naming Conventions §4. The boolean entry points remain alongside it.

The boolean MUST fail closed on an approval requirement. A decision resolving to allow with approval_required: true MUST make check() return false. This is a property of the decision, not of the matched rule: the requirement may be a pending one raised by an unevaluable rule that did not itself match, or carried through default_effect: allow (§6.1.1 rule 5), and the boolean MUST fail closed on those identically.

check() is public API consumed by callers that are not the Executor — tooling, preflight helpers, third-party integrations — and such a caller can only read a boolean as "let it through / do not". Returning true would let it execute a call the ACL said needed a human. Returning false is wrong in the benign direction: the caller sees a refusal where the truth was "ask first". The Executor uses the structured API and is unaffected, and a boolean caller meets this only when an operator has authored a rule carrying approval.

6.9 Governance precedence

Approval requirements have more than one source. The composition is normative, not per-SDK.

# Interaction Rule
1 Rule matching First match wins. The matched rule determines access; when access is allow, the approval requirement is that rule's own union any pending requirement raised by an unevaluable allow rule (§6.1.1 rule 5), which may therefore originate in a rule that did not match. When access is deny the requirement is false — a denial clears a pending requirement rather than composing with it (§6.1.1 rule 5), because "denied and needs approval" is the state §6.1.6 rule 2 already rejects
2 default_effect allow / deny only. There is no default approval source, but default_effect: allow MUST carry a pending requirement (§6.1.1 rule 5) through to the result. Absent one, no match means false. An empty rule list reaches the default effect too and can never carry a requirement, since only a rule can raise one
3 ACL requirement + module annotations.requires_approval Union. Either source may require a human; neither may cancel the other
4 ACL requirement + ExecutionPolicy override A policy may add a requirement and MUST NOT remove one the ACL set. A policy requires_approval: false overrides the module's annotation, never the ACL's decision
5 gate_destructive (§7.9.2) Contributes to the union of #3
6 Preflight (§7.9.5) validate() MUST report the union of #3–#5 for the given call site
7 Audit (§6.3.1) decision stays "allow" / "deny"; the requirement is a separate field

Rule 4 is the one that is not obvious. The ACL is a caller-scoped authorization layer; ExecutionPolicy is a module-scoped platform override. Letting a module-scoped override cancel a caller-scoped decision is a privilege escalation: a policy rule written for orders.* would silently strip an approval requirement an ACL author attached to one untrusted caller. Union is the only safe composition.

Rule 7 is a compatibility constraint, not a modelling preference. AuditEntry.decision is a string that downstream consumers parse. A third value breaks every existing parser; a new field beside it does not.

6.10 ACL-aware capability discovery

Capability discovery answers whether a trusted caller may see metadata for an active, public module. Every invocation MUST still satisfy the execution pipeline's ACL, validation, policy, approval, and lifecycle checks.

6.10.1 Silent visibility

  • The Executor MUST use the prospective target invocation's caller frame, depth, and trusted identity, with the ACL that governs its pipeline. It MUST NOT derive identity or caller from query data. When no ACL governs the default assembly, public active modules are eligible.
  • ACL.evaluate_visibility MUST preserve §6.1–§6.2 rule ordering, structural prechecks, and fail-closed resolution. It MUST evaluate known built-in identity, role, and depth predicates. Argument predicates and custom handlers, including replacements for built-ins, are unknown to discovery. The probe MUST NOT supply fabricated arguments or run these handlers. After structural precheck, false in an AND and true in an OR settle the corresponding expression. Negating unknown remains unknown.
  • The probe MUST grant visibility only if every reachable first-match result is an allow. A reachable unknown deny hides the target. An unknown allow may change the approval requirement, but the fallthrough path still requires a grant. Malformed conditions retain §6.1.1 deny and pending-approval semantics. A custom ACL MUST provide an equivalent silent decision for its governed targets to be eligible.
  • Discovery MUST NOT emit the ordinary ACL audit entry or denied event, write to execution error history, validate inputs, call the policy evaluator or approval handler, or run module hooks or execution. It MUST NOT return hidden, disabled, draining, missing, or otherwise ineligible registrations. Metadata MUST correspond to the authorized registration generation, even when the same version is registered again.

6.10.2 Summaries, definition lookup, and paging

The Executor and APCore MUST expose idiomatic equivalents of list_callable(context, options) and get_callable_definitions(module_ids, context). SDKs MAY provide a version-aware single-definition lookup for adapters. A version selector MUST use the invocation resolver and MUST NOT disclose stale or unresolvable metadata.

  • list_callable MUST produce a CapabilityPage containing items and an opaque, nullable next_cursor. Each ModuleSummary MUST contain module_id, resolved version, description, tags, readonly, and access_hint. Summaries MUST NOT include schemas, source paths, or arbitrary metadata.
  • access_hint MUST be requires_approval when every eligible path requires approval under ACL and Step 5, conditional when the requirement can vary or the final-input policy can add a requirement, and allowed otherwise. include_approval_required: false MUST omit entries with requires_approval.
  • Filters are query, prefix, tags, and readonly. Omitted filters are unconstrained. The default lexical search MUST trim and lowercase the query and match it as one substring within the lowercased module ID, description, or a single tag. Prefixes and requested tags match literally, and every requested tag MUST be present. Results MUST have deterministic order with a module ID tie breaker. Page size defaults to 20 and the allowed range is 1–100.
  • A cursor MUST be bound to the issuing Executor, trusted principal and caller frame, and normalized request filters, including page size. Invalid, expired, or foreign cursors MUST fail without returning entries or cursor binding details. Every emitted entry MUST pass current visibility, including after ACL or registry changes.
  • Definition lookup MUST return the full detached input and output JSON Schemas with the resolved module ID and version. It MUST check visibility again. Missing, hidden, and unauthorized IDs MUST be omitted indistinguishably; duplicate IDs MUST appear at most once in first-request order.
  • A configured CapabilitySearchProvider (§11.3) MAY rank candidate IDs. The Executor MUST run the same visibility and active-registration checks on those IDs before returning metadata.

6.10.3 Manifest search and adapter projection

system.manifest.search is a read-only module using the filters and pagination in §6.10.2. Clients MUST omit unset input fields. Its result uses the CapabilityPage shape in snake_case with a nullable next_cursor. The call MUST pass its own ACL. Target visibility MUST then use the original trusted caller frame, excluding the search module's own frame. The existing system.manifest.full and system.manifest.module retain their own ACL checks and wire contracts.

A caller-aware adapter MUST use the same trusted context as its invocation path when applying discovery to its published modules. Standard MCP tools/list MUST retain the complete inputSchema of each eligible tool. Lightweight summaries and definition lookup MUST use the separate discovery API. MCP exposes system.manifest.search as a read-only query tool when the module is available to the requester. When the adapter publishes module documentation resources, listing and direct access MUST apply the same visibility. Transport control tools and ACL-gated management manifests retain their own authorization contracts.

6.11 Trusted Identity Delegation

An Identity MAY carry immutable scopes, on_behalf_of, and issuer fields. scopes is a set of nonempty, case-sensitive strings with no characters in the Unicode White_Space property. SDKs MUST normalize duplicate members. An absent scope set leaves an ordinary identity under the existing ACL contract. A present empty set explicitly grants zero scopes. The optional issuer qualifies the identity namespace and, when supplied, MUST be a nonempty string. Identity attributes remain separate from these fields.

The Identity in the Context is the current actor. Each on_behalf_of link points toward the root subject that delegated authority. For a direct identity, the actor is also the root subject and delegation depth is zero. Trusted hosts MAY create a scoped root and derive a delegated identity from a trusted direct actor and an explicit requested scope set. Each requested scope MUST be present in the immediate parent's effective set and in the recipient's own ceiling if the supplied actor already carries one. Every linked identity MUST have an explicit scope set, including the parent of the first delegation. SDKs MUST reject cycles, malformed authority fields, widening, and chains deeper than eight active links. Repeated actor identifiers in a bounded, attenuating chain confer no additional authority.

Context and identity restoration MUST validate the same structure and attenuation as local construction. The wire names are scopes, on_behalf_of, and issuer, with on_behalf_of containing a nested identity object. SDKs MUST omit absent fields and preserve the legacy wire shape for identities that omit all three. Callers MUST NOT treat successful deserialization as authentication or accept an untrusted caller's payload as the authority of an existing Context.

For a scope-enabled identity, the first matching ACL allow rule MUST contain a nonempty, top-level scopes condition enforced by the stock predicate. Each listed scope MUST be present on the current actor. An otherwise matching allow without this grant MUST produce a deny, even if a later rule could grant access. Scope tests reachable only through compound conditions and an allow default MUST NOT grant access. Deny rules retain the ordinary condition and ordering semantics in §6.1 and §6.3. Conditions for subject_types and subject_roles evaluate against the root subject. max_delegation_depth evaluates against the active link count. An identity-dependent condition without a trusted identity MUST NOT match.

The effective ACL configuration and pipeline MUST enforce scoped authority for execution, streaming, preflight, and discovery. When the Executor cannot establish that the scope gate applies, each of those paths MUST fail closed. Discovery uses the prospective caller frame in §6.10 and applies the same ordered semantics without emitting ACL audit entries.

SDKs MUST bind delegation-sensitive cursors and approval resumption to a stable projection of the current actor, root subject, effective scopes and trusted active lineage. This projection includes security-relevant role memberships, identity types and issuer qualifiers, and excludes arbitrary attributes and token history. Final-input policy MUST receive a detached view of the trusted authority. A deployment MAY use a separate stable ownership projection for transport records, keyed on issuer-qualified actor and root subject. Reauthentication can carry the same owner, but current scopes MUST govern protected operations and scoped authority MUST participate in permission cache keys.

A handler that can resume a pending approval for a scope-enabled identity MUST advertise support for authority scope and MUST verify the authority projection alongside the applicable invocation scope. The SDK MUST NOT issue a pending credential or attempt resumption for a scope-enabled identity when the handler lacks this capability. A handler MUST NOT grant access to or consume a record for a different authority. Final-scope pending approvals also require the capability specified in §7.2. Legacy approvals retain their existing invocation binding.

ACL audit entries for scope-enabled identities MUST include actor_id, subject_id, and active delegation_depth. When an audit event carries a redacted identity snapshot, D-93 redaction MUST apply to attributes at every hop. The snapshot MUST NOT contain raw credentials.

Adapters that opt into RFC 8693 JWT scope and actor projection MUST verify the signature, expected iss and aud, and required exp before accepting the projection. They MUST validate nbf and iat when supplied. The standard scope claim uses the scope-token string syntax in RFC 6749 §3.3. A deployment MAY map an additional provider claim whose value is a scope string or array of scope tokens. When both configured claims are present, their normalized sets MUST agree. At least one configured scope representation MUST be present. The top-level sub and outermost act claim yield at most one active Core link. Outer actor roles require an explicit trusted mapping. Nested act claims are history limited to a structurally validated depth of eight. Those claims MUST NOT contribute to Core roles, scope, active depth, approval, or ownership. A supplied credential on a governed route that fails verification or the configured claim mapping MUST be rejected when projection is enabled. Explicitly exempt endpoints MUST NOT establish scoped authority from rejected credentials. See RFC 8693 §4.1 for the actor claim and §4.2 for scope strings.


7. Approval System

7.1 Overview

The Approval System provides runtime enforcement of the requires_approval annotation. While annotations are generally hints for AI/LLM clients, requires_approval is unique: when an ApprovalHandler is configured, the Executor blocks execution of modules marked requires_approval=true until explicit approval is granted.

This mechanism is the bridge between annotation-level metadata and runtime governance: Human-in-the-Loop approval is enforced by the Executor, not merely hinted at.

Relationship to ACL:

Concern ACL (§6) Approval System (§7)
Question answered "Is this caller_id allowed to invoke this module?" "Does this invocation need human sign-off?"
Mechanism Pattern-based rule matching Pluggable handler with external interaction
Timing Step 4 in Executor pipeline Step 5 in Executor pipeline (after ACL)
Interaction None (deterministic rule evaluation) May involve user dialog, webhook, or agent confirmation

A caller_id may pass ACL (they have the role to call deploy.prod) but still require approval for each invocation (because the module is destructive).

7.2 ApprovalHandler Protocol

Implementations MUST define an ApprovalHandler protocol (or interface) with the following contract:

Interface: ApprovalHandler
  /**
   * Request approval for a module execution.
   * Implementation decides whether to block synchronously or return pending.
   *
   * @param request — ApprovalRequest containing module_id, arguments, context, annotations
   * @return result — ApprovalResult with status: approved|rejected|timeout|pending
   */
  request_approval(request: ApprovalRequest) → ApprovalResult

  /**
   * Query the status of a pending approval.
   * Default implementation SHOULD return rejected.
   *
   * @param approval_id — Identifier from a prior pending result
   * @return result     — ApprovalResult with current status
   */
  check_approval(approval_id: String) → ApprovalResult

  /**
   * Authorize resumption of a specific invocation (optional, Phase B).
   * @param approval_id — Resume credential from a prior pending result
   * @param request    — ApprovalRequest for the current invocation
   */
  check_approval_for_call(approval_id: String, request: ApprovalRequest) → ApprovalResult

These methods MUST be asynchronous (async/await) in implementations that support it. An SDK MUST reject a request to resume an approval when the configured handler does not implement scoped resumption. Status-only handlers remain usable for fresh requests.

Before returning approved from check_approval_for_call, a handler MUST verify the credential's expiry and match the current request to the original approved invocation. The scope MUST cover the trusted principal (when present), caller_id, canonical target ID, and the arguments. The handler MUST consume the approved credential atomically with successful verification. A handler using durable storage MAY authorize resumption after a process restart.

A handler that implements final-scope resumption MUST explicitly advertise supports_final_scope in the SDK's native form. It MUST distinguish the final scope from legacy records and verify the resolved module version and canonical argument digest as well as the trusted principal, caller and target. Absence of a final-scope marker on a stored record MUST NOT match a final-scope request. An SDK MUST NOT expose a pending final-scope credential or pass one to a handler that has not advertised this capability. Fresh synchronous approval remains available to such a handler.

7.3 Data Types

7.3.1 ApprovalRequest

ApprovalRequest:
  type: object
  required: [module_id, arguments, context, annotations, caller_id, action]
  properties:
    module_id:
      type: string
      description: "Target module's canonical ID"
    arguments:
      type: object
      description: "Detached snapshot of the business arguments at the enforcing approval gate. Step 5 uses submitted arguments. The opted-in Step 7.5 uses the validated execution inputs."
    module_version:
      type: [string, "null"]
      description: "Version on the registration selected by Step 3, when supplied by the final approval gate. Null indicates no registered version."
    canonical_args_digest:
      type: [string, "null"]
      pattern: "^[0-9a-f]{64}$"
      description: "SHA-256 digest of the final-scope argument encoding. A non-null value indicates final scope. This field is private to the trusted handler contract."
    context:
      type: object
      description: "Execution context (trace_id, identity, call_chain) — see §5.7 Context Parameter Specification"
    annotations:
      type: object
      description: "Module's ModuleAnnotations (requires_approval is guaranteed true) — see §4.4 Module Behavior Annotations"
    caller_id:
      type: [string, "null"]
      description: "The invoking module's canonical ID, read from context.caller_id; null for a top-level/external call, exactly as Context.caller_id is (§5.7) — not the \"@external\" substitution ACL evaluation makes internally"
    action:
      type: string
      description: "The target module's canonical ID being requested, equal to module_id — a flat field so a handler can read request.action without cross-referencing request.module_id under a second name (decision D-03)"
    description:
      type: [string, "null"]
      description: "Module's human-readable description"
    tags:
      type: array
      items: { type: string }
      description: "Module's tags"

caller_id and action (D-03). Both are populated by the approval gate that constructs the request: caller_id = context.caller_id and action = module_id. Conformance: ../../conformance/fixtures/approval_request_fields.json.

7.3.2 ApprovalResult

ApprovalResult:
  type: object
  required: [status]
  properties:
    status:
      type: string
      enum: [approved, rejected, timeout, pending]
      description: "Approval decision"
    approved_by:
      type: [string, "null"]
      description: "Identifier of the approver (human, agent, policy)"
    reason:
      type: [string, "null"]
      description: "Reason for rejection or additional context"
    approval_id:
      type: [string, "null"]
      description: "Confidential resume credential for a pending approval"
    metadata:
      type: [object, "null"]
      description: "Additional metadata from the approval process"
    audit_id:
      type: [string, "null"]
      description: "Optional non-secret approval correlation identifier"

7.4 Executor Integration (Step 5)

The Approval Gate is Step 5 in the Executor's pipeline, between ACL Enforcement and Middleware Before Chain:

Executor Pipeline:
  Step  1: Context Creation
  Step  2: Call Chain Guard
  Step  3: Module Lookup
  Step  4: ACL Enforcement
  Step  5: Approval Gate
  Step  6: Middleware Before Chain
  Step  7: Input Validation
  Step  8: Module Execution
  Step  9: Output Validation
  Step 10: Middleware After Chain
  Step 11: Result Return

Step 11 Contract:

  1. Executor.call() MUST return the module's output dict unchanged (no framework envelope). Output Validation (Step 9) MUST have already passed before Step 11 returns.
  2. Executor.stream() MUST complete the async iterator after the last chunk; the final accumulated dict (recursive deep-merge of all yielded chunks per §5 streaming semantics) is what Step 9 validates.
  3. Executor.validate() MUST return a PreflightResult (§12.2) carrying per-check status, a requires_approval flag, and the duck-type-compatible valid / errors properties.
  4. Trace metadata (trace_id, caller_id, call_chain, executor) MUST be carried on the Context object, MUST NOT be attached to the return value.
  5. Side-channel emissions (events, OTel spans, audit log entries) MAY continue after Step 11 returns; the return value MUST NOT depend on side-channel completion.

Step 5 Algorithm:

Algorithm: approval_gate(module, arguments, resume_credential, context, approval_handler, policy)

Input:
  module         — Resolved module instance
  arguments      — Business arguments at the gate
  resume_credential — Optional private invocation credential from _approval_token
  context        — Execution context (with identity)
  approval_handler — Configured ApprovalHandler or null
  policy         — Attached ExecutionPolicy or the built-in defaults

Behavior:
  1. LET annotations = resolve_effective_annotations(module, policy, ACL decision, context)
  2. IF annotations.requires_approval is false → SKIP
  3. IF approval_handler is null:
       a. IF policy.strict → EMIT rejected decision and THROW ApprovalDeniedError
       b. WARN once per module, then CONTINUE to Step 6
  4. LET request = ApprovalRequest(module_id, snapshot of arguments, context, annotations, ...)
     IF resume_credential is present:
       a. IF approval_handler has no check_approval_for_call → THROW ApprovalDeniedError
       b. LET result = approval_handler.check_approval_for_call(resume_credential, request)
     ELSE:
       a. LET result = approval_handler.request_approval(request)
  5. SWITCH result.status:
       "approved" → CONTINUE to Step 6
       "rejected" → THROW ApprovalDeniedError(result)
       "timeout"  → THROW ApprovalTimeoutError(result)
       "pending"  → THROW ApprovalPendingError(result)

The gate fires on the union of its governance sources (D-96, D-125). Step 1 of the algorithm MUST consult module.annotations. When the registry also holds declared annotations for the module, the gate MUST include the registry declaration in its evaluation (§4.13). The effective metadata starts with the logical OR of the live and declared requires_approval and destructive values. Other annotations come from the live instance. The gate then evaluates the attached policy and the call's ACL approval requirement.

The union binds every reader of requires_approval / destructive for a registered module, not the gate alone:

Reader Requirement
Approval gate (Step 5) Fires on the union.
Executor.validate preflight (§7.9.5) Reports the union, so it cannot disagree with the gate.
Governance-posture accessor (§6.6.5) Reads the union; a module gated by the pipeline MUST NOT be reported as ungated.
system.manifest.* annotations Publishes the union — an agent decides whether to call from this.

An implementation MUST NOT resolve this union with its metadata-merge precedence (§4.13's YAML > code), which is correct for a descriptor and wrong for a gate: the merge lets the weaker declaration win in both directions. Consequently a metadata requires_approval: false does not cancel a module that declares true in code, and the manifest publishes the value the gate enforces — advertising a governance flag the gate does not honour is worse than advertising none, because it is a specific claim an agent acts on.

Rationale: reading only the declared annotations ignores what the module declares, and reading only the module ignores what an operator declared in configuration. Both are fail-open, and on this surface the failure direction is the whole point: requiring approval that was not strictly needed costs a prompt, skipping approval that was needed is a bypass. This mirrors §6.9, where the requirement is the union of the module annotation, the ACL rule and gate_destructive, and where a policy may only add.

The ACL's approval requirement reaches Step 5. §6.1.6 lets a rule require approval for a specific call, so Step 4 produces two results and Step 5 MUST consult both:

  1. The gate fires when the module's annotations.requires_approval is true or the ACL decision for this call carried approval_required or gate_destructive applies — the union of §6.9 rows 3–5.
  2. An ExecutionPolicy override MUST NOT clear a requirement the ACL set (§6.9 row 4).
  3. The ApprovalRequest handed to the handler MUST carry the effective annotations, as §7.9.3 already requires; an ACL-sourced requirement makes requires_approval effectively true for that call.

An implementation that read only the annotation would silently ignore every rule carrying approval — the rule would load, match, and do nothing.

Key behaviors: - When an invocation requires approval and has no ApprovalHandler, the default gate MUST raise ApprovalDeniedError before running the module. An explicit ExecutionPolicy(strict = false) permits the invocation with the warning in §7.9.4. - When an ExecutionPolicy (§7.9) is attached, the gate consults it first: the policy may force approval on a module that does not declare requires_approval, or (with gate_destructive) gate a destructive module. - The _approval_token mechanism (Phase B) allows clients to retry after external approval without re-triggering the approval flow. - The _approval_token key MUST be removed from business arguments before they reach subsequent steps. This applies to an invocation whose strategy omits the approval gate as well. The executor can carry the credential separately for the approval handler. A preflight has no approval decision to resume.

Resume semantics. When a caller retries an APPROVAL_PENDING call with _approval_token in the request arguments, the executor MUST re-enter the pipeline from Step 1. Implementations MUST NOT preserve intermediate PipelineContext state across suspension and resumption. The fresh traversal receives business arguments separately from the resume credential. Steps 1–4 run on both traversals, so the ACL audit entry (§6.3.1) and tracing occur once per traversal. Modules MUST NOT assume those steps are skipped on resume. With the default approval timing, Step 6 (middleware_before) and later steps run only after the gate allows the call to continue. The condition for a host to opt in to final approval is defined in §7.4.1. Neither module middleware nor the module receives the credential as a business argument. External retry and replay layers can persist approval_id and the original inputs to drive this flow. See Durability Boundary §2.2 for integration patterns.

Scope of approved arguments. Fresh and resumed requests use the same gate-time snapshot. In the standard strategy, middleware_before can transform those inputs after approval, and input validation checks the transformed values. A deployment that lets a transformation change the resource or action being authorized can normalize the values before the gate or enforce a separate authorization check on the transformed values.

7.4.1 Opt-in post-validation policy

A host MAY install an instance-scoped PolicyEvaluator using the policy_evaluator extension point. The evaluator is code supplied by the host. Its asynchronous evaluate(request) returns a PolicyVerdict with decision set to allow, deny, or require_approval, and an optional static rule_id. PolicyEvaluationRequest carries the canonical target ID, its resolved registration version, caller_id, trusted identity, a detached snapshot of the validated execution arguments, and the sensitive instance field paths identified by the input schema as JSON Pointers. The evaluator does not receive the resume credential. Registration version refers to the selection in Step 3, including across async evaluation or reload. A host that changes a module's approval-relevant behavior without changing its version is responsible for invalidating its outstanding approvals.

When an evaluator is installed, the strategy MUST preserve the built-in authorization and validation boundaries and run post_validation_policy (Step 7.5) after successful input validation and before the module call or stream producer starts. An incompatible strategy MUST fail configuration or invocation before execution. A skip, replacement, ignored error or recovery MUST NOT bypass the policy decision or dispatch values besides the covered snapshot. Policy evaluation MUST NOT receive inputs from a traversal that did not pass ACL and input validation. Step 4 retains its submitted-arguments ACL contract.

Step 5 computes the early approval requirement without prompting, verifying, or consuming the credential. It MAY fail early when the built-in strict policy requires a handler and none is configured. Hosts enabling the evaluator MUST use before middleware solely for trusted transformations without approval-dependent side effects. Step 7.5 uses the union of the earlier requirement and the evaluator's approval requirement. allow MUST NOT clear an earlier requirement. The gate performs at most one request or one scoped verification on the final snapshot. Both required approval and submitted credentials require a handler. A submitted credential MUST be verified even if the current verdict is allow. Reject a mismatched, expired or consumed credential without a fresh approval request or execution. An evaluator's deny or failure is terminal before approval or dispatch.

Approval uses the same pending, timeout, and explicit denial results as Step 5. The final scope binds caller_id, canonical target ID, resolved module version, canonical_args_digest, and the trusted principal when present. It binds (identity.type, identity.id) for a legacy principal and additionally binds the authority projection in §6.11 for a scope-enabled principal. The scope encoding is local to the producing SDK and is independent of the schema content hash. The handler MUST compare all scope fields as well as the final-scope marker. Scope digests MUST NOT be used to transfer approval between SDKs with different native numeric types.

For the argument digest, the SDK MUST encode the effective argument object as UTF-8. Objects and arrays use compact JSON punctuation, strings use JSON escaping with Unicode scalar values preserved, and object names sort by unsigned UTF-16 code units. Encode null and booleans as JSON literals. Encode safe native integers as i followed by their signed decimal form and ;. Encode finite binary64 floats as f followed by sixteen lowercase hex digits of their bits and ;. Where the language has only binary64 numbers, safe integral values use integer encoding except negative zero. Safe integers are in the inclusive range [-9007199254740991, 9007199254740991]. Reject integers or integral floats outside the range, lone surrogates, non-finite or cyclic values, and host values for which the SDK cannot prove a lossless JSON-shaped projection. The SDK MUST fail closed for an unsupported value and MUST NOT change the business value merely to compute a digest.

Preflight evaluates policy on the same validated input its dry traversal obtains after ACL, without running before middleware. It reports the combined approval requirement without prompting, consuming credentials, or emitting approval or policy-decision events. It MUST NOT invoke module-level preview or preflight callbacks following an authorization failure. Execution always reevaluates after normal transformations. A preflight result is not an approval or an execution permit.

An evaluator has a finite timeout, defaulting to 1,000 milliseconds and bounded by the invocation deadline. Its timeout, malformed verdict, unsupported input representation, or exception is reported as POLICY_EVALUATION_ERROR with retryable: true and user_fixable: false. A denied verdict is POLICY_DENIED with retryable: false, user_fixable: true, and safe user guidance. External cancellation retains the invocation's cancellation outcome. Policy errors and apcore.policy.decision telemetry MUST NOT carry raw arguments, argument digests, credentials, or evaluator exceptions. A pending credential uses the caller-only approval delivery in §7.4. The policy event MAY include the decision, a safe static rule ID, and sensitive schema field paths.

7.4.2 Optional call-tree budgets

A host MAY attach a budget with optional call and cost limits and per-module cost estimates. The limits, estimates, and actual costs are nonnegative integers no greater than 9007199254740991. A missing module estimate is zero. Child calls share the same ledger.

For a budgeted invocation, the stock call-chain guard MUST reserve one slot before dispatch. A budgeted strategy without the guard MUST fail before business execution. Pending approval, rejection, or cancellation before dispatch MUST release the slot. The dispatcher MUST atomically check the estimate against the cost limit and commit the slot and its initial charge before calling the handler or starting a stream producer. Each retry that starts business execution MUST consume a slot and charge. Preflight MUST NOT check, reserve, or commit budget.

The module MAY record an actual total once per active attempt. This replacement is atomic. On an actual overrun, the cost report MUST raise an error and the charge MUST remain in the ledger. If the module handles that error, normal output validation and completion apply to its result. Recording cost without a budget has no effect. Exceeding a limit raises nonretryable CALL_BUDGET_EXCEEDED with details.dimension set to calls or cost. Snapshots report used calls, reserved calls, and total charged cost, capping the reported numbers at the largest portable integer.

7.5 Error Types

Implementations MUST define the following error types under ModuleError:

approval_error_codes:
  APPROVAL_DENIED:
    description: "Approval was explicitly rejected"
    http_status: 403
  APPROVAL_TIMEOUT:
    description: "Approval request timed out without response"
    http_status: 408
  APPROVAL_PENDING:
    description: "Approval is pending — retry with _approval_token after approval"
    http_status: 202

Error hierarchy addition:

ModuleError
├── ...existing errors...
├── ApprovalError              # Base class for all approval errors
│   ├── ApprovalDeniedError    # APPROVAL_DENIED — Explicitly rejected
│   ├── ApprovalTimeoutError   # APPROVAL_TIMEOUT — No response within timeout
│   └── ApprovalPendingError   # APPROVAL_PENDING — Awaiting external approval

Each approval error MUST carry a result field containing the full ApprovalResult.

7.6 Built-in Handlers

Implementations SHOULD provide these built-in handlers:

Handler Behavior Use Case
AlwaysDenyHandler Always returns rejected Default safe behavior when no handler configured but enforcement desired
AutoApproveHandler Always returns approved Testing and development
CallbackApprovalHandler Delegates to a user-provided callback Custom approval logic

7.6.1 The CallbackApprovalHandler callback

The convenience handler exists so a decision can be supplied without implementing the full contract. It MUST NOT be weaker than the contract it wraps:

  1. The callback MUST be asynchronous. An approval handler is I/O-shaped — it may block waiting for human input (§7.8 Phase A) through a UI, a chat tool or similar — and a convenience wrapper that cannot express that use case is a trap rather than an affordance.
  2. The callback MUST be able to express failure in the host language's idiom: a raised exception, a rejected promise, an Err. ApprovalHandler.request_approval returns a fallible result, and a wrapper that can only return a value forces an author to fabricate a "rejected" result for an infrastructure outage — which is indistinguishable in the audit trail from a human saying no.
  3. An SDK MAY additionally provide a synchronous convenience constructor for decisions computable in-process, but MUST NOT give the synchronous one the name other SDKs give the asynchronous one. A reader who knows the handler in one SDK will assume the name means the same thing in the next.

7.7 Protocol Bridge Handlers

Protocol bridges (such as apcore-mcp, apcore-a2a, apcore-cli) SHOULD provide handlers that leverage their protocol's interaction capabilities:

Bridge Handler Mechanism
apcore-mcp ElicitationApprovalHandler Uses MCP Elicitation protocol to show confirmation dialog in MCP clients
apcore-a2a A2AApprovalHandler Uses A2A protocol interaction to request confirmation from calling agent
apcore-cli CliApprovalHandler Uses interactive terminal prompt to request confirmation from user

These handlers are not part of the apcore core specification — they are provided by the respective bridge packages.

7.8 Phased Implementation

Phase A: Synchronous Approval (Required)

  • request_approval() blocks until a decision is reached or timeout occurs.
  • Suitable for interactive scenarios (MCP client dialogs, agent-to-agent confirmation).
  • All conformant implementations MUST support Phase A.

Phase B: Asynchronous Approval (Optional)

  • request_approval() may return status: "pending" with an approval_id.
  • Client retries the tool call with _approval_token in arguments.
  • check_approval_for_call(approval_id, request) checks the current invocation and consumes an approved credential.
  • Suitable for long-running approval workflows (Slack, email, dashboard).
  • Phase B is optional but recommended for production deployments.

7.9 Execution Policy

An Execution Policy is a declarative, execution-time governance layer that overrides a module's governance annotations (requires_approval, destructive) independent of how the module was registered. It exists because "governed capabilities" is a platform-level promise: an operator must be able to gate already-registered modules without editing their code or re-registering them.

7.9.1 Attach Point and Precedence

  1. A policy MUST attach at the Executor and be consulted by the Approval Gate (Step 5, §7.4).
  2. A policy is a set of pattern rules. Each rule matches a module ID using the ACL wildcard semantics (Algorithm A08, §6.2) and carries optional overrides for requires_approval and destructive (each null/absent = "do not override"). Rule matching consults the module ID and nothing else; the call's arguments reach resolution but never a rule (§7.9.6).
  3. Rule selection MUST use ACL specificity scoring (Algorithm A10, §6.4): the most specific matching rule wins. On a specificity tie, the more restrictive rule wins (a rule that forces requires_approval = true outranks one that clears it).
  4. A matched rule's non-null override MUST take precedence over the module's own declared or scanned annotation. This is deliberate: external governance is the platform's word over the module author's.
  5. A policy decision MUST be recorded in the audit trail. When a policy changes a module's effective governance, the Executor MUST emit apcore.policy.override (§9.16.2) when an event emitter is configured.

7.9.2 destructive → approval resolution

The approval gate keys on the effective requires_approval. HTTP-method inference and scanners can set destructive = true independently of requires_approval.

  • When gate_destructive is true, a module whose effective destructive is true MUST be treated as needing approval even when requires_approval is false.
  • The built-in policy MUST default gate_destructive to true, including when the host supplies no policy. An explicit gate_destructive = false disables this source of approval while preserving requirements from module annotations, ACL rules, and policy rules. An implementation SHOULD warn when a destructive module is exposed without approval or ACL coverage (see §7.9.4).

7.9.3 Effective annotations to the handler

When the gate invokes the handler because a policy forced approval, the ApprovalRequest.annotations handed to the handler MUST carry the effective governance values (requires_approval = true, destructive = the effective value), not the module's raw declaration. This preserves the §7.3 contract that "requires_approval is guaranteed true" in a handler-visible ApprovalRequest.

7.9.4 Fail loud, not silent (security principle)

A misconfigured or unreachable governance control MUST NOT silently allow. Concretely:

  1. The built-in policy MUST default strict to true. When a call needs approval and has no handler, the gate MUST raise ApprovalDeniedError (APPROVAL_DENIED). Given explicit strict = false, it MUST emit a warning at least once per module and continue.
  2. A destructive module that no approval gate covers SHOULD produce a warning (at least once per module).
  3. A strict-fail-closed rejection MUST emit apcore.approval.decision (status rejected) like any other adjudication.
  4. An implementation that loads a policy from YAML or JSON MUST reject unknown keys and rules missing pattern. Omitted policy booleans MUST take the built-in defaults, and explicit boolean values MUST be preserved.

The implicit warn-and-continue behavior from earlier protocol versions is deprecated. During migration an application can select strict = false, gate_destructive = false explicitly to retain that behavior. An application that requires approval can provide an ApprovalHandler. Explicit strategies that omit the built-in approval gate remain visible in the governance posture report (§6.6.5).

7.9.5 Preflight

Executor.validate() (§12.2) MUST report the governance-effective requires_approval — the union of §6.9 rows 3–5 for the given call site, which includes an ACL rule carrying approval (§6.1.6). Reporting only the policy-effective value would tell a caller no approval is needed for a call the gate will stop. That union is by construction the same verdict the gate will enforce, including a gate_destructive-driven or rule-forced approval. The apcore.acl.denied and governance decision events MUST NOT be emitted during a dry-run validate().

7.9.6 Call-site inputs to policy resolution

Policy resolution receives the call site — what the module is being called with — as well as which module is being called. Governance keyed on the module alone forces an operator to gate every call to a module in order to gate some of them, which produces audit noise and weakens requires_approval from "this needs approval" to "this might". The pipeline holds the data at the point of the decision — the gate is Step 5, and the invocation's arguments and Context are in scope there — so this section makes them an input to resolution without introducing a declarative predicate over them.

  1. Policy resolution MUST receive the call site: the invocation arguments and the Context, alongside the module ID and annotations.
  2. The built-in pattern rules of §7.9.1 MUST NOT consult the call site. A rule set's verdict MUST be a function of the module ID and the annotations alone, so that it stays statically auditable and reproducible from the policy document.
  3. The call site exists so that an implementation can carry it into the audit trail and the apcore.policy.override event (§9.16.2). What an implementation records MUST be the call site's shape — which keys were present, their types — and MUST NOT be argument values, since rule 4 places this before schema validation and an argument may hold anything, including a secret. This specification defines no policy interface for a host to implement: ExecutionPolicy is a concrete type, and making it pluggable is deliberately not specified.
  4. The arguments handed to policy resolution have NOT been schema-validated: the approval gate is Step 5 and input validation is Step 7 (§12.8). An implementation MUST document this, and MUST NOT assume the call site is well-formed, present, or of the declared type.
  5. The framework-owned approval token (_approval_token, §7.4) MUST be stripped from arguments before policy resolution. §7.4's requirement to remove it "before passing to subsequent steps" does not reach this case on its own: policy resolution happens inside Step 5, ahead of any subsequent step. It is a protocol-level key, not caller input; leaving it in place puts a token into the audit trail and the apcore.policy.override payload.
  6. Adding the call site MUST NOT change the verdict any existing policy produces.
  7. What is required is the capability, not one API shape. An implementation MUST provide an explicit, backward-compatible entry point for call-site-aware resolution, and MUST leave the pre-existing entry point's verdicts unchanged. The form is language-idiomatic and deliberately unconstrained: an added method (resolve_with_call_site), keyword-only parameters, or an options object are all conforming. Forcing one shape on three languages would violate API Surface & Naming Conventions §4, which fixes the noun across SDKs and lets the idiom differ. The constraint is real in one direction: because rule 6 forbids the new inputs from changing any verdict, widening a published signature buys nothing and costs every external caller a compile error, so a language without default arguments or overloading SHOULD add a method rather than widen.

A declarative argument predicate on PolicyRule is deliberately not specified here

ACL rules discriminate on caller, target, identity type, roles, call depth and argument keys (§6.1, §6.1.7); policy rules on module ID alone. Adding an argument predicate to PolicyRule would grow a second condition language over the same decision point. If one is specified, it is to be designed jointly with ACL conditions.

7.10 Conformance

The tiers below grade the approval subsystem alone. They are not the SDK conformance levels of Conformance: there, Tiers 1–2 are part of Level 1 (Approval gate (Phase A), MUST) and Tiers 3–4 are part of Level 2 (Approval Phase B and Execution Policy, SHOULD).

Tier Requirement
Tier 1 (Basic) ApprovalHandler protocol defined. The default gate raises APPROVAL_DENIED when a call needs approval and lacks a handler.
Tier 2 (Standard) Step 5 implemented in call(), call_async(), and stream() paths; AlwaysDenyHandler and AutoApproveHandler provided
Tier 3 (Full) Phase B support (check_approval_for_call, _approval_token); CallbackApprovalHandler provided; approval audit events emitted
Tier 4 (Governance) Execution Policy (§7.9): external override + specificity precedence, gate_destructive, strict fail-closed, effective-annotations contract, and the apcore.approval.decision / apcore.policy.override / apcore.acl.denied events

8. Error Handling Specification

8.1 Unified Error Format

All errors must follow unified format:

error_format:
  type: object
  required: [code, message]
  properties:
    code:
      type: string
      description: "Error code (format: CATEGORY_SPECIFIC_ERROR)"
    message:
      type: string
      description: "Human-readable error message"
    details:
      type: object
      description: "Error details (optional)"
    cause:
      type: object
      description: "Original error (optional, for error chains)"
    trace_id:
      type: string
      description: "Trace ID"
    timestamp:
      type: string
      format: datetime
    retryable:
      type: [boolean, "null"]
      description: "Whether the error is retryable (see §8.6 for defaults per error code)"
    ai_guidance:
      type: [string, "null"]
      description: "Machine-readable hint for AI agents on how to handle this error"
    user_fixable:
      type: [boolean, "null"]
      description: "Whether the end-user can fix the root cause without developer intervention"
    suggestion:
      type: [string, "null"]
      description: "Actionable suggestion for resolving the error"

details keys. Every key of details is snake_case in the serialized error of every implementation (module_id, caller_id, timeout_ms), whatever name the host language uses for the field in memory (D-149).

Schema validation details. A SCHEMA_VALIDATION_ERROR carries details.errors, a list with one item per failed check. Each item is an object with exactly three keys (D-149):

Key Value
path A JSON Pointer (RFC 6901) to the failing value within the validated instance — /count, /tags/1; the empty string "" for the instance root
keyword The JSON Schema keyword that failed at path — type, required, minimum, enum, … A missing required property is reported at the object that lacks it, with keyword required
message A human-readable description of the failure

8.1.1 AI Error Guidance Fields

The four optional fields (retryable, ai_guidance, user_fixable, suggestion) enable AI agents to programmatically understand and respond to errors without parsing human-readable messages.

These fields are the foundation of apcore's Self-Healing mechanism, which serves two higher-level goals:

  • Self-Repair: The Agent autonomously corrects errors and retries within a single interaction.
  • Self-Evolution: The system continuously adapts through health monitoring, event-driven feedback loops, and runtime reconfiguration (see §9.11 Hot-Reload, §10 Observability).

Field semantics:

Field Type Purpose
retryable boolean \| null Whether retrying the same call may succeed. Each error code has a default value (see §8.6). Callers may override. null means "depends on context".
ai_guidance string \| null Machine-readable guidance for AI agents, e.g. "validate input schema before retry", "check module registry for available alternatives".
user_fixable boolean \| null Whether the end-user (non-developer) can resolve the issue, e.g. fixing a typo in input vs. a server misconfiguration.
suggestion string \| null Human-readable actionable suggestion, e.g. "Check that the table name contains only lowercase letters and underscores".

Serialization rules:

  • Implementations MUST use sparse serialization: fields with null values SHOULD be omitted from the serialized output.
  • retryable defaults to the value specified in §8.6 for each error code. Callers may explicitly override this default.
  • ai_guidance, user_fixable, and suggestion default to null (omitted).

Example with AI guidance fields:

{
  "code": "SCHEMA_VALIDATION_ERROR",
  "message": "Input validation failed",
  "details": {
    "errors": [
      { "path": "/table", "keyword": "pattern", "message": "Table name does not match the required pattern" }
    ]
  },
  "retryable": false,
  "user_fixable": true,
  "suggestion": "Use 'user_info' as the table name.",
  "ai_guidance": "validate input against schema before retry; this error will recur with the same input"
}

8.2 Framework Error Codes

http_status is descriptive, not a required SDK surface

Each entry below carries an http_status. It is a suggested mapping for an integration that places an executor behind HTTP — a gateway, an apcore-a2a-* server — and implementations are NOT required to expose it. The MUST in §7.5 and here is define the following error types; the status is metadata about each type, in the same way description is.

Conformance fixtures therefore do not assert http_status. 499 (an nginx extension) and 508 (WebDAV) are practical choices for a gateway author, which is a further reason the mapping is guidance rather than a contract every implementation must reproduce.

error_codes:
  # Configuration-related (CONFIG_*)
  CONFIG_NOT_FOUND:
    description: "Configuration file not found"
    http_status: 500
  CONFIG_INVALID:
    description: "Invalid configuration file"
    http_status: 500
  CONFIG_BIND_ERROR:
    description: "Binding a configuration namespace to a typed model failed"
    http_status: 500
  CONFIG_MOUNT_ERROR:
    description: "Invalid Config Bus mount operation (§9.7)"
    http_status: 500
  CONFIG_NAMESPACE_DUPLICATE:
    description: "A configuration namespace is registered twice (§9.5)"
    http_status: 500
  CONFIG_NAMESPACE_RESERVED:
    description: "A reserved namespace name or env prefix is registered by another package (§9.8.2)"
    http_status: 500
  CONFIG_ENV_PREFIX_CONFLICT:
    description: "An env_prefix is already registered by another namespace (§9.8.2)"
    http_status: 500
  CONFIG_ENV_MAP_CONFLICT:
    description: "An environment variable is already mapped by an env_map (§9.8.3)"
    http_status: 500

  # Module-related (MODULE_*)
  MODULE_NOT_FOUND:
    description: "Module doesn't exist"
    http_status: 404
  MODULE_LOAD_ERROR:
    description: "Module load failed"
    http_status: 500
  MODULE_EXECUTE_ERROR:
    description: "Module execution error"
    http_status: 500
  MODULE_TIMEOUT:
    description: "Module execution timeout"
    http_status: 504
  MODULE_DISABLED:
    description: "Module is disabled via system.control.toggle_feature"
    http_status: 403
  INVALID_MODULE_ID:
    description: "module_id is empty or fails the Module ID Format Constraint (§2.1)"
    http_status: 400
  MODULE_ID_CONFLICT:
    description: "Multi-class discovery derived the same ID for two classes in one file (§2.1.1)"
    http_status: 500
  MODULE_RELOAD_CONFLICT:
    description: "system.control.reload_module received both module_id and path_filter"
    http_status: 400
  DUPLICATE_MODULE_ID:
    description: "A module ID that is already registered was registered again (§12.7.4)"
    http_status: 409
  ID_TOO_LONG:
    description: "A derived module ID exceeds the 192-character maximum (§2.7)"
    http_status: 500
  INVALID_SEGMENT:
    description: "A derived multi-class segment does not match the Canonical ID grammar (§2.1.1)"
    http_status: 500
  STREAMING_INTERFACE_MISMATCH:
    description: "A module declares streaming support but its stream() method does not satisfy the streaming interface"
    http_status: 500

  # Context-related
  CONTEXT_BINDING_ERROR:
    description: "An Executor tried to bind a Context already bound to a different Executor"
    http_status: 500

  # Circuit breaker
  CIRCUIT_BREAKER_OPEN:
    description: "CircuitBreakerMiddleware rejected the call because the circuit is open"
    http_status: 503

  # Execution-related (EXECUTION_*)
  EXECUTION_CANCELLED:
    description: "Module execution cancelled via CancelToken"
    http_status: 499

  # Reload-related (RELOAD_*)
  RELOAD_FAILED:
    description: "Module hot-reload failed"
    http_status: 500

  # Schema-related (SCHEMA_*)
  SCHEMA_NOT_FOUND:
    description: "Schema doesn't exist"
    http_status: 404
  SCHEMA_VALIDATION_ERROR:
    description: "Schema validation failed"
    http_status: 400
  SCHEMA_PARSE_ERROR:
    description: "Schema parse error"
    http_status: 500
  SCHEMA_CIRCULAR_REF:
    description: "Schema circular reference detected — a $ref → $ref chain that never reaches a schema body (§4.15)"
    http_status: 500
  SCHEMA_MAX_DEPTH_EXCEEDED:
    description: "$ref resolution exceeded schema.max_ref_depth. Distinct from SCHEMA_CIRCULAR_REF: the chain is well-formed but too deep (§4.11, §4.15)"
    http_status: 500
  SCHEMA_UNION_NO_MATCH:
    description: "Value matched no branch of a oneOf/anyOf union"
    http_status: 400
  SCHEMA_UNION_AMBIGUOUS:
    description: "Value matched more than one branch of a oneOf union, which MUST be exclusive"
    http_status: 400

  # Permission-related (ACL_*)
  ACL_DENIED:
    description: "Permission denied"
    http_status: 403
  ACL_RULE_ERROR:
    description: "ACL rule error"
    http_status: 500

  # Function module-related (FUNC_*)
  FUNC_MISSING_TYPE_HINT:
    description: "Function parameter missing type annotation"
    http_status: 500
  FUNC_MISSING_RETURN_TYPE:
    description: "Function missing return type annotation"
    http_status: 500

  # Binding-related (BINDING_*)
  BINDING_INVALID_TARGET:
    description: "Binding target format invalid"
    http_status: 500
  BINDING_MODULE_NOT_FOUND:
    description: "Binding target module path can't be imported"
    http_status: 500
  BINDING_CALLABLE_NOT_FOUND:
    description: "Binding target callable not found"
    http_status: 500
  BINDING_NOT_CALLABLE:
    description: "Binding target not callable"
    http_status: 500
  BINDING_SCHEMA_INFERENCE_FAILED:
    description: "Auto-schema inference failed: callable lacks usable type hints"
    http_status: 500
    # Deprecated alias: BINDING_SCHEMA_MISSING — serialized payloads carrying it remain decodable.
  BINDING_SCHEMA_MODE_CONFLICT:
    description: "Binding entry sets fields of more than one schema source (§5.12.2)"
    http_status: 500
  BINDING_STRICT_SCHEMA_INCOMPATIBLE:
    description: "auto_schema is strict and an inferred schema fails the strict-mode check (§5.12.5)"
    http_status: 500
  BINDING_FILE_INVALID:
    description: "Binding file parse error"
    http_status: 500

  # Middleware-related (MIDDLEWARE_*)
  MIDDLEWARE_CHAIN_ERROR:
    description: "Middleware chain execution failed"
    http_status: 500

  # Pipeline-related (PIPELINE_*, STEP_*, STRATEGY_*)
  PIPELINE_CONFIGURATION_ERROR:
    description: "Pipeline configuration names a step or anchor that does not exist, or sets a field the step does not accept (§5.16.1)"
    http_status: 500
  PIPELINE_ABORT:
    description: "A pipeline step aborted the pipeline"
    http_status: 500
  PIPELINE_STEP_ERROR:
    description: "A pipeline step failed; wraps the step's error (§5.16 requirement 1)"
    http_status: 500
  PIPELINE_DEPENDENCY_ERROR:
    description: "A step's requires is not satisfied by the provides of the steps before it"
    http_status: 500
  PIPELINE_STEP_NOT_FOUND:
    description: "configure_step() named a step the strategy does not contain"
    http_status: 500
  STEP_NOT_FOUND:
    description: "A strategy API call (remove, insert_after, insert_before) named a step the strategy does not contain"
    http_status: 500
  STEP_NAME_DUPLICATE:
    description: "Two steps of one strategy carry the same name"
    http_status: 500
  STEP_NOT_REMOVABLE:
    description: "remove() named a step the strategy marks non-removable"
    http_status: 500
  STEP_NOT_REPLACEABLE:
    description: "replace() named a step the strategy marks non-replaceable"
    http_status: 500
  STRATEGY_NOT_FOUND:
    description: "A pipeline strategy preset name does not exist (§6.6.3.2)"
    http_status: 500

  # System modules (SYS_*)
  SYS_MODULES_DISABLED:
    description: "An operation that needs the system modules was called while sys_modules.enabled is false"
    http_status: 500
  SYS_MODULE_REGISTRATION_FAILED:
    description: "A system.* module failed to register at startup"
    http_status: 500

  # Async tasks (TASK_*, REAPER_*)
  TASK_LIMIT_EXCEEDED:
    description: "AsyncTaskManager task ceiling reached"
    http_status: 429
  TASK_STORE_UNAVAILABLE:
    description: "A TaskStore backend is unreachable or refused an operation"
    http_status: 503
  REAPER_ALREADY_RUNNING:
    description: "start_reaper() was called while a reaper is already running"
    http_status: 500

  # Version-related (VERSION_*)
  VERSION_INCOMPATIBLE:
    description: "SDK/config version incompatible"
    http_status: 500
  VERSION_CONSTRAINT_INVALID:
    description: "A dependency version constraint string is malformed (§5.3)"
    http_status: 500

  # Error code registry (ERROR_CODE_*)
  ERROR_CODE_COLLISION:
    description: "Custom error code collides with framework or other module code"
    http_status: 500
  ERROR_FORMATTER_DUPLICATE:
    description: "An error formatter is already registered for the adapter name"
    http_status: 500

  # Trace context
  INVALID_PARENT_ID:
    description: "TraceContext.inject received a parent_id override that is not 16 lowercase hex characters"
    http_status: 400

  # Dependency-related (CIRCULAR_*, DEPENDENCY_*)
  CIRCULAR_DEPENDENCY:
    description: "Module dependency cycle detected"
    http_status: 500
  DEPENDENCY_NOT_FOUND:
    description: "Dependent module doesn't exist"
    http_status: 500
  DEPENDENCY_VERSION_MISMATCH:
    description: "Dependent module exists but its registered version does not satisfy the declared version constraint"
    http_status: 500

  # General errors (GENERAL_*)
  GENERAL_INVALID_INPUT:
    description: "Invalid input"
    http_status: 400
  GENERAL_INTERNAL_ERROR:
    description: "Internal error"
    http_status: 500
  GENERAL_NOT_IMPLEMENTED:
    description: "Feature not implemented"
    http_status: 501

  # Call chain-related (CALL_*)
  CALL_DEPTH_EXCEEDED:
    description: "Call chain depth exceeded limit"
    http_status: 508
  CIRCULAR_CALL:
    description: "Circular call detected"
    http_status: 508
  CALL_FREQUENCY_EXCEEDED:
    description: "Same module call frequency exceeded limit"
    http_status: 508

  CALL_BUDGET_EXCEEDED:
    description: "Call-tree count or cost limit exceeded (§7.4.2)"
    http_status: 429

  # Approval-related (APPROVAL_*)
  APPROVAL_DENIED:
    description: "Approval was explicitly rejected"
    http_status: 403
  APPROVAL_TIMEOUT:
    description: "Approval request timed out without response"
    http_status: 408
  APPROVAL_PENDING:
    description: "Approval is pending, retry with _approval_token"
    http_status: 202
  POLICY_DENIED:
    description: "The installed policy denied the validated invocation"
    http_status: 403
  POLICY_EVALUATION_ERROR:
    description: "The installed policy could not evaluate the invocation safely"
    http_status: 503

8.3 Error Propagation

Implementations MUST propagate errors according to the following algorithm:

Algorithm: propagate_error(error, module_id, context)

Input:
  error     — Original exception/error object
  module_id — Module ID where error occurred
  context   — Current execution context

Output:
  module_error — Standardized ModuleError object

Steps:
  1. If error is already ModuleError type:
     a. Keep original error.code
     b. Append current module_id to error.chain
     c. Return error
  2. Construct module_error:
     a. code ← Map based on error type:
        - SchemaValidationError → "SCHEMA_VALIDATION_ERROR"
        - ACLDeniedError → "ACL_DENIED"
        - TimeoutError → "MODULE_TIMEOUT"
        - Other → "MODULE_EXECUTE_ERROR"
     b. message ← Human-readable message from error
     c. details ← Extract structured details from error
     d. cause ← error (keep original error)
     e. trace_id ← context.trace_id
     f. module_id ← module_id
     g. call_chain ← Copy of context.call_chain
     h. timestamp ← Current UTC time (ISO 8601)
  3. Return module_error
error_propagation:
  # Module errors
  module_error:
    - "Module-thrown errors **MUST** be wrapped as ModuleError"
    - "Original error **MUST** be saved in cause field"
    - "Error code prefixed with MODULE_"

  # Error context
  context:
    - "Error **MUST** contain trace_id"
    - "Error **SHOULD** contain occurrence location (module_id)"
    - "**MUST** support error chain tracing"

8.4 Custom Error Codes

Modules can define their own error codes:

custom_error_codes:
  # Naming convention
  naming:
    pattern: "{MODULE_PREFIX}_{ERROR_NAME}"
    module_prefix: "Last part of module ID in uppercase"
    examples:
      - module_id: "executor.validator.db_params"
        prefix: "DB_PARAMS"
        error_codes:
          - "DB_PARAMS_INVALID_TABLE"
          - "DB_PARAMS_SQL_INJECTION"

  # Declare in Schema
  declaration:
    location: "error_schema.codes"
    example:
      error_schema:
        codes:
          DB_PARAMS_INVALID_TABLE:
            description: "Invalid table name"
            http_status: 400
          DB_PARAMS_SQL_INJECTION:
            description: "SQL injection detected"
            http_status: 400

  # Error code registration
  registration:
    - "Framework startup **MUST** collect all module error codes"
    - "**MUST** detect error code conflicts"
    - "**SHOULD** generate error code documentation"

  # Framework error code priority
  priority:
    - "Framework error code prefixes **MUST** be reserved and modules **MUST NOT** use them. The canonical set is the fourteen listed in [features/error-system.md](../features/error-system.md) § Error Code Constants — `ACL_`, `APPROVAL_`, `BINDING_`, `CALL_`, `CIRCULAR_`, `CONFIG_`, `DEPENDENCY_`, `ERROR_CODE_`, `FUNC_`, `GENERAL_`, `MIDDLEWARE_`, `MODULE_`, `SCHEMA_`, `VERSION_` — the set each SDK exports as `FRAMEWORK_ERROR_CODE_PREFIXES`. A framework code outside these prefixes (`EXECUTION_CANCELLED`, `RELOAD_FAILED`, `INVALID_MODULE_ID`, the `PIPELINE_*` and `STEP_*` codes) is reserved as an exact code by the `framework_codes` check below, not by its prefix."
    - "Module custom error codes **MUST NOT** conflict with framework error codes"

  # Collision detection algorithm
  collision_detection: |
    Algorithm: detect_error_code_collisions(framework_codes, module_codes_map)

    Steps:
      1. all_codes ← Copy of framework_codes
      2. For each (module_id, codes) ∈ module_codes_map:
         For each code ∈ codes:
           a. If code ∈ framework_codes → Throw error: Module can't use framework reserved codes
           b. If code ∈ all_codes → Throw error: Error code already registered by other module
           c. all_codes ← all_codes ∪ {code}
      3. Return all_codes (complete error code registry)

8.5 Error Response Format

# Standard error response
error_response:
  code: "DB_PARAMS_INVALID_TABLE"
  message: "Invalid table name format"
  details:
    field: "table"
    value: "User-Info"
    expected: "Only lowercase letters and underscores allowed"
  trace_id: "4bf92f3577b34da6a3ce929d0e0e4736"
  timestamp: "2026-02-05T10:30:00Z"
  cause: null  # Or nested error object
  retryable: false
  user_fixable: true
  suggestion: "Table names must use only lowercase letters and underscores. Change 'User-Info' to 'user_info'."
  # ai_guidance: omitted (null) — sparse serialization

8.6 Retry Semantics

Implementations MUST NOT default retry failed module invocations. Retry behavior MUST be explicitly controlled by caller_id or middleware.

Retryability Classification:

Error Code Retryable Description
MODULE_TIMEOUT Yes Timeout may be temporary
GENERAL_INTERNAL_ERROR Yes Internal error may be transient
APPROVAL_TIMEOUT Yes Approval handler may respond on retry
CIRCUIT_BREAKER_OPEN Yes The circuit closes again after its recovery window
MODULE_EXECUTE_ERROR Depends Depends on module's annotations.idempotent
CONFIG_NOT_FOUND No Configuration file missing, needs deployment fix
CONFIG_INVALID No Configuration content invalid, needs manual fix
ACL_RULE_ERROR No ACL rule definition error, needs config fix
ACL_DENIED No Permission insufficiency won't change with retry
APPROVAL_DENIED No Explicit denial, retry won't change decision
APPROVAL_PENDING No Async approval in progress, use polling instead
POLICY_DENIED No Policy denied the validated invocation
POLICY_EVALUATION_ERROR Yes Policy evaluation could not complete safely
MODULE_NOT_FOUND No Module non-existence won't change with retry
MODULE_DISABLED No Module explicitly disabled, needs re-enabling
MODULE_LOAD_ERROR No Load errors typically need code fixes
EXECUTION_CANCELLED Yes Cancellation may be temporary; retry with a fresh CancelToken, since the cancelled one stays cancelled
RELOAD_FAILED Yes Reload may succeed after transient issue resolves
SCHEMA_VALIDATION_ERROR No Input error won't change with retry
SCHEMA_NOT_FOUND No Schema reference missing, needs config fix
SCHEMA_PARSE_ERROR No Schema syntax error, needs manual fix
SCHEMA_CIRCULAR_REF No Circular reference in schema, needs manual fix
SCHEMA_MAX_DEPTH_EXCEEDED No Reference chain too deep, needs schema or config fix
SCHEMA_UNION_NO_MATCH No Input error won't change with retry
SCHEMA_UNION_AMBIGUOUS No Input error won't change with retry
CALL_DEPTH_EXCEEDED No Call chain structure issue, retry won't change
CIRCULAR_CALL No Call chain structure issue, retry won't change
CALL_FREQUENCY_EXCEEDED No Call chain structure issue, retry won't change
CALL_BUDGET_EXCEEDED No The shared call or cost limit has been reached
GENERAL_INVALID_INPUT No Invalid input, caller_id must fix before retry
FUNC_MISSING_TYPE_HINT No Code-level issue, needs developer fix
FUNC_MISSING_RETURN_TYPE No Code-level issue, needs developer fix
BINDING_INVALID_TARGET No Binding format error, needs config fix
BINDING_MODULE_NOT_FOUND No Binding target module missing, needs config fix
BINDING_CALLABLE_NOT_FOUND No Binding target callable missing, needs code fix
BINDING_NOT_CALLABLE No Binding target not callable, needs code fix
BINDING_SCHEMA_INFERENCE_FAILED No Schema could not be inferred for binding, needs code or binding fix
BINDING_SCHEMA_MODE_CONFLICT No Binding declares conflicting schema sources, needs config fix
BINDING_STRICT_SCHEMA_INCOMPATIBLE No Inferred schema not strict-compatible, needs code fix
BINDING_FILE_INVALID No Binding file parse error, needs config fix
CIRCULAR_DEPENDENCY No Module dependency cycle, needs architecture fix
MIDDLEWARE_CHAIN_ERROR No Middleware failed, needs code fix
VERSION_INCOMPATIBLE No Version mismatch, needs upgrade or config fix
ERROR_CODE_COLLISION No Error code conflict, needs code fix
PIPELINE_CONFIGURATION_ERROR No Pipeline configuration invalid, needs config fix

Implementations SHOULD use this table as the default retryable value for each error subclass. Callers may override the default on a per-instance basis.

Module timeouts and retries. When MODULE_TIMEOUT is raised by a module call, implementations MUST set retryable from the module's annotations.idempotent: true only when the module declares that repeating the call produces no additional side effects, false otherwise. The table default still applies to timeouts raised without module context (for example a pipeline step budget). A non-idempotent call that timed out may already have applied side effects, so retrying it is not safe by default.

For EXECUTION_CANCELLED, APPROVAL_TIMEOUT, CIRCUIT_BREAKER_OPEN and PIPELINE_CONFIGURATION_ERROR the default is a MUST: an error of one of these codes constructed without an explicit retryable MUST carry the value in the table above — true for the first three, false for PIPELINE_CONFIGURATION_ERROR — and MUST NOT leave it unset (D-135). Retry middleware still never retries a cancelled call on its own: a cancellation does not reach the on_error chain.

Note: GENERAL_NOT_IMPLEMENTED and DEPENDENCY_NOT_FOUND are defined in §8.2 and appear in the §8.7 hierarchy. Both are non-retryable by default.

Retry middleware (if implemented) SHOULD: - Only retry errors marked as retryable - Only auto-retry modules with annotations.idempotent == true - Use exponential backoff strategy - Set max retry count limit (SHOULD not exceed 5 times)

8.7 Error Hierarchy

All framework errors MUST extend from a single ModuleError base class using a flat hierarchy. Implementations use a flat hierarchy under ModuleError for simplicity.

ModuleError (base error for all framework errors)
├── ConfigError                    # CONFIG_INVALID — Invalid configuration file
├── ConfigNotFoundError            # CONFIG_NOT_FOUND — Configuration file not found
├── ModuleNotFoundError            # MODULE_NOT_FOUND — Module doesn't exist
├── ModuleLoadError                # MODULE_LOAD_ERROR — Module load failed
├── ModuleExecuteError             # MODULE_EXECUTE_ERROR — Module execution error
├── ModuleTimeoutError             # MODULE_TIMEOUT — Module execution timeout
├── ModuleDisabledError            # MODULE_DISABLED — Module is disabled
├── ExecutionCancelledError        # EXECUTION_CANCELLED — Execution cancelled via CancelToken
├── ReloadFailedError              # RELOAD_FAILED — Module hot-reload failed
├── SchemaNotFoundError            # SCHEMA_NOT_FOUND — Schema doesn't exist
├── SchemaValidationError          # SCHEMA_VALIDATION_ERROR — Schema validation failed
├── SchemaParseError               # SCHEMA_PARSE_ERROR — Schema parse error
├── SchemaCircularRefError         # SCHEMA_CIRCULAR_REF — Schema circular reference
├── SchemaMaxDepthExceededError    # SCHEMA_MAX_DEPTH_EXCEEDED — $ref chain exceeded max_ref_depth
├── ACLDeniedError                 # ACL_DENIED — Permission denied
├── ACLRuleError                   # ACL_RULE_ERROR — ACL rule error
├── FuncMissingTypeHintError       # FUNC_MISSING_TYPE_HINT — Function parameter missing type annotation
├── FuncMissingReturnTypeError     # FUNC_MISSING_RETURN_TYPE — Function missing return type annotation
├── BindingInvalidTargetError      # BINDING_INVALID_TARGET — target format invalid
├── BindingModuleNotFoundError     # BINDING_MODULE_NOT_FOUND — Module path can't be imported
├── BindingCallableNotFoundError   # BINDING_CALLABLE_NOT_FOUND — Can't find target callable
├── BindingNotCallableError        # BINDING_NOT_CALLABLE — Target not callable
├── BindingSchemaInferenceFailedError   # BINDING_SCHEMA_INFERENCE_FAILED — Schema could not be inferred (alias: BindingSchemaMissingError)
├── BindingSchemaModeConflictError      # BINDING_SCHEMA_MODE_CONFLICT — Conflicting schema sources
├── BindingStrictSchemaIncompatibleError # BINDING_STRICT_SCHEMA_INCOMPATIBLE — Inferred schema not strict-compatible
├── BindingFileInvalidError        # BINDING_FILE_INVALID — Binding file parse error
├── CircularDependencyError        # CIRCULAR_DEPENDENCY — Circular dependency
├── DependencyNotFoundError        # DEPENDENCY_NOT_FOUND — Dependent module doesn't exist
├── CallDepthExceededError         # CALL_DEPTH_EXCEEDED — Call depth exceeded limit
├── CircularCallError              # CIRCULAR_CALL — Circular call
├── CallFrequencyExceededError     # CALL_FREQUENCY_EXCEEDED — Call frequency exceeded limit
├── MiddlewareChainError           # MIDDLEWARE_CHAIN_ERROR — Middleware chain execution failed
├── ApprovalError                  # Base class for approval errors (§7)
│   ├── ApprovalDeniedError        # APPROVAL_DENIED — Approval explicitly rejected
│   ├── ApprovalTimeoutError       # APPROVAL_TIMEOUT — Approval timed out
│   └── ApprovalPendingError       # APPROVAL_PENDING — Approval pending (Phase B)
├── InvalidInputError              # GENERAL_INVALID_INPUT — Invalid input
├── InternalError                  # GENERAL_INTERNAL_ERROR — Internal error
├── NotImplementedError            # GENERAL_NOT_IMPLEMENTED — Feature not implemented
├── VersionIncompatibleError       # VERSION_INCOMPATIBLE — SDK/config version incompatible
└── ErrorCodeCollisionError        # ERROR_CODE_COLLISION — Error code collision detected

Each error class carries a code attribute set to the corresponding error code string (e.g., MODULE_NOT_FOUND). Implementations MUST ensure all framework-thrown errors are instances of ModuleError. Module custom errors SHOULD also extend ModuleError directly.

8.8 Error Formatter Registry

apcore-mcp and apcore-a2a each independently implement an ErrorMapper that translates ModuleError into their protocol-specific format (MCP camelCase JSON, A2A JSON-RPC codes). The Error Formatter Registry provides a shared registration point so this translation contract is visible to the framework, without requiring apcore to know protocol details.

Scope: apcore provides the interface and fallback only. Protocol-specific formatters are owned by each adapter package. Adoption is SHOULD-level for ecosystem adapters.

8.8.1 ErrorFormatter Protocol

protocol ErrorFormatter:
    format(error: ModuleError, context: Context) → dict
    # Returns a protocol-specific error representation.
    # MUST NOT raise — return best-effort dict on internal failure.

8.8.2 Registration API

ErrorFormatterRegistry is a class exported from the apcore package:

from apcore import ErrorFormatterRegistry
ErrorFormatterRegistry.register(
    adapter_name: string,        # MUST — unique adapter id (e.g., "mcp", "a2a", "cli")
    formatter:    ErrorFormatter  # MUST — implements ErrorFormatter protocol
)

Registration rules: 1. adapter_name MUST be unique. Registering the same name twice MUST raise ERROR_FORMATTER_DUPLICATE. 2. Registration SHOULD happen at adapter initialization, before any module calls are processed. 3. The registry is global and shared across all Executor instances.

8.8.3 Lookup Algorithm

Algorithm: format_error(error, adapter_name, context)

Steps:
  1. formatter ← ErrorFormatterRegistry.get(adapter_name)
  2. If formatter is nil:
       → Serialize via error.to_dict() (§8.5 standard format)
  3. Return formatter.format(error, context)

The framework guarantees a result — callers MUST NOT handle exceptions from format_error.

8.8.4 Ecosystem Adoption

Ecosystem adapters SHOULD register their formatter at initialization:

Adapter adapter_name Responsibility
apcore-mcp mcp snake_case → camelCase, ACL masking, AI guidance mapping
apcore-a2a a2a JSON-RPC code mapping (-32601/-32602/-32603), truncation
apcore-cli cli Terminal-friendly formatting, exit code derivation

apcore itself does not ship these formatters. Each adapter package owns its implementation.

8.8.5 New Error Code

Error Code Trigger
ERROR_FORMATTER_DUPLICATE register() called twice for the same adapter_name

9. Configuration Specification

9.1 Framework Configuration

apcore.yaml is the core configuration file of the framework. Implementations MUST validate configuration files according to the following JSON Schema.

What is required, and why so little is. A key is required only when it has no canonical default — that is, only when omitting it leaves a value the framework cannot supply. By that rule exactly two keys are required: version and project.name. Every other key in this section either carries a default in schemas/defaults.schema.json (extensions.*, schema.*, acl.*, executor.*, sys_modules.*, observability.*, stream.*) or is optional outright, so requiring it would reject a configuration the framework can resolve perfectly well.

The MUST markers in the example below therefore mean "this key is normative and its default is fixed", not "the file is invalid without it". Only version and project.name make a file invalid by their absence — schemas/apcore-config.schema.json declares exactly those two in its required array.

Requiredness is evaluated against the declared document, before defaults are merged. A required-field check run after the default table has been merged can never fail, because the merge has already supplied every key.

What "declared" means. The declared document is everything supplied by someone — the configuration file, environment-variable overrides (§9.2), runtime set(), and mount() — and excludes exactly one thing: the framework's own default table. Implementations MUST expose this view (Config.get_declared() / getDeclared() / Config.declared) and MUST use it for the required-field check.

Environment overrides count as declaration. APCORE_PROJECT_NAME=my-app against a file that omits project.name MUST satisfy the requirement: the operator has supplied the value, and a container deployment that configures entirely through the environment is a first-class case, not a degraded one. Only the default table is excluded, because a default is the framework answering its own question.

apcore.yaml Complete JSON Schema Definition:

Keys marked No effect are declared and accepted but read by no implementation; keys marked Deprecated are additionally scheduled for removal (§9.2.4).

# apcore.yaml — Complete configuration structure and constraints

$schema: "https://apcore.dev/config/v1"   # Editor/validator hint — no effect at runtime
version: "1.0.0"                    # REQUIRED — no default exists

# Project information
project:
  name: "my-ai-project"             # REQUIRED — no default exists (pattern: ^[a-z][a-z0-9_-]*$)
  version: "0.1.0"                   # SHOULD use semver. Reported by system.health.summary.

# Extension configuration
extensions:
  root: "./extensions"               # MUST (default: "./extensions")
  auto_discover: true                # Deprecated, no effect — see §9.2.4
  lazy_load: true                    # MAY, lazy loading (default: true). No effect — read by no implementation
  follow_symlinks: false             # MUST NOT default true (default: false)
  max_depth: 8                       # SHOULD, max scan depth (default: 8, max: 16)
  ignore_patterns:                   # MAY, additional ignore patterns
    - "*.test.*"
    - "*.spec.*"

# Schema configuration — these three keys are the whole namespace (§4.9);
# `defaults.schema.json` declares it additionalProperties: false. Strictness and
# type coercion are NOT configurable: they are properties of the contract, not
# of the host (§4.9, TYPE_MAPPING §17.3).
schema:
  root: "./schemas"                  # MUST (default: "./schemas")
  strategy: "yaml_first"             # SHOULD, loading strategy (yaml_first|native_first|yaml_only)
  max_ref_depth: 32                  # MAY, $ref max recursion depth (default: 32)

# ACL configuration
acl:
  root: "./acl"                      # MUST (default: "./acl")
  default_effect: "deny"             # MUST (default: deny) — deny|allow. Deprecated, no effect — see §9.2.4
  audit:
    enabled: true                    # SHOULD, audit logging (default: true). Deprecated, no effect — see §9.2.4
    log_level: "info"                # MAY, audit log level. Deprecated, no effect — see §9.2.4
    include_denied: true             # SHOULD, log denied calls. Deprecated, no effect — see §9.2.4

# Logging configuration
logging:
  level: "info"                      # SHOULD (trace|debug|info|warn|error|fatal). Deprecated, no effect — see §9.2.4
  format: "json"                     # SHOULD (json|text, default: json). Deprecated, no effect — see §9.2.4

# Observability configuration
observability:
  tracing:
    enabled: true                    # SHOULD (default: false — opt in)
    sampling_rate: 1.0               # MAY (0.0-1.0, default: 1.0)
    exporter: "stdout"               # MAY (stdout|otlp|jaeger)
  metrics:
    enabled: true                    # MAY (default: false — opt in). Deprecated, no effect — see §9.2.4
    exporter: "stdout"               # MAY (stdout|prometheus|otlp). Deprecated, no effect — see §9.2.4

# Middleware configuration
middleware:
  disabled: []                       # Deprecated, no effect — see §9.2.4

# Binding configuration
bindings:
  dir: "./bindings"                  # SHOULD, binding file directory (default: "./bindings")
  pattern: "*.binding.yaml"          # SHOULD, file matching pattern (default: "*.binding.yaml")

# ID Map configuration
id_map:
  auto_detect: true                  # SHOULD (default: true). No effect — read by no implementation
  overrides: null                    # MAY, path to an ID map file applied during discovery (§2.2)

9.1.1 Default Values Summary

Implementations MUST follow these default value conventions:

Configuration Item Default Value Valid Range Description
extensions.root "./extensions" Valid directory path Extension root directory
extensions.max_depth 8 1..16 Scan depth limit
schema.root "./schemas" Valid directory path Schema root directory
schema.max_ref_depth 32 1..100 $ref resolution depth limit
acl.root "./acl" Valid directory path ACL file root directory
acl.default_effect "deny" allow/deny Default behavior when no rule matches. Deprecated, no effect — the ACL file's default_effect (§6.1) is the one read; see §9.2.4
executor.default_timeout 30000 (ms) 0..600000 Per-module execution timeout (0 means no limit)
executor.global_timeout 60000 (ms) 0..600000 Global execution timeout across entire call chain (0 means no limit)
executor.max_call_depth 32 1..1000 Call chain max depth
executor.max_module_repeat 3 1..100 Max occurrences of same module in call chain
observability.tracing.enabled false true/false Distributed tracing switch
observability.tracing.sampling_rate 1.0 0.0..1.0 Trace sampling rate — consulted only by the proportional and error_first strategies
observability.tracing.strategy "full" full/proportional/error_first/off How the sampling decision is made (§10.7)
observability.tracing.exporter "stdout" stdout/otlp/jaeger Tracing exporter (§10.1.1). jaeger names no implementation in any SDK and is deprecated for removal at v2.0
observability.tracing.otlp_endpoint null URL, or null OTLP collector endpoint (§10.1.1). Read only when exporter is otlp; setting it with any other exporter is a load-time error
observability.metrics.enabled false true/false Metrics collection switch. Deprecated, no effect — see §9.2.4
observability.metrics.exporter "stdout" stdout/prometheus/otlp Metrics exporter. Deprecated, no effect — see §9.2.4
bindings.dir "./bindings" Valid directory path Binding file directory
bindings.pattern "*.binding.yaml" glob-dialect pattern (A25, §9.2.3) Binding file matching pattern, matched against the filename within bindings.dir
id_map.auto_detect true true/false Auto ID mapping detection. No effect — read by no implementation; an ID map, when one is configured, is always applied

Note: - Configuration values exceeding ranges MUST be rejected in validate_config() (algorithm A12) - Implementations use a dual-timeout model: default_timeout applies to each individual module execution, while global_timeout applies to the entire call chain from root invocation. If either timeout is exceeded, a MODULE_TIMEOUT error is raised. - timeout = 0 means disable that timeout, implementations SHOULD log WARN - max_call_depth and max_module_repeat used for call chain safety checks (algorithm A20)

9.1.2 Declarative Validation Limits (validation.*)

apcore does not impose limits on the content its users write. It offers them.

The validation.* keys are the six constraints an operator may switch on for a project. Every one of them is unconstrained by default, and every one is configurable. The specification recommends values; it does not enforce them.

Key Default Applies to Recommendation
validation.binding.description_max_length null — no limit a module's description 200 for a description an LLM ranks modules by; 500 where the surface tolerates it
validation.binding.documentation_max_length null — no limit a module's documentation 5000
validation.binding.tags_pattern null — no constraint each entry of a binding's tags "^[a-z][a-z0-9_]*$", which keeps a tag legible on every surface
validation.binding.version_require_semver false a binding's version true for a project that publishes bindings
validation.pipeline.step_name_max_length null — no limit a pipeline step's name 64
validation.pipeline.timeout_ms_max null — no limit a pipeline step's timeout_ms 300000

Scope. validation.* carries policy on authored content only. Technical limits are not validation.* keys and are not configurable: the canonical ID grammar and its 192-character maximum (§2.7), and the surface alias constraints of the display overlay (§5.13) — for example the 64-character maximum on display.mcp.alias — are fixed by this specification and the canonical schemas.

Example — a project opting in to every recommended limit. Omitting the validation: section, or leaving a key at its default, checks nothing.

# apcore.yaml
validation:
  binding:
    description_max_length: 200          # null (default) = no limit
    documentation_max_length: 5000       # null (default) = no limit
    tags_pattern: "^[a-z][a-z0-9_]*$"    # null (default) = no constraint
    version_require_semver: true         # false (default) = no constraint
  pipeline:
    step_name_max_length: 64             # null (default) = no limit
    timeout_ms_max: 300000               # null (default) = no bound

validation is a top-level framework section, like executor or bindings, declared as $defs/ValidationConfig in schemas/apcore-config.schema.json; in namespace mode (§9.6.1) it sits inside the apcore: section with the rest of the framework keys.

Requirements:

  1. A key set to null (or, for version_require_semver, false) imposes no check. The value is not validated, and an implementation MUST NOT substitute a limit of its own. This is the default for all six.
  2. A key set to a value MUST be enforced, and a violation MUST be reported as a validation error naming the key, the offending value's length or content, and the configured limit. An implementation MUST NOT downgrade an operator-configured limit to a warning: the operator asked for a limit, and a limit that only warns enforces nothing.
  3. A limit is checked where the value enters the system, never at call time. A constraint on authored content belongs at the moment the content is read, and the key namespace says where that is:
  4. validation.binding.* — in the binding loader, against each BindingEntry. schemas/binding.schema.json gives an entry exactly these four fields (description, documentation, tags, version), so the four keys map onto it one for one.
  5. validation.pipeline.* — when the pipeline: section is parsed, against each declared step.

A failing entry MUST be rejected with the binding-file or pipeline-configuration error the surrounding section already defines (BINDING_FILE_INVALID for a binding entry, PIPELINE_CONFIGURATION_ERROR for a pipeline step), naming the offending field. These keys add a check, not a new error taxonomy. 4. Limits count characters, not bytes. A description of 200 CJK characters is 200, not 600. 5. tags_pattern is a regex-dialect value (§9.2.3): an unanchored, case-sensitive search by the host engine, inside the portable subset of §9.2.3 requirement 6c. An operator who means "the whole tag" writes ^…$, exactly as the recommended value does. A pattern that does not compile is reported, never skipped (§9.2.3 requirement 6d). 6. version_require_semver names one grammar. A version satisfies it when it matches

^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$

which is the grammar from semver.org, unmodified. 1.0 does not satisfy it: the patch component is required. The grammar is written as a literal because naming a format without pinning it lets each implementation choose its own.

Rationale for the defaults. A limit that is right for one project's LLM-ranked module catalogue is wrong for another's internal tooling, so the recommendations above carry the design intent — a description an LLM ranks modules by wants to be short — and the operator decides whether to enforce it. tags_pattern and version_require_semver default to off because enforcing them by default would reject tags and versions that are otherwise valid, such as capitalised or hyphenated tags.

Interaction with §4.8. §4.8's advisory guidance stands: a long description is not recommended, and an implementation MAY warn about one independently of these keys. What it MUST NOT do is reject, unless description_max_length is configured.

9.1.3 A Declared Key MUST Reach Its Mechanism From a Config

A key declared in the canonical schemas MUST reach the mechanism it names from a Config. A facility reachable only through a direct constructor or function argument MUST NOT carry a key in the canonical schemas.

Rationale: a key that only an argument can satisfy is accepted, validated and documented, and does nothing when an operator sets it — while the mechanism itself works, so the defect is invisible from inside the implementation (D-73).

Requirements:

  1. What counts as a configuration entry point. Three, equally: a Config produced by a file load, one carrying an environment override (§9.2), and one constructed programmatically (Config({…}), set()). A value reaching the mechanism from any of them satisfies this section. What does not satisfy it is a direct argument that bypasses Config entirely — Registry(id_map_path=…), build_strategy_from_config(section, …), ACL(default_effect=…). Those arguments remain legitimate; what they cannot do is stand in for the key.

  2. Precedence. An explicit API argument wins over Config, which wins over the declared default. The order is fixed here so that a key with both doors wired resolves identically in every implementation: a caller passing the argument keeps its behaviour, and the key is the fallback.

  3. A key in the wrong file is the same defect. A key declared in apcore.yaml whose mechanism reads its value from a different file does nothing when written in apcore.yaml. The remedy is to keep the declaration in the file that is read and to withdraw the other: acl.default_effect and acl.audit.* in apcore.yaml are withdrawn in favour of the ACL file's default_effect (§6.1) and audit: block (§6.3.2, §9.2.4.1) — see §9.2.4.

Conformance. conformance/check_config_key_consumers.py enforces requirement 1: a key recorded live carries a behavioural probe that puts the key into a Config and observes an effect outside it. A probe that reaches the behaviour through a direct argument proves the behaviour exists, not that the key reaches it, and does not count. Requirement 2 is pinned per key by the precedence case each wiring fixture carries.

9.2 Environment Variable Override

Implementations MUST support overriding configuration file values through environment variables.

Override Rules:

Priority Source Example
1 (Highest) Environment variable APCORE_EXTENSIONS_ROOT=./ext
2 Configuration file extensions.root: "./extensions"
3 (Lowest) Default value "./extensions"

Environment Variable Naming Convention:

APCORE_{SECTION}_{KEY}

Rules:
  1. Prefix APCORE_ (uppercase)
  2. Nested levels separated by a single _
  3. An underscore inside a key name is written as a double __
  4. All letters uppercase
  5. Hyphens converted to underscores

Examples:
  extensions.root               → APCORE_EXTENSIONS_ROOT
  schema.max_ref_depth          → APCORE_SCHEMA_MAX__REF__DEPTH
  executor.default_timeout      → APCORE_EXECUTOR_DEFAULT__TIMEOUT
  executor.max_call_depth       → APCORE_EXECUTOR_MAX__CALL__DEPTH
  observability.tracing.enabled → APCORE_OBSERVABILITY_TRACING_ENABLED

9.2.1 Path-Typed Configuration Keys

A path-typed key is a configuration key whose value is a filesystem path. The set is closed and is declared by the canonical schemas: a property carrying "x-apcore-path": true in schemas/apcore-config.schema.json, or in a namespace schema it references (schemas/sys-modules.schema.json), is path-typed, and no other key is.

Key Environment variable Default
extensions.root APCORE_EXTENSIONS_ROOT "./extensions"
extensions.roots[] (string form) and extensions.roots[].root — (list-valued; see note) —
schema.root APCORE_SCHEMA_ROOT "./schemas"
acl.root APCORE_ACL_ROOT "./acl"
bindings.dir APCORE_BINDINGS_DIR "./bindings"
id_map.overrides APCORE_ID__MAP_OVERRIDES null (no ID map)
sys_modules.control.overrides_path APCORE_SYS_CONTROL_OVERRIDES__PATH null (no overrides file)

id_map.overrides and sys_modules.control.overrides_path are path-typed (D-138).

Requirements:

  1. Implementations MUST expose this set through a public, readable accessor (a constant, function, or equivalent) so that a consumer can ask which configuration values are paths without hardcoding the answer.
  2. A key added to §9.1 whose value is a filesystem path MUST carry the x-apcore-path marker in the same change that adds it. A path-valued key without the marker is a specification defect, not an implicit exclusion.
  3. extensions.roots is list-valued: every element is path-typed, in both the bare-string form and the { root, namespace } form. §9.2's scalar environment-override convention does not apply to it; an implementation MUST NOT invent a delimiter-separated APCORE_EXTENSIONS_ROOTS encoding.
  4. bindings.pattern is NOT path-typed. It is a glob-dialect pattern (A25, §9.2.3) matched against filenames within bindings.dir and is never resolved as a path in its own right. It is pattern-valued instead, and §9.2.3 declares that set the same way this section declares this one. id_map.overrides holds the path of an ID map file (§2.2); the module-ID overrides live inside that file.
  5. An empty string is not a path. When a path-typed key resolves to "" — most commonly because an APCORE_* variable is set but empty, which §9.2 still treats as an override — implementations MUST NOT use it as a directory. The empty value MUST be discarded and resolution MUST fall through to the next tier, exactly as if the variable had been unset. An implementation MAY log a warning naming the key.

    Rationale: export APCORE_ACL_ROOT= and a variable inherited empty from a container spec are both "set", so without this rule an empty string would replace a directory the configuration file declared and then resolve, relative to the working directory, to the working directory itself — a legal path, but never the one an operator meant.

Why the set is declared rather than inferred. A consumer that forwards apcore configuration across a process boundary — a CLI spawning a worker, a supervisor building a container environment — has to know which APCORE_* variables carry paths, because a relative path that crosses a boundary where the working directory changes silently re-roots. With no declared set, each such consumer maintains its own by hand and drifts from the others; the marker moves that answer to the one place that already defines the key surface.

What this section does not decide. It declares which keys carry paths. It does not define what a relative value in one of them is resolved against; that is §9.2.2's subject.

9.2.2 Path Resolution Base

Every Config MUST capture one absolute project root at construction or load. Implementations MUST expose it through a public, readable accessor.

How the configuration was selected Project root
An explicit path passed to the loader, or $APCORE_CONFIG_FILE (discovery tier 1) The directory of the selected file entry, including when it has the same path as a user-level configuration
A project-local configuration (discovery tiers 2–5) The directory of the selected file entry
A user-level configuration (discovery tiers 6–7) The process working directory at load
No file found, defaults, or an in-memory mapping The process working directory at load or construction

A configuration-file symlink MUST use the directory containing the selected entry as its base. Implementations MUST keep the captured root for the lifetime of that Config, including when reloading its source. Subsequent changes to the process working directory MUST NOT change the root or the meaning of a relative path in that configuration.

  1. Resolve value precedence first. Every relative path-typed value declared in §9.2.1 MUST be interpreted against the captured project root. This covers values supplied through the file, environment, API, defaults, and both supported forms of extensions.roots entries.
  2. Implementations MUST use an absolute path-typed value as supplied. Resolving a relative path MUST preserve the filesystem meaning of its path segments, including .. after a symbolic link. A missing value continues to use the precedence and fallback rules of its key, and an empty value follows §9.2.1.
  3. All consumers MUST use this rule, including filesystem checks during configuration validation. An implementation MAY resolve a path on read using the captured root, so the stored configuration can retain its original spelling. Implementations SHOULD expose the same resolver to callers handling values from a Config.
  4. This rule applies to values supplied by a Config. The contract of each consumer governs an explicit path argument passed directly to that consumer.

conformance/fixtures/config_project_root.json covers discovery tiers, explicit loading, path sources, and consumer behavior. See Config Bus for the SDK accessors.

Interaction with include: composition. If the proposed include: RFC is adopted, paths supplied by its merged configuration use this same project root.

9.2.3 Pattern-Valued Values

A pattern-valued value is a string that is matched against a name rather than used literally: a filename, a field name, an event type, a module ID. Every pattern-valued value names the algorithm that matches it. Host-language matchers — pathlib.Path.glob, fnmatch, the glob crate, RegExp, the regex crate — implement dialects that disagree with one another, so a value typed only as "glob" or "pattern" would have a different contract in each implementation. Naming an algorithm at every point of use, and closing the set of pattern-valued values, is what makes the contract portable, exactly as §9.2.1 does for path-typed keys.

Three dialects exist, and no fourth. Each pattern-valued property in the canonical schemas carries an "x-apcore-pattern" marker naming its dialect, the same way §9.2.1's path-typed keys carry "x-apcore-path".

Marker Algorithm Used for
"glob" A25 match_glob (below) filenames, field names, event types, path_filter
"regex" the host language's regular-expression engine, constrained by requirement 6 field values
"module-id" A08 match_pattern (§6.2) ACL rule patterns, match_modules
The closed set

A value not in this table is not pattern-valued. Adding one MUST add its row here and its x-apcore-pattern marker in the same change; a pattern-valued key without a marker is a specification defect, not an implicit exclusion.

Value Marker Matched against Case
bindings.pattern (§5.12.6) glob (A25) the filename of each entry directly in bindings.dir — never the path, never recursively sensitive
obs.redaction.sensitive_keys[] — entries containing * or ? (§10.6.1) glob (A25) the field name insensitive
obs.redaction.regex_patterns[] (§10.6.1) regex the field value, when it is a string — other values are never converted to a string to be tested insensitive
include_events[], exclude_events[], event_pattern (§9.16) glob (A25) the event type sensitive
system.control.reload_module → path_filter (§6.7) glob (A25) the module ID sensitive
ACL callers[] / targets[] (§6.2) module-id (A08) the module ID sensitive
pipeline / middleware match_modules[] (§5.16) module-id (A08) the module ID sensitive
extensions.ignore_patterns[] (§3.5) glob (A25) the entry name — one path segment, never the path sensitive

obs.redaction.sensitive_keys entries containing neither * nor ? are not patterns at all; they are substrings, matched by the separate rule in §10.6.1.

A value joins this table when an implementation consumes it, and its dialect is assigned in the same change. Assigning a dialect to a key that nothing reads would declare a contract nothing could be measured against.

extensions.ignore_patterns matches a narrow surface on purpose. A04 step 3a says entry name, so a pattern is matched against one path segment — node_modules, fixtures.py — and never against a path. * therefore cannot cross a directory boundary, because there is no boundary in the value being matched. Matching is case-sensitive, unlike sensitive_keys: these are filenames, and a protocol that folded them would make a configuration behave differently on a case-insensitive filesystem than on the case-sensitive one it was written against.

Algorithm A25 — match_glob
Algorithm: match_glob(pattern, value)

Input:
  pattern — a pattern-valued string
  value   — the name to test

Output:
  matched — boolean

Metacharacters — exactly two, and no others:
  *  matches zero or more characters, including "." and "/"
  ?  matches exactly one character

Every other character is a literal, INCLUDING  [  ]  {  }  \  !  ^  -
There is no escape character: to match a literal "*" or "?" is not expressible,
and that is deliberate (see requirement 4).

Steps:
  1. Split pattern on "*" into segments s[0..n-1].
     A pattern with no "*" yields exactly one segment.
  2. If n == 1:
       → Return match_exact(s[0], value)          # no "*": whole value must match
  3. If NOT match_prefix(s[0], value) → Return false
     pos ← len(s[0])
  4. For i in 1 .. n-2:                            # the interior segments
       found ← the LEFTMOST index j >= pos with match_exact(s[i], value[j : j+len(s[i])])
       If no such j → Return false
       pos ← found + len(s[i])
  5. last ← s[n-1]
     If last is empty → Return true                # pattern ended with "*"
     If len(value) - pos < len(last) → Return false
     → Return match_exact(last, value[len(value)-len(last) :])
  6. where:
       match_exact(seg, text)  ≡ len(seg) == len(text) AND match_prefix(seg, text)
       match_prefix(seg, text) ≡ len(text) >= len(seg) AND
                                 for every k in 0..len(seg)-1:
                                     seg[k] == "?"  OR  seg[k] == text[k]

Complexity: O(m x n), m = len(pattern), n = len(value)

Step 4 is leftmost-first, non-backtracking, which is the same greedy strategy A08 already specifies. It is stated as an algorithm rather than as a syntax because three implementations converge only when the procedure is fixed: two matchers can both claim "* and ?" and still disagree on a*a against aaa.

Requirements
  1. Implementations MUST match every glob-dialect value in the table above with A25. An implementation MUST NOT delegate to a host-library matcher whose dialect differs from A25 — fnmatch, pathlib.Path.glob, the glob crate and a translated RegExp all differ from it and from each other.
  2. Every string is a valid pattern. A25 has no parse phase and no error return. An implementation MUST NOT reject, warn about, or skip a pattern-valued value on syntactic grounds; a[b, {x,y} and ** are patterns whose bracket, brace and second star are literals. Rationale: a matcher that raises on an unbalanced [ would refuse a control-plane request that a conforming matcher serves.
  3. Case sensitivity is a property of the surface, not of the algorithm. A25 itself compares characters exactly. A surface marked insensitive in the table above MUST apply the same case fold to both the pattern and the value before calling A25. Folding only one side is a silent bypass: it makes a pattern spelled "*Token*" match nothing while "*token*" matches, with no diagnostic, on a redaction surface.
  4. [, ], {, } and \ are literals. Character classes are the construct the host libraries disagree about most — [!x] versus [^x] negation, POSIX classes, ranges — and they are the construct no real value in the table above needs. Excluding them removes the disagreement rather than adjudicating it. The cost is stated plainly: a literal * or ? in a name cannot be matched exactly. No value in the table has an alphabet that contains either character.
  5. A25 is not A08, and the two surfaces do not overlap. A08 (§6.2) matches ACL rule patterns and match_modules against module IDs; A25 matches everything else in the table. A08 treats ? as a literal, and since a module ID (§2.7) cannot contain ?, an ACL pattern containing one matches nothing; §6.2.2 requires such a pattern to be reported. Rationale: making ? a wildcard in A08 would turn a dead allow rule live, widening authorization without any change to the ACL file.
  6. Regex-dialect values. a. Matching is an unanchored search: a value matches when the pattern matches anywhere within it. An operator wanting a whole-value match writes ^…$. b. Matching is case-insensitive. c. Portable subset. A pattern SHOULD be expressible without lookaround, backreferences, or inline flag groups ((?i)). Those three are exactly where the engines disagree: the Rust regex crate refuses lookaround and backreferences by design, to keep matching linear in the input, and JavaScript rejects (?i). A pattern outside the subset is not portable, and a configuration that relies on one is not conformant across SDKs. d. A pattern that does not compile MUST NOT be discarded in silence. The implementation MUST emit a diagnostic naming the pattern and the engine's error, once per configuration load, and validate_config() (A12, §9.3) MUST report it as a validation error. Rationale: a skipped pattern is indistinguishable from a rule that is working, and on a redaction surface the consequence is plaintext credentials in a log.
What this section does not change

This section fixes the matching language, not the policy. It sets no default value, changes no key's meaning, and adds no pattern to any surface; each value's semantics are defined by the section its row cites.

9.2.4 Deprecated Configuration Keys

The keys below are declared in the canonical schemas, validated, accepted under _config.strict, and environment-overridable — and no implementation reads them, so setting one has no effect. They are deprecated and will be removed. This table is the authoritative list.

Key Declared Migrate to Removed
acl.default_effect §9.1.1 The ACL file's default_effect (§6.1). An ACL's default effect comes from the ACL file (§9.1.3 requirement 3) Not before v2.0
acl.audit.enabled §9.1 The ACL file's audit.enabled (§6.3.2, §9.2.4.1) Not before v2.0
acl.audit.include_denied §9.1 The ACL file's audit.include_denied (§6.3.2, §9.2.4.1) Not before v2.0
acl.audit.log_level §9.1 The ACL file's audit.log_level (§6.3.2, §9.2.4.1) Not before v2.0
logging.level §9.1 No replacement key (D-67). apcore does not own the host's logging policy — see below Not before v2.0
logging.format §9.1 No replacement key (D-67) — as above Not before v2.0
observability.metrics.enabled §9.1.1 No replacement key. Metrics come from a MetricsCollector supplied to the API Not before v2.0
observability.metrics.exporter §9.1.1 No replacement key. There is no metrics-exporter abstraction; a MetricsCollector is supplied as a constructor argument Not before v2.0
middleware.disabled §9.1 No replacement key. Remove a registered middleware with remove(), or a pipeline step with pipeline.remove (§5.16.1). The built-in middleware it names are not installed (§11.4) (D-137) Not before v2.0
extensions.auto_discover §9.1 No replacement key. Discovery runs when discover() is called; the key is read only by §9.3's semantic-validation warning (D-150) Not before v2.0

Requirements:

  1. When a loaded configuration document declares any key in the table above, implementations MUST emit a deprecation warning naming every such key present. The table is the whole list: a key not in it MUST NOT produce this warning. Emit the warning once per configuration load. Each load evaluates the condition independently.
  2. The warning MUST be driven by the declared document, not the merged view. Every one of these keys has a default. Checking the declared document keeps the warning specific to configurations that actually set a deprecated key.
  3. Deprecation does not change behaviour. The keys parse, validate, appear in get(), and remain accepted under _config.strict. Nothing may start rejecting them in the 1.x line.
  4. Removal is not before v2.0, and not before the two-minor window §13.2 requires and §13.4 restates for remove_field. Until then a configuration that sets them stays valid.

Why a warning and not a deletion. Every key in the table is accepted under _config.strict: true. Deleting a declared key turns a currently-valid strict configuration into a rejected one, which is the migration §13.2 exists to schedule.

logging.level and logging.format are withdrawn with no replacement key (D-67). The reason is a boundary rather than an implementation cost: apcore does not own the host's logging policy. Wiring the keys would require either threading the two values through Context — the object every Context.logger() call builds a logger from, which carries no reference to a Config — or a process-global logger configuration. A global would end the isolation apcore has between two APCore instances in one process, since every Context.logger() returns a fresh instance.

Controlling apcore's log output. apcore's ContextLogger does not route through the host's logging framework: it writes structured lines directly to standard error (sys.stderr in Python, console.error in TypeScript, a stderr writer in Rust), so configuring the host language's logging API has no effect on apcore's output. The supported path is the API argument: construct a ContextLogger with the level, format and sink you want and hand it to the middleware that emits — ObsLoggingMiddleware(logger=…) in every SDK, whose precedence (the supplied logger, else a default) is the §9.1.3 requirement 2 contract.

Context.logger() is deprecated, and is not the answer to this

The path above covers the middleware. It does not cover Context.logger(), which constructs a default logger per access — output always stderr, info, JSON, in every SDK. Withdrawing logging.* makes §9.1.3's rule hold, because the keys stop naming a mechanism they cannot reach; it does not hand the host control of that path.

It is not given one. Context.logger() is deprecated and is removed at v2.0. Module code SHOULD log through the host application's own logger, which is the same boundary D-67 draws: level, format, sink, sampling and per-instance policy stay with the host. ObsLoggingMiddleware is not the migration target — it emits apcore's execution events, a different facility, and moving ad-hoc logging onto it would change record shape and volume.

9.2.4.1 The ACL file's audit: block

schemas/acl-config.schema.json declares an audit block at the root of an ACL policy file, with the same meaning as the deprecated acl.audit.* keys above. The ACL file's block is the declaration that is read (§6.3.2, decision D-66). acl.audit.* in apcore.yaml stays in §9.2.4's table with the ACL file's block named as its migration target, and is deleted at v2.0.

Rationale: the ACL loader already parses the document the block lives in, so the setting is read where it is written; reading acl.audit.* instead would require the apcore.yaml loader to reach into ACL construction.

  1. An ACL file carrying a root-level audit block MUST NOT produce a deprecation warning: the block has a delivery contract and is read (§6.3.2). A key that has a consumer is not announced as going away, for the same reason §9.2.4 requirement 1 says the table is the whole list. The notices that apply to the block are narrower and point the other way — §6.3.2 requirement 6's for include_denied: false, and requirement 1's for a block overridden by a callback.

§6.3.2 requirement 8 validates the audit subtree and nothing else. An ACL file is not validated against acl-config.schema.json as a whole, so every other unrecognised root key in an ACL file is ignored. This is not unknown-key closure for ACL files.

9.3 Configuration Validation Algorithm

Implementations MUST validate configuration at startup:

Algorithm: validate_config(config)

Input:
  config — Merged configuration object (env + file + defaults)

Output:
  validated_config — Validated configuration, or throw CONFIG_INVALID error

Steps:
  1. For each required field — `version` and `project.name`, the only two keys
     with no canonical default (§9.1):
     If missing from the DECLARED document (before the default table is merged)
       → Throw CONFIG_INVALID with the missing field path
     A key that carries a default in defaults.schema.json is NEVER required;
     checking it after merging defaults is a no-op and MUST NOT be relied on.
  2. Type validation:
     For each field, validate value type conforms to Schema definition
  3. Constraint validation:
     - extensions.root MUST be valid directory path
     - schema.root MUST be valid directory path
     - acl.default_effect MUST be "allow" or "deny"
     - observability.tracing.sampling_rate MUST be in [0.0, 1.0] range
     - extensions.max_depth MUST be in [1, 16] range
  4. Semantic validation:
     - If extensions.auto_discover == true and extensions.root doesn't exist → Warning
     - If schema.strategy == "yaml_only" and schema.root doesn't exist → Error
  5. Return validated_config

9.4 Config Bus Architecture

The apcore configuration system serves as a Config Bus — shared infrastructure that any package in the apcore ecosystem (or external packages) can register with, without being forced to adopt it.

9.4.1 Design Principles

Principle Description
Bus, not center apcore.Config does not own or mandate configuration; it provides registration, loading, validation, and access infrastructure. Packages that never call register_namespace are unaffected.
Zero-cost adoption Existing apcore.yaml files continue to work without modification. Namespace mode activates only when the file contains an apcore: top-level key.
Gradual integration Projects choose their integration depth: (1) apcore-only, (2) apcore + ecosystem packages, (3) apcore + third-party mount, (4) full unified file. Each level is independently valid.
Cross-language consistency All SDK implementations (Python, TypeScript, Rust) MUST implement the same namespace registration, loading, and validation semantics defined in this section.
Strict and flexible coexistence Strict mode enforces that every namespace is registered; flexible mode (default) passes through unknown namespaces with a warning. Both modes coexist within a single deployment.

9.4.2 Terminology

Term Definition
Namespace A top-level key in the unified configuration file (e.g., apcore, apflow, apcore-mcp). Each namespace is owned by exactly one package.
Schema A JSON Schema (Draft 2020-12) document that describes the structure, types, defaults, and constraints for a namespace's configuration.
Config Bus The Config class acting as shared infrastructure: it stores registered namespaces, loads configuration files, applies environment overrides per namespace, validates registered namespaces, and provides unified access.
Mount The act of attaching an external configuration source (file or dict) to a namespace in the Config Bus, without requiring a unified configuration file.
Legacy mode Backward-compatible behavior where the entire YAML file is treated as the apcore namespace. Activated when no apcore: top-level key is detected.
Namespace mode The file is partitioned by top-level keys, each representing a registered (or unregistered) namespace. Activated when an apcore: top-level key is present.

9.5 Namespace Registration

9.5.1 Registration API

All SDK implementations MUST expose a namespace registration method on the Config class (or its language-idiomatic equivalent).

Canonical signature (pseudocode):

Config.register_namespace(
    name:        string,                            # MUST — namespace identifier
    schema:      JSONSchema | path | nil,           # MAY  — validation schema
    env_prefix:  string | nil,                      # MAY  — env var prefix (nil = auto-derive from name)
    defaults:    map | nil,                          # MAY  — default values for this namespace
    env_style:   "nested" | "flat" | "auto" | nil,  # MAY  — env var key conversion strategy
    max_depth:   int | nil,                          # MAY  — max nesting depth for env conversion
    env_map:     map<string, string> | nil,          # MAY  — bare env var → config key mapping
)

Parameters:

Parameter Required Description
name MUST Namespace identifier. Pattern: ^[a-z][a-z0-9]*(-[a-z0-9]+)*$ (lowercase, hyphens allowed). Examples: apcore, apflow, apcore-mcp, my-billing.
schema MAY JSON Schema document (inline object or file path). When provided, the namespace section is validated against this schema during Config.validate(). When nil, the namespace is registered for isolation and env override only — no structural validation is performed.
env_prefix MAY Uppercase prefix for environment variable overrides (e.g., APFLOW). When nil, auto-derived from name via name.upper().replace("-", "_") (e.g., name="apcore-mcp" → env_prefix="APCORE_MCP"). When an explicit string, used as-is. Must match pattern: ^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$.
defaults MAY Default configuration values for this namespace. Merged before file data (lowest priority).
env_style MAY Controls how environment variable suffixes are converted to config keys. "auto" (default): matches the suffix against the defaults tree structure to determine the correct interpretation — flat keys match flat, nested paths match nested. When defaults is nil, falls back to "nested" behavior. "nested": single _ → . (section separator), double __ → literal _ — suitable for purely hierarchical config structures. "flat": no conversion, suffix is lowercased as-is — suitable for purely flat snake_case config keys where _ is part of the key name, not a hierarchy separator. When nil, defaults to "auto".
max_depth MAY Maximum nesting depth for environment variable key conversion. Applies to "nested" and "auto" styles; ignored for "flat". After reaching max_depth levels, remaining _ characters are preserved as literal underscores instead of being converted to . separators. Default: 5. Example: A_B_C_D_E_F_G with max_depth=5 → a.b.c.d.e_f_g (5 segments).
env_map MAY Explicit mapping of bare (unprefixed) environment variable names to config keys within this namespace. Each key is an exact env var name (e.g., "REDIS_URL"), each value is the target config key (e.g., "cache_url"). Only explicitly listed env vars are captured. Same priority as env_prefix overrides. An env var name MUST NOT appear in more than one env_map (global or namespace) — duplicates raise CONFIG_ENV_MAP_CONFLICT. When nil, no bare env var mapping is applied.

Registration rules:

  1. register_namespace MUST be callable before Config.load(). Implementations may also allow registration after load (see §9.5.3).
  2. Registering the same namespace name twice MUST raise CONFIG_NAMESPACE_DUPLICATE.
  3. The namespace apcore is implicitly registered by the framework itself. Attempting to register apcore externally MUST raise CONFIG_NAMESPACE_RESERVED.
  4. The reserved namespace _config MUST NOT be registerable. It is used for Config Bus meta-configuration (see §9.6.3). Attempting to register it MUST raise CONFIG_NAMESPACE_RESERVED.
  5. Namespace registration is permanent for the process lifetime. There is no unregister_namespace API in this version of the specification. This simplifies thread safety and avoids invalidation cascades across Config instances.

9.5.2 Cross-Language Registration Examples

Python:

from apcore import Config

# Nested style (default) — hierarchical config with _ → . conversion
Config.register_namespace(
    "apflow",
    schema="schemas/apflow.schema.json",
    env_prefix="APFLOW",
    defaults={"api": {"timeout": 30.0}},
)

# Flat style — flat snake_case config, no _ → . conversion
Config.register_namespace(
    "reach",
    env_prefix="REACHFORGE",
    env_style="flat",
    defaults={"devto_api_key": "", "llm_model": "gemini-pro"},
)

# Auto style — mixed flat keys + nested sections, resolved via defaults
Config.register_namespace(
    "myapp",
    env_prefix="MYAPP",
    env_style="auto",
    defaults={"devto_api_key": "", "publish": {"delay": 5, "retry": 3}},
)

TypeScript:

import { Config } from 'apcore-js/config';

// Nested style (default)
Config.registerNamespace({
  name: 'apflow',
  schema: 'schemas/apflow.schema.json',
  envPrefix: 'APFLOW',
  defaults: { api: { timeout: 30.0 } },
});

// Flat style
Config.registerNamespace({
  name: 'reach',
  envPrefix: 'REACHFORGE',
  envStyle: 'flat',
  defaults: { devto_api_key: '', llm_model: 'gemini-pro' },
});

// Auto style
Config.registerNamespace({
  name: 'myapp',
  envPrefix: 'MYAPP',
  envStyle: 'auto',
  defaults: { devto_api_key: '', publish: { delay: 5, retry: 3 } },
});

Rust:

use apcore::Config;

// Nested style (default)
Config::register_namespace(NamespaceRegistration {
    name: "apflow",
    schema: Some("schemas/apflow.schema.json".into()),
    env_prefix: Some("APFLOW"),
    defaults: Some(serde_json::json!({"api": {"timeout": 30.0}})),
    env_style: EnvStyle::Nested,
    max_depth: 5,
})?;

// Flat style
Config::register_namespace(NamespaceRegistration {
    name: "reach",
    env_prefix: Some("REACHFORGE"),
    env_style: EnvStyle::Flat,
    defaults: Some(serde_json::json!({"devto_api_key": "", "llm_model": "gemini-pro"})),
    schema: None,
    max_depth: 5,
})?;

// Auto style
Config::register_namespace(NamespaceRegistration {
    name: "myapp",
    env_prefix: Some("MYAPP"),
    env_style: EnvStyle::Auto,
    defaults: Some(serde_json::json!({"devto_api_key": "", "publish": {"delay": 5, "retry": 3}})),
    schema: None,
    max_depth: 5,
})?;

Java:

import dev.apcore.Config;

Config.registerNamespace(NamespaceRegistration.builder()
    .name("apflow")
    .schema("schemas/apflow.schema.json")
    .envPrefix("APFLOW")
    .defaults(Map.of("api", Map.of("timeout", 30.0)))
    .build());

9.5.3 Registration Lifecycle

Namespace registration is global (class-level), not per-instance. The registry of namespaces is shared across all Config instances within a process. This matches the real-world pattern: a package registers its namespace once at import time, and any Config instance can then load, validate, and serve that namespace's data.

┌──────────────────────────────────────────────────────────────────────────┐
│                      Config Bus Lifecycle                                │
│                                                                          │
│  Phase 1: Registration (global)   Phase 2: Loading       Phase 3: Usage │
│  ──────────────────────────────   ───────────────────    ─────────────── │
│                                                                          │
│  Config.register_namespace(...)   Config.load(path)      config.get(...) │
│  Config.register_namespace(...)   ├─ read global registry config.set(...)│
│  Config.register_namespace(...)   ├─ detect mode         config.mount()  │
│  ...                              ├─ parse YAML          config.reload() │
│                                   ├─ merge defaults      config.bind()   │
│                                   ├─ apply env overrides                 │
│                                   ├─ validate (A12-NS)                   │
│                                   └─ return Config instance              │
└──────────────────────────────────────────────────────────────────────────┘

Config instances are independent. Each Config.load() call returns a new instance with its own data tree and lock. Multiple Config instances may coexist (e.g., in tests), but they all share the same global namespace registry.

Late registration (calling register_namespace after one or more Config.load() calls) is permitted with these constraints:

  1. The namespace is added to the global registry immediately.
  2. Already-loaded Config instances are not retroactively modified. The new namespace takes effect on the next Config.load() or config.reload() call. This avoids surprising mutations to instances that callers may already be using.
  3. If the caller_id needs the new namespace to apply immediately to an existing instance, they MUST call config.reload() explicitly. The reload will pick up the newly registered namespace, apply its defaults and env overrides, and validate.
  4. Late registration MUST NOT invalidate previously loaded data in other namespaces.

9.6 Unified Configuration File

9.6.1 Mode Detection Algorithm

When Config.load(path) is called, implementations MUST detect the file mode:

Algorithm: detect_config_mode(parsed_yaml)

Input:
  parsed_yaml — Top-level mapping from the YAML file

Output:
  mode — "legacy" or "namespace"

Steps:
  1. If parsed_yaml contains a top-level key "apcore":
       → Return "namespace"
  2. Else:
       → Return "legacy"

Note — Detection rationale: This algorithm relies on the fact that apcore is not a valid top-level key in the legacy §9.1 schema (the legacy schema uses version, extensions, schema, acl, project, etc. — never apcore as a wrapper). A file that contains apcore: as a top-level key is unambiguously a namespace-mode file.

Consequence: A namespace-mode file that omits the apcore: section (e.g., contains only apflow: and apcore-mcp:) will be misdetected as legacy mode and fail validation. This is by design — the apcore: namespace section is required in namespace mode because it contains framework-critical fields (version, extensions.root, etc.). Users who want namespace mode without apcore core configuration should use apcore: with minimal required fields, or use the mount mechanism (§9.7) instead.

Legacy mode — the entire file is the apcore namespace (backward compatible with §9.1):

# apcore.yaml — legacy mode (no "apcore:" key)
version: "1.0.0"
extensions:
  root: ./extensions
executor:
  default_timeout: 5000

Namespace mode — each top-level key is a namespace:

# project.yaml — namespace mode ("apcore:" key present)
apcore:
  version: "1.0.0"
  extensions:
    root: ./extensions

apflow:
  api:
    server_url: http://localhost:8000

apcore-mcp:
  transport: streamable-http
  port: 8000

9.6.2 Merge Priority (Namespace Mode)

For each registered namespace, the merge priority (highest wins) is:

Priority Source Description
1 (Highest) Environment variables {ENV_PREFIX}_{SECTION}_{KEY}
2 Configuration file Namespace section from YAML
3 Mount data Data supplied via config.mount()
4 (Lowest) Registered defaults Defaults from register_namespace()

For the apcore namespace, legacy merge rules (§9.2) apply unchanged, using the APCORE_ prefix.

9.6.3 Config Bus Meta-Configuration

The reserved _config namespace controls Config Bus behavior itself. It MUST NOT be registerable by external packages.

_config:
  strict: false          # SHOULD, default: false
  allow_unknown: true    # SHOULD, default: true (only relevant when strict: false)
Field Type Default Description
strict boolean false When true: (a) every top-level key (except _config) MUST correspond to a registered namespace — unknown namespaces cause a ConfigError; and (b) every key inside a framework section of the apcore namespace MUST be declared by schemas/apcore-config.schema.json, which is additionalProperties: false for all of them. See the reject_unknown_framework_keys sub-algorithm in §9.10. Clause (b) applies in legacy mode too, where the whole file is the apcore namespace.
allow_unknown boolean true When strict is false and allow_unknown is true, unknown namespace data is stored and accessible via get() but not validated. When allow_unknown is false, unknown namespaces are silently ignored (not stored).

Behavior matrix:

strict allow_unknown Unknown namespace in YAML Result
true (ignored) billing: {db: ...} ConfigError: namespace billing not registered
false true billing: {db: ...} Stored, accessible, WARN logged, not validated
false false billing: {db: ...} Silently ignored, not stored

Requirements (D-69):

  1. Namespace mode only. This field governs namespaces, and a legacy document has none — its root is the apcore namespace, so an unrecognised top-level key there is a framework key governed by §9.10's walk under strict. strict's clause (b) says it "applies in legacy mode too"; clause (a), and this field with it, do not. An implementation MUST NOT drop a top-level key from a legacy document on the strength of allow_unknown.

  2. allow_unknown: false drops. When strict is false and allow_unknown is false, an unregistered top-level namespace MUST NOT be stored: get() answers as though the document never carried it. This applies only to a configuration that explicitly sets allow_unknown: false; the default is true.

  3. allow_unknown: true warns. The namespace is stored and readable, and the implementation MUST emit one diagnostic per configuration load naming every unregistered namespace it retained, stating that they are not validated. The presence of an unregistered namespace in the loaded document triggers the notice.

  4. An absent _config takes the defaults. The matrix describes the default pair (strict: false, allow_unknown: true), so a document that declares an unregistered namespace and no _config block at all is requirement 3's row. Reading an absent block as an exemption would make the documented default unreachable.

9.6.4 File Format Examples

Scenario 1 — Pure apcore (legacy, zero migration):

# apcore.yaml — legacy mode (no "apcore:" key)
version: "1.0.0"
extensions:
  root: ./extensions
schema:
  root: ./schemas
acl:
  root: ./acl                 # default_effect is set in the ACL file itself (§6.1)
project:
  name: my-project

Scenario 2 — apcore + ecosystem packages:

# project.yaml
apcore:
  version: "1.0.0"
  extensions:
    root: ./extensions
  schema:
    root: ./schemas
  acl:
    root: ./acl
  project:
    name: my-project

apflow:
  api:
    server_url: http://localhost:8000
    timeout: 30.0
  governance:
    default_policy: auto-downgrade
  durability:
    max_attempts: 3
    backoff_strategy: exponential

apcore-mcp:
  transport: streamable-http
  port: 8000
  auth:
    enabled: true

apcore-a2a:
  name: "My Agent"
  url: http://localhost:9000
  skills:
    - name: data-analysis
      module: executor.analyze

apcore-cli:
  theme: minimal
  output_format: json

Scenario 3 — Third-party project with mount (separate files):

# apcore.yaml — only apcore's own config
apcore:
  version: "1.0.0"
  extensions:
    root: ./extensions
  project:
    name: saas-platform
# Third-party project mounts its own config files
config = Config.load("apcore.yaml")
config.mount("billing", from_file="config/billing.yaml")
config.mount("notifications", from_file="config/notifications.yaml")

Scenario 4 — Strict mode for new projects:

# project.yaml
_config:
  strict: true

apcore:
  version: "1.0.0"
  extensions:
    root: ./extensions
  project:
    name: greenfield-app

apflow:
  api:
    server_url: http://localhost:8000

apcore-mcp:
  transport: streamable-http

Scenario 5 — Framework integration (Django, FastAPI):

# project.yaml — framework integration registers its own namespace automatically
apcore:
  version: "1.0.0"
  extensions:
    root: ./extensions
  project:
    name: django-app

django-apcore:
  auto_register_modules: true
  url_prefix: /api/apcore
  middleware:
    enabled: true

fastapi-apcore:
  auto_register_modules: true
  route_prefix: /apcore
  openapi:
    include: true

9.7 Mount Mechanism

The mount mechanism allows attaching external configuration sources to the Config Bus without requiring a unified configuration file. This is the primary integration path for third-party projects with existing configuration systems.

9.7.1 Mount API

Canonical signature (pseudocode):

config.mount(
    namespace:  string,           # MUST — target namespace
    from_file:  path | nil,       # MAY  — load from file
    from_dict:  map  | nil,       # MAY  — load from in-memory dict
)

Exactly one of from_file or from_dict MUST be provided.

Mount rules:

  1. The target namespace may or may not be previously registered via register_namespace.
  2. If registered: mount data is merged (file/dict < env overrides), then validated against the registered schema.
  3. If not registered: mount data is stored as-is, accessible via get(), but not validated. A WARN SHOULD be logged.
  4. Mounting to a namespace that already has data (from the unified file or a prior mount) MUST deep-merge the mount data into the existing data. Mount data has lower priority than file data (see §9.6.2). This means the unified file is the authoritative source when both exist. If the caller_id intends the mounted file to be the authoritative source for a namespace, the namespace section SHOULD NOT appear in the unified file.
  5. Mounting to the apcore namespace is permitted but SHOULD log a WARN (it overrides framework configuration).
  6. Mounting to _config MUST raise a CONFIG_MOUNT_ERROR.

9.7.2 Cross-Language Mount Examples

Python:

config = Config.load("apcore.yaml")

# Mount from file
config.mount("billing", from_file="config/billing.yaml")

# Mount from dict (e.g., loaded by a third-party library)
config.mount("notifications", from_dict={"provider": "ses", "region": "us-east-1"})

TypeScript:

const config = await Config.load('apcore.yaml');

config.mount('billing', { fromFile: 'config/billing.yaml' });
config.mount('notifications', { fromDict: { provider: 'ses', region: 'us-east-1' } });

Rust:

let mut config = Config::load("apcore.yaml")?;

config.mount("billing", MountSource::File("config/billing.yaml".into()))?;
config.mount("notifications", MountSource::Dict(serde_json::json!({
    "provider": "ses", "region": "us-east-1"
})))?;

Go:

cfg, _ := config.Load("apcore.yaml")

cfg.Mount("billing", config.FromFile("config/billing.yaml"))
cfg.Mount("notifications", config.FromDict(map[string]any{
    "provider": "ses", "region": "us-east-1",
}))

Java:

Config config = Config.load("apcore.yaml");

config.mount("billing", MountSource.fromFile("config/billing.yaml"));
config.mount("notifications", MountSource.fromDict(Map.of(
    "provider", "ses", "region", "us-east-1"
)));

9.7.3 Mount vs Unified File Decision Guide

Criterion Unified File Mount
New project, full apcore adoption Recommended —
Existing project adding apcore — Recommended
Config managed by external tool (Ansible, Terraform) — Recommended
Single-file deployment simplicity Recommended —
Team owns all config schemas Recommended —
Third-party config with unknown schema — Recommended

Both approaches produce the same namespace tree at runtime. The choice is purely organizational.

9.8 Environment Variable Override (Namespace Mode)

9.8.1 Per-Namespace Env Prefix

In namespace mode, each registered namespace with an env_prefix has its own environment variable scope.

Naming convention:

The env variable convention depends on the env_style setting of the namespace registration (see §9.5.1). The default style is "auto".

Nested style (env_style = "nested") — follows the same rules defined in §9.2:

{ENV_PREFIX}_{SECTION}_{KEY}

Rules:
  1. Prefix is the registered env_prefix (uppercase), followed by _
  2. Single _ → . (section separator), up to max_depth levels
  3. Double __ → literal _ (within key names)
  4. All letters uppercase
  5. After max_depth segments, remaining _ are preserved as literal _

Examples (namespace "apflow", env_prefix "APFLOW", env_style "nested"):
  APFLOW_API_SERVER__URL=http://...    → apflow.api.server_url
  APFLOW_API_TIMEOUT=60                → apflow.api.timeout
  APFLOW_GOVERNANCE_DEFAULT__POLICY=x  → apflow.governance.default_policy

Examples (namespace "apcore-mcp", env_prefix "APCORE_MCP", env_style "nested"):
  APCORE_MCP_TRANSPORT=stdio          → apcore-mcp.transport
  APCORE_MCP_PORT=9000                → apcore-mcp.port

Examples (namespace "apcore", env_prefix "APCORE" — unchanged from §9.2):
  APCORE_EXECUTOR_DEFAULT__TIMEOUT=5000 → apcore.executor.default_timeout

Flat style (env_style = "flat") — the suffix after the prefix is lowercased without any separator conversion. Underscores in the suffix are preserved as literal underscores in the config key. This is designed for namespaces whose config keys are flat snake_case identifiers (e.g., devto_api_key, llm_model) rather than hierarchical paths.

{ENV_PREFIX}_{KEY}

Rules:
  1. Prefix is the registered env_prefix (uppercase), followed by _
  2. Suffix is lowercased as-is (no _ → . conversion, no __ escaping needed)
  3. All letters uppercase in the env var

Examples (namespace "reach", env_prefix "REACHFORGE", env_style "flat"):
  REACHFORGE_DEVTO_API_KEY=abc123     → reach.devto_api_key
  REACHFORGE_LLM_MODEL=gemini-pro     → reach.llm_model
  REACHFORGE_PUBLISH_DELAY=5          → reach.publish_delay

Examples (namespace "myapp", env_prefix "MYAPP", env_style "flat"):
  MYAPP_DATABASE_URL=postgres://...    → myapp.database_url
  MYAPP_MAX_RETRIES=3                  → myapp.max_retries

Auto style (env_style = "auto") — resolves each env var suffix by matching against the registered defaults tree structure. This handles namespaces that mix flat snake_case keys with nested sub-sections, without requiring the user to escape underscores.

Algorithm: auto_resolve(suffix, defaults_tree, depth, max_depth)

  1. Try full suffix (lowercased) as a flat key in the current tree level.
     If found → return suffix (flat match).

  2. If depth >= max_depth → return suffix as flat key (depth limit).

  3. For each underscore position in suffix (left to right):
     Split into (prefix, remainder).
     If prefix exists in tree AND is a dict/map:
       Recurse: sub_key ← auto_resolve(remainder, tree[prefix], depth+1, max_depth)
       If sub_key is not nil → return prefix + "." + sub_key

  4. No match found → fall back to nested conversion (with max_depth).

Examples (namespace "reach", env_prefix "REACHFORGE", env_style "auto",
          defaults {"devto_api_key": "", "publish": {"delay": 5, "retry": 3}}):

  REACHFORGE_DEVTO_API_KEY=abc  → "devto_api_key" in defaults? Yes → reach.devto_api_key
  REACHFORGE_PUBLISH_DELAY=5    → "publish_delay" in defaults? No
                                → split "publish" + "delay"
                                → "publish" is dict? Yes → "delay" in it? Yes
                                → reach.publish.delay
  REACHFORGE_PUBLISH_RETRY=3    → same logic → reach.publish.retry
  REACHFORGE_NEW_UNKNOWN=x      → no match in defaults → nested fallback → reach.new.unknown

When to use each style: Use "nested" when your config is purely hierarchical (e.g., api.server.url, executor.default_timeout). Use "flat" when your config is a flat set of snake_case keys without any nesting (e.g., devto_api_key, llm_model). Use "auto" — the default — when your config mixes flat snake_case keys with nested sub-sections; it is the recommended style for most real-world applications. "auto" requires defaults to be provided for accurate resolution; keys not found in defaults fall back to "nested" behavior.

max_depth (default: 5) — limits the nesting depth for "nested" and "auto" styles. After max_depth segments are produced, remaining _ characters are preserved as literal underscores. This prevents excessively deep nesting from long env var names. Ignored for "flat" style.

Examples (max_depth=5):
  A_B_C_D_E=1       → a.b.c.d.e          (5 segments — within limit)
  A_B_C_D_E_F_G=1   → a.b.c.d.e_f_g      (5 segments — F_G kept as literal)
  A_B_C_D_E_F_G_H=1 → a.b.c.d.e_f_g_h    (5 segments — F_G_H kept as literal)

Type coercion follows the same rules as §9.2: "true"/"false" → boolean, numeric strings → int/float, otherwise string.

Note — apflow env var compatibility: apflow's own convention is a simpler one where dots become single underscores without the double-underscore escape (e.g., api.server_url → APFLOW_API_SERVER_URL). This works because apflow's config keys do not contain literal underscores. When migrating to the Config Bus, apflow SHOULD adopt the §9.2 convention (APFLOW_API_SERVER__URL) for consistency, but implementations may accept both forms during a transition period by attempting double-underscore parsing first and falling back to the simpler form.

9.8.2 Env Prefix Conflict Prevention

Env prefix conflicts arise when one registered prefix is a string prefix of another, making it ambiguous which namespace owns a given env var. The following rules prevent this:

  1. Each env_prefix MUST be unique across all registered namespaces. Attempting to register a duplicate env_prefix MUST raise CONFIG_ENV_PREFIX_CONFLICT.
  2. An env_prefix that begins with APCORE_ — APCORE_MCP, APCORE_OBSERVABILITY, APCORE_SYS — is permitted; a conflict is a duplicate (rule 1), not a shared leading string. Such a prefix and the apcore namespace's APCORE both match its variables, and implementations resolve that by longest-prefix match (dispatch algorithm below).
  3. The exact prefix APCORE is reserved for the apcore namespace. Attempting to register it for another namespace MUST raise CONFIG_NAMESPACE_RESERVED (D-146).
  4. An environment variable is dispatched to one namespace: the one whose prefix is the longest match. An APCORE_ variable that matches no registered prefix belongs to the apcore namespace and is read through §9.2's conversion. Implementations MUST NOT write one variable into two namespaces — a variable dispatched to a namespace whose prefix begins with APCORE_ is not also applied to the apcore namespace (D-146).

Resolving the APCORE / APCORE_MCP ambiguity:

A naive prefix scheme would make APCORE_MCP (for apcore-mcp) collide with APCORE_ (for apcore, key path mcp.*). The ecosystem convention resolves this by requiring apcore ecosystem packages to use a double-underscore separator between APCORE and the sub-package name in their env prefix:

Package Namespace Env Prefix Why safe
apcore apcore APCORE Base prefix
apcore-mcp apcore-mcp APCORE_MCP Longest-prefix match; no apcore key begins with mcp.
apcore-a2a apcore-a2a APCORE_A2A Longest-prefix match; no apcore key begins with a2a.
apcore-cli apcore-cli APCORE_CLI Longest-prefix match; no apcore key begins with cli.
apflow apflow APFLOW Completely disjoint prefix
django-apcore django-apcore DJANGO_APCORE No DJANGO namespace registered — no prefix collision

APCORE_MCP_TRANSPORT begins with both APCORE_ and APCORE_MCP_. Among registered prefixes the longer one wins, so the variable is dispatched to apcore-mcp as transport. Read through §9.2's conversion instead, the same variable names mcp.transport, which is no apcore key. A package prefix of the form APCORE_<X> is therefore safe exactly when no apcore key begins with <x>..

However, this convention introduces complexity. Implementations MUST use longest-prefix-match when dispatching env vars to namespaces:

Algorithm: dispatch_env_var(env_key, registered_prefixes)

Input:
  env_key             — Environment variable name (e.g., "APCORE_MCP_TRANSPORT")
  registered_prefixes — List of (env_prefix + "_", namespace_name) tuples,
                        sorted by prefix length descending

Output:
  (namespace_name, suffix) or nil

Steps:
  1. For each (prefix, ns_name) in registered_prefixes (longest first):
       If env_key starts with prefix:
         → Return (ns_name, env_key[len(prefix):])
  2. If env_key starts with "APCORE_":
       → Return ("apcore", env_key[len("APCORE_"):])   # §9.2 conversion applies
  3. Return nil (env var does not match any namespace)

Each env_key is dispatched once; the result names the only namespace it is written to (rule 4).

9.8.3 Env Override Application Algorithm

Algorithm: apply_namespace_env_overrides(config_data, registered_namespaces)

Input:
  config_data           — Merged configuration tree (all namespaces)
  registered_namespaces — Map of namespace name → registration info

Output:
  config_data with env overrides applied per namespace

Steps:
  0. Build prefix table (with auto-derive):
       registered_prefixes ← []
       For each (name, registration) in registered_namespaces:
         prefix ← registration.env_prefix
         If prefix is nil:
           prefix ← name.upper().replace("-", "_")     # auto-derive
         registered_prefixes.append((prefix + "_", name, registration))
       Sort registered_prefixes by prefix length descending (longest first)

  1. Build env_map lookup (global + per-namespace):
       global_env_map ← Config._global_env_map           # from Config.env_map()
       ns_env_maps ← {}                                   # env_var → (ns_name, config_key)
       For each (name, registration) in registered_namespaces:
         If registration.env_map is not nil:
           For each (env_var, config_key) in registration.env_map:
             ns_env_maps[env_var] ← (name, config_key)

  2. For each (env_key, env_value) in environment variables:
       coerced ← coerce_env_value(env_value)

       # 2a. Check global env_map (bare env var → top-level key)
       If env_key in global_env_map:
         config_data[global_env_map[env_key]] ← coerced
         continue

       # 2b. Check namespace env_map (bare env var → namespace key)
       If env_key in ns_env_maps:
         (ns_name, config_key) ← ns_env_maps[env_key]
         set config_data[ns_name][config_key] ← coerced
         continue

       # 2c. Prefix-based dispatch (dispatch_env_var, §9.8.2)
       match ← dispatch_env_var(env_key, registered_prefixes)
       If match is nil → skip
       (ns_name, suffix, registration) ← match
       max_depth ← registration.max_depth or 5
       If registration.env_style == "flat":
         key ← lowercase(suffix)
         set config_data[ns_name][key] ← coerced
       Else if registration.env_style == "auto":
         key ← auto_resolve(suffix, registration.defaults, 0, max_depth)
         set config_data[ns_name] via key (flat or nested depending on resolution)
       Else:  # "nested"
         dot_path ← convert suffix (single _ → ., double __ → _), lowercase,
                     stopping at max_depth segments
         set config_data[ns_name][dot_path] ← coerced (nested via set_nested)

  3. Return config_data

9.9 Namespace-Aware Access API

9.9.1 Unified Access

In namespace mode, get() and set() use dot-paths where the first segment is the namespace:

config.get("apcore.executor.default_timeout")   → 30000
config.get("apflow.api.timeout")                 → 30.0
config.get("apcore-mcp.transport")               → "streamable-http"
config.get("billing.db.host")                    → "localhost"

In legacy mode, get() behaves as before (no namespace prefix):

config.get("executor.default_timeout")           → 30000

Implementations MUST NOT break legacy mode access patterns. When the config is in legacy mode, get("executor.default_timeout") MUST continue to work without requiring an apcore. prefix.

Dot-path namespace resolution algorithm:

Because namespace names may contain hyphens (e.g., apcore-mcp), implementations MUST NOT naively split on the first . to extract the namespace. Instead:

Algorithm: resolve_namespace_path(dot_path, mode, known_namespaces)

Input:
  dot_path         — Full dot-path string (e.g., "apcore-mcp.transport")
  mode             — "legacy" or "namespace"
  known_namespaces — Set of registered + loaded namespace names

Output:
  (namespace, remainder) or (nil, dot_path) for legacy mode

Steps:
  1. If mode == "legacy":
       → Return (nil, dot_path)   // entire path is within apcore namespace

  2. Extract candidate ← substring before the first "."
     remainder ← substring after the first "."
     // candidate = "apcore-mcp", remainder = "transport"
     // Hyphens are legal in namespace names but NOT in config key segments,
     // so this split is unambiguous.

  3. If candidate is in known_namespaces:
       → Return (candidate, remainder)

  4. Else:
       → Return (candidate, remainder)
       // Unknown namespace — behavior depends on strict/allow_unknown settings.
       // The get() method should look up candidate as a top-level key in the
       // config data tree; if absent, return the provided default.

Why this is unambiguous: Namespace names allow hyphens (^[a-z][a-z0-9]*(-[a-z0-9]+)*$) but the §9.1 config keys within a namespace use underscores, not hyphens (e.g., default_timeout, max_depth). The first . is always the boundary between namespace and config path. A dot-path like apcore-mcp.transport can only mean namespace apcore-mcp, key transport — never namespace apcore, key mcp.transport (because apcore in namespace mode would require apcore.mcp.transport).

9.9.2 Namespace Accessor

Implementations SHOULD provide a convenience method to retrieve the entire configuration subtree for a namespace:

config.namespace("apflow")
→ {"api": {"server_url": "...", "timeout": 30.0}, "governance": {...}}

This returns a deep copy. Mutations to the returned object MUST NOT affect the Config Bus.

9.9.3 Typed Access

Implementations SHOULD provide typed access methods appropriate to the language:

Statically typed languages (Rust, Go, Java, TypeScript):

config.bind<T>("apflow")  → T    // Deserialize namespace into typed struct

Python:

# Option A: runtime type check
timeout: float = config.get_typed("apflow.api.timeout", float)

# Option B: Pydantic / dataclass binding (Pydantic as optional dependency)
settings: ApflowSettings = config.bind("apflow", ApflowSettings)

Binding rules:

  1. bind() deserializes the namespace subtree into the target type.
  2. If the namespace has a registered JSON Schema, validation SHOULD have already occurred at load time. bind() performs structural deserialization only — it SHOULD NOT re-validate.
  3. If deserialization fails (missing fields, type mismatch), bind() MUST raise a ConfigError with a clear message indicating the namespace and the failing field.
  4. The model type used in bind() is owned by the downstream package, not by apcore. apcore provides the mechanism, not the types.

9.9.4 Registered Namespace Introspection

Implementations SHOULD expose a method to list registered namespaces:

Config.registered_namespaces()
→ [
    {name: "apcore",     env_prefix: "APCORE",      has_schema: true},
    {name: "apflow",     env_prefix: "APFLOW",      has_schema: true},
    {name: "apcore-mcp", env_prefix: "APCORE_MCP", has_schema: true},
    {name: "billing",    env_prefix: "BILLING",      has_schema: false},
  ]

This is useful for diagnostic tools, CLI introspection, and IDE plugins.

9.9.5 Reserved Namespace Query

§9.5.1 (rules 3 and 4) defines a set of namespace names that are reserved by the framework and MUST NOT be registered by external callers (apcore is owned by the framework itself; _config is used for Config Bus meta-configuration per §9.6.3).

Implementations MUST expose a public, read-only query API returning the set of reserved top-level namespace names.

Canonical signature (pseudocode):

Config.reserved_namespaces()
→ frozen_set<string>   # MUST be immutable from the caller's perspective

Requirements:

  1. The returned set MUST include at minimum apcore and _config.
  2. The returned set MUST be the same set used by register_namespace to enforce CONFIG_NAMESPACE_RESERVED (single source of truth — implementations MUST NOT maintain two separate lists).
  3. The returned set MUST be immutable from the caller's perspective. Languages without immutable set types MUST return a defensive copy or a read-only view.
  4. The API MUST be callable without instantiating Config (class-level or module-level access) — diagnostic tools may query reserved names before any config file is loaded.
  5. The method name follows language idiom (snake_case for Python/Rust, camelCase getter or method for TypeScript). Concrete names are non-normative; semantics are normative.

Cross-language examples:

from apcore import Config

# Class-level query — no Config instance needed
reserved = Config.reserved_namespaces()
assert "apcore" in reserved
assert "_config" in reserved

# Pre-validate user input before register_namespace
def register_user_namespace(name: str) -> None:
    if name in Config.reserved_namespaces():
        raise ValueError(
            f"Namespace '{name}' is reserved by the apcore framework. "
            f"Pick a different name (e.g., 'my-{name}')."
        )
    Config.register_namespace(name)
import { Config } from 'apcore-js/config';

// Static getter — no Config instance needed
const reserved: ReadonlySet<string> = Config.reservedNamespaces;
console.assert(reserved.has('apcore'));
console.assert(reserved.has('_config'));

// Pre-validate user input before registerNamespace
function registerUserNamespace(name: string): void {
  if (Config.reservedNamespaces.has(name)) {
    throw new Error(
      `Namespace '${name}' is reserved by the apcore framework. ` +
      `Pick a different name (e.g., 'my-${name}').`,
    );
  }
  Config.registerNamespace(name);
}
use apcore::Config;

// Module-level query — no Config instance needed.
// Returned as `&'static [&'static str]` (idiomatic Rust for a small,
// compile-time-known reserved set; inherently immutable, zero runtime
// initialisation cost).
let reserved: &'static [&'static str] = Config::reserved_namespaces();
assert!(reserved.contains(&"apcore"));
assert!(reserved.contains(&"_config"));

// Pre-validate user input before register_namespace.
fn register_user_namespace(name: &str) -> Result<(), String> {
    if Config::reserved_namespaces().iter().any(|&s| s == name) {
        return Err(format!(
            "Namespace '{}' is reserved by the apcore framework. \
             Pick a different name (e.g., 'my-{}').",
            name, name,
        ));
    }
    // Real call site: Config::register_namespace takes a NamespaceRegistration
    // struct and returns Result<(), ModuleError>. Omitted here for brevity;
    // see §9.5.1.
    Ok(())
}

Intended audience: This API is for third-party consumers (custom CLIs, framework integrations, application code) that accept user-supplied namespace names. Official downstream packages in the apcore ecosystem (apcore-cli-*, apcore-mcp-*, apcore-toolkit-*) do not call Config.set() or register_namespace() with user input and therefore do not need to consume this API.

9.10 Validation Algorithm (Namespace-Aware A12-NS)

Algorithm A12 (§9.3) is extended for namespace mode:

Algorithm: validate_config_ns(config_data, mode, registered_namespaces, meta_config)

Input:
  config_data           — Full configuration tree
  mode                  — "legacy" or "namespace"
  registered_namespaces — Map of namespace name → registration info
  meta_config           — Parsed _config section (strict, allow_unknown)

Output:
  validated config, or throw CONFIG_INVALID error

Steps:
  1. If mode == "legacy":
       → Run original A12 algorithm on config_data (unchanged behavior)
       → Run reject_unknown_framework_keys(config_data, meta_config)
       → Return

  2. Validate the "apcore" namespace:
       apcore_data ← config_data["apcore"]
       Run original A12 algorithm on apcore_data
       Run reject_unknown_framework_keys(apcore_data, meta_config)

  3. For each top-level key (ns_name) in config_data:
       If ns_name == "_config" → skip (meta-configuration)
       If ns_name == "apcore" → skip (already validated in step 2)

       a. If ns_name is in registered_namespaces:
            registration ← registered_namespaces[ns_name]
            If registration.schema is not nil:
              Validate config_data[ns_name] against registration.schema
              Collect errors with namespace prefix: "{ns_name}: {error}"

       b. Else (unknown namespace):
            If meta_config.strict == true:
              Error: "Unknown namespace '{ns_name}' (strict mode enabled)"
            Else if meta_config.allow_unknown == true:
              Log WARN: "Namespace '{ns_name}' is not registered; data stored but not validated"
            Else:
              Remove config_data[ns_name] from the tree (silently ignore)

  4. If any errors collected → throw CONFIG_INVALID with all errors
  5. Return validated config_data
Sub-algorithm: reject_unknown_framework_keys(apcore_data, meta_config)

Steps:
  1. If meta_config.strict != true:
       → Return (the key is retained and readable; see below)

  2. declared ← union of the canonical config schemas, as a set of full
     dot-paths (see below). Every object in those schemas is
     `additionalProperties: false`, at EVERY level — not only at the section
     root — so the walk is recursive:

     walk(data, prefix):
       For each (key, value) in data:
         path ← prefix + "." + key
         If path is not a declared prefix of any entry in `declared`:
           Collect error: "Unknown key '{path}' (strict mode enabled)"
           Continue          (do not descend into an undeclared subtree)
         If value is an object AND path names a declared CONTAINER:
           walk(value, path)
         (a declared leaf ends the walk whatever its value is; a declared
          container holding a non-object is a type error Algorithm A12's
          constraint table owns, not an undeclared key)

     For each framework section in declared:
       walk(apcore_data[section], section)

  3. If any errors collected → throw CONFIG_INVALID with ALL of them

Unknown keys inside the apcore namespace. Every framework section in schemas/apcore-config.schema.json is additionalProperties: false. That closedness is enforced only under _config.strict: true.

The walk is recursive

additionalProperties: false holds at every level of those schemas, not just at the section root — observability.tracing, acl.audit, validation.binding and obs.redaction are each closed in their own right. A walk that iterated only apcore_data[section]'s direct children would leave strict mode blind exactly where a typo is hardest to spot: observability.tracing.sampling_rat would pass (its parent tracing is declared) while the canonical schema rejects it, and the misspelled sampling rate would silently fall back to its default.

  • Default (strict: false). An unknown key inside a framework section MUST be retained and readable through get(). Implementations MUST NOT silently discard it. This is a cross-language requirement: an SDK that models a section as a typed record still has to keep what the record does not model, because "the operator wrote it and it vanished" is indistinguishable from "the operator never wrote it".
  • strict: true. The key MUST cause CONFIG_INVALID, and the error MUST enumerate every offending key rather than failing on the first, so one restart is enough to see the whole problem.

allow_unknown does not apply here. It is defined in §9.6.3 for unknown top-level namespaces, and stretching one field across two granularities would make its meaning depend on where it is read.

The declared surface is the union of the canonical schemas, not one file. schemas/apcore-config.schema.json is the root, but sections that own a separate file declare their keys there — $defs/SysModulesConfig stops at enabled while schemas/sys-modules.schema.json declares control.*, error_history.* and events.* under §9.15.3. Implementations MUST derive the surface from the same set conformance/generate_config_key_governance.py reads, which is the authoritative list and is pinned by conformance/fixtures/config_key_governance.json.

Taking the root file alone would reject sys_modules.events.enabled — a documented key that every SDK's constraint table validates.

Why strict and not a warning

strict already means "every top-level key must correspond to a registered namespace" (§9.6.3). Extending it to the keys inside the framework namespace is the same promise one level down, for operators who have already asked for it. A key with no declaration is either a typo — in which case the operator is looking at a default they believe they overrode — or dead configuration. Both are worth a startup failure to someone who opted into strictness, and neither is worth one to someone who did not.

9.11 Hot-Reload (Namespace Mode)

config.reload() MUST support namespace mode:

  1. Re-read the YAML file.
  2. Re-detect mode (legacy vs namespace).
  3. Re-apply all registered namespace defaults.
  4. Re-apply all environment variable overrides per registered namespace.
  5. Re-validate per A12-NS — but only if the originating load() validated. An SDK whose load() accepts a validation opt-out (validate=False / {validate: false}) MUST carry that choice forward to reload(). Silently re-imposing validation on a config the caller deliberately loaded without it is a behaviour change disguised as a refresh; conversely an SDK with no such opt-out MUST always re-validate here. Reload is a refresh of the same config, not a stricter reload of it.
  6. Atomically replace the config data tree.
  7. Re-apply mount data for namespaces that were mounted (mount sources SHOULD be remembered).

If a mount source was from_file, the file SHOULD also be re-read during reload. If the mount source was from_dict, the original dict is re-applied (not re-read).

9.12 Cross-Language Implementation Requirements

9.12.1 Required API Surface

All SDK implementations claiming Config Bus conformance MUST implement:

Method Requirement Level Description
Config.register_namespace() MUST Static/class method for namespace registration
Config.env_map() MUST Static/class method to register global bare env var → top-level config key mappings
Config.load() MUST Load with mode detection (legacy/namespace)
Config.from_defaults() MUST Create from defaults (apcore namespace only, legacy compatible)
config.get(dot_path) MUST Namespace-aware dot-path access
config.set(dot_path, value) MUST Namespace-aware dot-path mutation
config.mount(ns, source) MUST Attach external config source
config.validate() MUST A12-NS validation
config.reload() MUST Hot-reload with namespace support
config.namespace(name) SHOULD Retrieve full namespace subtree
config.bind(ns, type) SHOULD Typed deserialization
config.get_typed(path, type) SHOULD Single-value typed access
Config.registered_namespaces() SHOULD Introspection

9.12.2 Language-Idiomatic Naming

Concept Python TypeScript Rust
Register register_namespace() registerNamespace() register_namespace()
Load Config.load() Config.load() Config::load()
Get config.get() config.get() config.get()
Mount config.mount() config.mount() config.mount()
Bind config.bind() config.bind<T>() config.bind::<T>()
Namespace config.namespace() config.namespace() config.namespace()

Parameter passing style: Each language uses its idiomatic parameter passing convention. Python uses keyword arguments (mount("ns", from_file="path")), TypeScript uses an options object (mount('ns', { fromFile: 'path' })), and Rust uses enum variants (mount("ns", MountSource::File(...))). The semantic contract is identical; only the surface syntax varies.

9.12.3 Thread Safety

All Config Bus methods MUST be thread-safe / concurrency-safe:

  • register_namespace() MUST use a global lock or atomic registry (registrations can happen from multiple threads during framework startup).
  • get(), set(), mount(), reload() MUST be synchronized per Config instance (same requirement as §12.7).
  • bind() reads a snapshot — the returned object is independent and needs no synchronization.

9.12.4 Error Types

Implementations MUST use the following error codes (extensions to §8). All config errors inherit from the base error type (ModuleError in Python, equivalent in other languages) and are non-retryable (retryable = false), consistent with CONFIG_NOT_FOUND and CONFIG_INVALID (§8.2, §8.6):

Error Code Trigger Defined in
CONFIG_NOT_FOUND Configuration file not found §8.2
CONFIG_INVALID Validation failure, including namespace-level schema validation errors and strict-mode unknown namespace errors §8.2
CONFIG_NAMESPACE_DUPLICATE register_namespace called twice for the same namespace name This section
CONFIG_NAMESPACE_RESERVED Attempt to register apcore or _config This section
CONFIG_ENV_PREFIX_CONFLICT An env_prefix already registered by another namespace (§9.8.2 rule 1) This section
CONFIG_MOUNT_ERROR Mount source file not found, invalid YAML in mount file, or mount to _config This section
CONFIG_BIND_ERROR Typed deserialization failure in bind() — missing fields or type mismatch between namespace data and target type This section
CONFIG_ENV_MAP_CONFLICT An env var name in env_map is already claimed by another env_map (global or namespace) This section

9.13 Ecosystem Integration Patterns

9.13.1 apcore Ecosystem Packages

Packages in the apcore ecosystem (apcore-mcp, apcore-a2a, apcore-cli, apflow, framework integrations) SHOULD follow this pattern:

# In package __init__.py or equivalent entry point

from apcore import Config

# Register at import time — before Config.load() is called by the application
Config.register_namespace(
    "apcore-mcp",
    schema=_resolve_schema_path("apcore-mcp.schema.json"),
    env_prefix="APCORE_MCP",   # shares APCORE_ with the apcore namespace; longest-prefix match dispatches it (§9.8.2)
    defaults={"transport": "streamable-http", "port": 8000},
)

Convention for apcore ecosystem packages:

Package Namespace Env Prefix Conflict? Schema
apcore (core) apcore APCORE — apcore-config.schema.json
apcore-mcp apcore-mcp APCORE_MCP Shared leading APCORE_, resolved by longest-prefix match (§9.8.2) apcore-mcp.schema.json
apcore-a2a apcore-a2a APCORE_A2A Same as above apcore-a2a.schema.json
apcore-cli apcore-cli APCORE_CLI Same as above apcore-cli.schema.json
apflow apflow APFLOW No — disjoint from APCORE_ apflow.schema.json
django-apcore django-apcore DJANGO_APCORE No — no DJANGO namespace registered django-apcore.schema.json
fastapi-apcore fastapi-apcore FASTAPI_APCORE No — no FASTAPI namespace registered fastapi-apcore.schema.json
flask-apcore flask-apcore FLASK_APCORE No — no FLASK namespace registered flask-apcore.schema.json
nestjs-apcore nestjs-apcore NESTJS_APCORE No — no NESTJS namespace registered nestjs-apcore.schema.json
axum-apcore axum-apcore AXUM_APCORE No — no AXUM namespace registered axum-apcore.schema.json

Why APCORE_MCP can share APCORE_. The prefix APCORE_ (for the apcore namespace) is a string prefix of APCORE_MCP_, so APCORE_MCP_TRANSPORT could be read as apcore → mcp.transport or as apcore-mcp → transport. Dispatch among registered prefixes is by longest match (§9.8.2), which gives it to apcore-mcp, and no apcore key begins with mcp., so the other reading names no apcore key. Framework integrations like DJANGO_APCORE do not meet the question at all: no DJANGO namespace is registered, so DJANGO_APCORE_* is unambiguous.

9.13.2 Third-Party Package Integration

Third-party packages that want to participate in the Config Bus SHOULD follow this pattern:

# In third-party package setup
from apcore import Config

# Schema is optional — register for namespace isolation and env override only
Config.register_namespace(
    "my-billing",
    env_prefix="BILLING",
    # No schema — existing config structure is not constrained by apcore
)

Third-party packages MUST NOT assume that apcore.Config is the only configuration source. The registration is additive — if the application does not use the Config Bus, the package must fall back to its own configuration mechanism:

# Defensive integration pattern for third-party packages
def get_billing_config(apcore_config=None):
    """Return billing config from Config Bus if available, else standalone."""
    if apcore_config is not None:
        try:
            return apcore_config.namespace("my-billing")
        except KeyError:
            pass

    # Fallback: use own config mechanism
    return load_billing_config_standalone()

9.13.3 Framework Integration Auto-Registration

Framework integrations (django-apcore, fastapi-apcore, etc.) SHOULD auto-register their namespace when the framework loads them:

Django:

# django_apcore/apps.py
from django.apps import AppConfig as DjangoAppConfig

class DjangoApcoreConfig(DjangoAppConfig):
    name = "django_apcore"

    def ready(self):
        from apcore import Config
        Config.register_namespace(
            "django-apcore",
            schema=self._resolve_schema(),
            env_prefix="DJANGO_APCORE",
            defaults={"auto_register_modules": True, "url_prefix": "/api/apcore"},
        )

FastAPI:

# fastapi_apcore/__init__.py
from apcore import Config

Config.register_namespace(
    "fastapi-apcore",
    schema=_resolve_schema(),
    env_prefix="FASTAPI_APCORE",
    defaults={"auto_register_modules": True, "route_prefix": "/apcore"},
)

NestJS:

NestJS (no NESTJS namespace exists — single underscore is safe):

// nestjs-apcore/src/index.ts
import { Config } from 'apcore-js/config';

Config.registerNamespace({
  name: 'nestjs-apcore',
  schema: resolveSchema(),
  envPrefix: 'NESTJS_APCORE',
  defaults: { autoRegisterModules: true, routePrefix: '/apcore' },
});

9.14 Config Discovery (Optional)

Implementations may support automatic configuration file discovery. When Config.load() is called without a path argument, the following search order SHOULD be used:

Algorithm: discover_config_file()

Search order (first match wins):
  1. $APCORE_CONFIG_FILE          — explicit override via env var
  2. ./project.yaml               — project root
  3. ./project.yml
  4. ./apcore.yaml                — apcore-specific
  5. ./apcore.yml
  6. ~/.config/apcore/config.yaml — user-level (XDG on Linux, ~/Library/Application Support on macOS)
  7. ~/.apcore/config.yaml        — legacy user-level

If no file is found:
  → Use Config.from_defaults() (apcore namespace only, no error)

This is a MAY-level feature. Implementations that do not support discovery MUST require an explicit path in Config.load().

Note: The file name does not influence mode detection. A file named project.yaml may contain legacy-mode content, and a file named apcore.yaml may contain namespace-mode content. Mode is always determined by the presence of the apcore: top-level key (see §9.6.1).

9.15 apcore Built-in Namespace Registrations

The framework pre-registers three namespaces for its own subsystems at startup, before any application Config.load() call: observability (§9.15.2), sys_modules (§9.15.3) and obs (§9.15.4). Every implementation MUST register all three (D-144). This applies the Config Bus pattern (§9.4) to apcore's own internal configuration — the same mechanism apcore exposes to third parties is used by apcore itself.

The namespaces promote existing flat keys that already live inside the apcore namespace into dedicated, independently-configurable namespaces. The migration is strictly additive: legacy mode files continue to work unchanged.

9.15.1 Bootstrap Order

┌─────────────────────────────────────────────────────────────┐
│                Framework Bootstrap Order                    │
│                                                             │
│  1. Config.register_namespace("observability", ...)         │
│  2. Config.register_namespace("sys_modules", ...)           │
│     Config.register_namespace("obs", ...)                   │
│  3. [Application / ecosystem packages register their own]   │
│  4. Config.load(path)                                       │
│  5. register_sys_modules(config)                            │
└─────────────────────────────────────────────────────────────┘

Third-party packages SHOULD register their namespaces after step 2 and before step 4 (at import time). The order of the three built-in registrations among themselves is not significant.

9.15.2 observability Namespace

Extracts the existing observability.* flat keys from the apcore namespace into a dedicated Config Bus namespace. This makes observability configuration independently addressable and allows ecosystem adapters to read a single authoritative source.

The value sets below are not declared here. schemas/apcore-config.schema.json is the canonical declaration of every observability.* key, its type, its enum and its default, and this registration MUST agree with it. The namespace has no schema file of its own: a second declaration of one surface would be free to disagree with the first. in_memory is not a configurable exporter value (§10.1.1 requirement 2).

Config.register_namespace(
    "observability",
    # Types, enums and defaults: schemas/apcore-config.schema.json $defs/ObservabilityConfig.
    env_prefix="APCORE_OBSERVABILITY",
    defaults={
        "tracing": {
            "enabled": False,
            "strategy": "full",        # §10.7
            "sampling_rate": 1.0,
            "exporter": "stdout",      # §10.1.1 requirement 2
            "otlp_endpoint": None,     # §10.1.1 requirement 3
        },
        "metrics": {
            "enabled": False,          # Deprecated, no effect — see §9.2.4
            "exporter": "stdout",      # Deprecated, no effect — see §9.2.4
        },
    },
)

The namespace MUST declare tracing and metrics only — the two blocks $defs/ObservabilityConfig declares — and MUST NOT register any other block under observability (D-144). The settings those other blocks would name live elsewhere: error-history bounds in sys_modules.error_history.*, the platform-notify thresholds in sys_modules.events.thresholds.* (§9.15.3), and redaction in obs.redaction.* (§10.6.1).

Migration: Existing apcore.observability.* flat keys map 1:1 to observability.* namespace keys. No changes required to existing configuration files.

Environment variable examples (env_prefix = APCORE_OBSERVABILITY):

APCORE_OBSERVABILITY_TRACING_STRATEGY=error_first
APCORE_OBSERVABILITY_TRACING_ENABLED=true
APCORE_OBSERVABILITY_TRACING_SAMPLING_RATE=0.25

Ecosystem adoption — adapter packages SHOULD read from this namespace rather than maintaining their own observability defaults:

Package Keys to read
apcore (core) Full namespace — owns all keys
apcore-mcp tracing.strategy
apcore-a2a tracing.strategy
apcore-cli tracing.strategy
Third-party tracing.* (MAY) — read-only

logging.level and logging.format are not listed: both are withdrawn (§9.2.4, D-67), and no apcore code path acts on either, so an adapter reading them would read a value with no effect.

9.15.3 sys_modules Namespace

Promotes the existing sys_modules.* flat keys — currently read directly by register_sys_modules() — into a dedicated namespace, making system module configuration independently overridable without touching the apcore namespace.

Config.register_namespace(
    "sys_modules",
    schema="schemas/sys-modules.schema.json",
    env_prefix="APCORE_SYS",
    defaults={
        # The two activation flags default to False, matching
        # schemas/sys-modules.schema.json and §6.6.3. The per-module sub-flags
        # below stay True: they select WHICH modules register once activation
        # has happened, they do not activate anything on their own.
        "enabled": False,
        "health":   {"enabled": True},
        "manifest": {"enabled": True},
        "usage": {
            "enabled": True,
            "retention_hours": 168,          # Retention for usage records in hourly buckets
            "bucketing_strategy": "hourly",  # Supported granularity
        },
        "control":  {"enabled": True},
        "error_history": {
            "max_entries_per_module": 50,
            "max_total_entries": 1000,
        },
        "events": {
            "enabled": False,
            "subscribers": [],
            "thresholds": {
                "error_rate": 0.1,
                "latency_p99_ms": 5000.0,
            },
        },
    },
)

These defaults are off, and §6.6.3 is the reason

enabled and events.enabled are the two flags §6.6.3 describes as the 0 / 7 / 10 activation ladder, and both default to false. Registering this namespace with enabled: True would stand the system modules up in every project that never asked for them, and events.enabled: True would additionally stand up the three system.control.* write modules — the approval-gated control plane — by default. The same defaults are declared by schemas/sys-modules.schema.json and pinned by conformance/fixtures/config_defaults.json.

Migration: register_sys_modules() MUST prefer config.namespace("sys_modules") in namespace mode, falling back to config.get("sys_modules.*") in legacy mode.

Environment variable examples (env_prefix = APCORE_SYS):

APCORE_SYS_ENABLED=true
APCORE_SYS_EVENTS_THRESHOLDS_ERROR_RATE=0.05
APCORE_SYS_EVENTS_ENABLED=false

9.15.4 obs Namespace

Carries the configured redaction rules of §10.6.1. Its declaration is $defs/ObsConfig in schemas/apcore-config.schema.json, and the registration MUST agree with it (D-144).

Config.register_namespace(
    "obs",
    # Types and defaults: schemas/apcore-config.schema.json $defs/ObsConfig.
    env_prefix="APCORE_OBS",
    defaults={
        "redaction": {
            "regex_patterns": [],
            "sensitive_keys": [...],          # the canonical default list, §10.6.1
            "replacement": "***REDACTED***",
        },
    },
)

9.16 Event Type Naming Convention and Canonical Definitions

This section defines the canonical event type names, their payload contracts, and the naming convention for the ecosystem. Each event type names exactly one event with one payload shape.

9.16.1 Naming Convention

Event type names MUST use dot-namespaced format. The prefix identifies ownership:

Prefix Owner Examples
apcore.* Core framework apcore.registry.module_registered, apcore.config.updated
apcore-mcp.* apcore-mcp apcore-mcp.tool_called
apcore-a2a.* apcore-a2a apcore-a2a.task_submitted
apcore-cli.* apcore-cli apcore-cli.command_invoked
apflow.* apflow apflow.step_completed
Custom Third-party billing.invoice_generated

The apcore.* prefix is reserved. Ecosystem packages MUST NOT emit events with this prefix.

9.16.2 Canonical Core Event Types

The following are the canonical event type names, payload keys, and severity for all events emitted by apcore SDKs. Implementations MUST use these names, and MUST NOT emit the retired names in the second column. Each retired name either named two different events with different payloads (module_health_changed, config_changed), and is replaced by one canonical name per event, or broke the apcore.<subsystem>.<event> convention, where the subsystem segment names the emitter: registry events belong to apcore.registry.*, not apcore.module.*, and the threshold events belong to apcore.health.* — the health-monitoring PlatformNotifyMiddleware — because error and latency are categories, not subsystems. features/event-system.md lists each retired name with its replacement.

Canonical Name Retired name Severity Emitted by Payload Keys
apcore.registry.module_registered module_registered, apcore.module.registered info Registry bridge module_id
apcore.registry.module_unregistered module_unregistered, apcore.module.unregistered info Registry bridge module_id
apcore.registry.module_drain_started — info Registry operation_id, reason_kind, drain_timeout_ms
apcore.registry.module_drain_timed_out — warn Registry operation_id, reason_kind, action, active_count
apcore.registry.module_drain_recovered — info (ready) / error (unavailable) Registry operation_id, abort_reason, outcome
apcore.registry.module_reload_failed — error Registry operation_id, phase, error_code, compensation
apcore.client.shutdown_resources_completed — info (completed) / error (failed) APCore client operation_id, registry_outcome, forced_count, failure_count
apcore.module.toggled module_health_changed (toggle usage) info/warn system.control.toggle_feature module_id, enabled
apcore.module.reloaded config_changed (reload usage) info system.control.reload_module module_id, previous_version, new_version
apcore.config.updated config_changed (key-update usage) info system.control.update_config key, old_value, new_value
apcore.config.reloaded — info system.control.reload_module with reload_config: true, in an implementation that offers it (D-44) reason
apcore.health.error_threshold_exceeded apcore.error.threshold_exceeded error PlatformNotifyMiddleware module_id, error_rate, threshold
apcore.health.latency_threshold_exceeded apcore.latency.threshold_exceeded warn PlatformNotifyMiddleware module_id, p99_latency_ms, threshold
apcore.health.recovered module_health_changed (recovery usage) info PlatformNotifyMiddleware module_id, error_rate
apcore.approval.decision — info (approved/pending) / warn (rejected/timeout) Approval Gate (§7) module_id, status, approved_by, reason, approval_id (non-secret audit_id or null), trace_id
apcore.policy.override — info Approval Gate (§7) module_id, pattern, requires_approval, destructive, needs_approval, reason, trace_id
apcore.acl.denied — warn ACL Check (§6) module_id, caller_id, reason, trace_id
apcore.acl.audit — observability-independent: the ACL file's audit.log_level, default info ACL Check (§6) — the default sink of §6.3.2 only, never a supplied callback all thirteen §6.3.1 AuditEntry fields, under their snake_case wire names
apcore.stream.post_validation_failed — error Executor (streaming Phase 3) error_type, message, trace_id
apcore.registry.module_load_failed — error Registry module_id, callback_name, error_type, error_message
apcore.circuit.opened — warn CircuitBreakerMiddleware module_id, caller_id, error_rate
apcore.circuit.closed — info CircuitBreakerMiddleware module_id, caller_id, error_rate
apcore.subscriber.circuit_opened — warn Event delivery (per-subscriber breaker) subscriber_id, subscriber_type, consecutive_failures
apcore.subscriber.circuit_closed — info Event delivery (per-subscriber breaker) subscriber_id, subscriber_type, recovery_attempt
apcore.event.delivery_failed — error Event bus (dead-letter path) subscriber_type, subscriber_id, original_event, error, attempt_count, timestamp — the full payload is specified in features/event-system.md § Dead-Letter Event on Permanent Failure, which is authoritative

The payloads of apcore.subscriber.circuit_opened and apcore.subscriber.circuit_closed MUST carry subscriber_id, the ID of the subscriber whose breaker changed state, beside subscriber_type: two subscribers of one type are otherwise indistinguishable (D-145).

Governance events. apcore.approval.decision, apcore.policy.override, and apcore.acl.denied make the governance chain (ACL → policy → approval) observable on the event bus. They are emitted only when an event emitter is configured, are best-effort side channels (execution outcome MUST NOT depend on their delivery), and follow the skip contract: the approval gate emits apcore.approval.decision only when it actually adjudicates (never on a skipped gate), and apcore.acl.denied is NOT emitted during a dry-run validate() preflight. See §7.9 (Execution Policy) for the policy layer that drives apcore.policy.override.

9.16.3 Event Pattern Matching

A subscriber's event_pattern, and the include_events / exclude_events lists of a filter subscriber, are glob-dialect patterns matched with A25 (§9.2.3) against the event type, case-sensitively. Event types are lower-case by §9.16.1's convention, so a case fold would change no decision and is not applied.

  1. event_pattern selects what a subscriber receives. "*" — the default — receives everything.
  2. include_events, when present, is an allow-list and is decisive: the event is forwarded when any entry matches and discarded otherwise, and exclude_events is not consulted. exclude_events applies only when include_events is absent, and then an event matching any entry is discarded.
  3. exclude_events is why the algorithm has to be named here. A pattern that fails to match means the event is delivered, so a matcher that understands fewer metacharacters than the operator wrote does not narrow the filter — it opens it: a subscriber excluding secret.?vent would receive that event from a matcher that supports only *, with nothing to indicate the pattern had not been understood. include_events fails the safe way round, withholding events instead.
  4. A pattern is never rejected and never warned about on syntactic grounds (§9.2.3 requirement 2).

10. Observability Specification

10.1 Tracing

Based on OpenTelemetry specification:

tracing:
  # Trace context
  context:
    trace_id:
      format: "32-char lowercase hex (W3C Trace Context compatible)"
      propagation: "Must propagate in call chain"
    span_id:
      format: "16 character hexadecimal"
    parent_span_id:
      format: "16 character hexadecimal"

  # Span creation rules
  spans:
    - name: "apcore.module.execute"
      attributes: [module_id, method, duration_ms, success]

  # Propagation methods
  propagation:
    - "Auto-propagate through context parameter"
    - "Use W3C Trace Context for HTTP calls"

apcore.module.execute is the one span the specification defines. Executor.validate() (§12.8) is not traced (D-143).

Each execution span records the calling invocation's span ID as its parent. At the entry to a local call tree, the parent is the validated remote parent ID when a TraceParent supplied the trace ID. Concurrent calls in the same trace retain individual start times and parent links. See Tracing architecture and the trace_context conformance fixture.

10.1.1 Tracing from Configuration (observability.tracing.*)

The five observability.tracing.* keys (enabled, strategy, sampling_rate, exporter, otlp_endpoint) are one unit, because they depend on one another: sampling_rate is consulted only under a strategy that uses it; the strategy and rate configure a tracing middleware, which has an effect only once it is installed; and installing it requires an exporter, which is an object rather than a name. Rationale: a key in this chain that is honoured without the others reads configuration and changes nothing an operator can observe.

The keys are declared — types, enums and defaults — in schemas/apcore-config.schema.json, which is canonical; §9.15.2's observability namespace registration references that declaration and does not carry its own.

Requirements:

  1. Installation. When the loaded configuration declares observability.tracing.enabled: true, implementations MUST install a tracing middleware built from observability.tracing.* at client construction. When the key is absent or false — the default — implementations MUST install nothing: a project that does not ask for tracing is untouched.

  2. The exporter is selected by name. observability.tracing.exporter MUST select the exporter the middleware is built with:

Value Exporter Target
stdout (default) the implementation's stdout span exporter the process's standard output
otlp the implementation's OTLP span exporter observability.tracing.otlp_endpoint, or http://localhost:4318/v1/traces when it is null
jaeger none — see requirement 4 —

The enum is closed and this table is the whole of it. An implementation's in-memory or test span exporter MUST NOT be reachable by name from configuration. Rationale: a caller who selects one this way has no standardised way to reach the spans it holds, so it would take effect and produce nothing an operator can see.

  1. otlp_endpoint reaches the exporter, or the configuration is rejected. When the effective exporter is otlp, observability.tracing.otlp_endpoint MUST be passed to it; when it is null, the implementation's default endpoint applies. When otlp_endpoint is set to a non-null value and the effective exporter is not otlp, implementations MUST reject the configuration at load with a CONFIG_INVALID error naming both keys. Rationale: accepting it would leave an operator with an endpoint they wrote down and nothing reading it.

  2. A named exporter that this implementation cannot build installs nothing, and says so. When exporter names something the implementation cannot construct, it MUST emit a diagnostic naming the value and what to use instead, MUST NOT install a tracing middleware, and MUST NOT substitute a different exporter. Tracing is then off, and the operator learns why nothing is being exported. Two cases exist:

  3. jaeger names no implementation. It stays in the enum for the 1.x line and is removed at v2.0 under §13.4's window, because narrowing an enum rejects a configuration that is otherwise accepted.

  4. otlp where the implementation's OTLP support is an optional dependency or build feature that is not present. Installing a middleware whose exporter discards every span would be worse than installing none: the operator would see tracing "enabled" and no traces, with nothing to read.

  5. Sampling reaches the decision. observability.tracing.strategy and observability.tracing.sampling_rate MUST reach the middleware's sampling decision as §10.7 defines it. An operator who writes strategy: proportional with sampling_rate: 0.1 MUST get approximately 10% of call chains sampled, not all of them.

  6. Precedence, and never two middlewares. A tracing middleware the caller supplied in code wins: when one is already present in the chain, implementations MUST NOT install a second from configuration. A span_exporter extension MUST reconfigure the installed middleware rather than adding one, so the ordering is extension-supplied exporter object > observability.tracing.exporter > the default. This follows the general rule that an API argument beats Config (§9.1.3).

  7. No deprecation warning. None of the five observability.tracing.* keys is deprecated. Implementations MUST NOT emit the §9.2.4 deprecation warning for any of them.

10.2 Logging

logging:
  levels: [trace, debug, info, warn, error, fatal]

  # Structured logging
  format:
    timestamp: "ISO 8601"
    level: string
    message: string
    trace_id: string
    module_id: string
    extra: object

  # Sensitive data
  sensitive_data:
    - "x-sensitive fields auto-redacted"
    - "Passwords, tokens not logged"

10.3 Metrics

metrics:
  - name: "apcore_module_calls_total"
    type: counter
    labels: [module_id, status]

  - name: "apcore_module_duration_seconds"
    type: histogram
    labels: [module_id]

  - name: "apcore_module_errors_total"
    type: counter
    labels: [module_id, error_code]

10.4 Usage Tracking

Implementations SHOULD provide a UsageCollector that tracks per-module call statistics for the system.usage.* system modules:

usage:
  storage: "in-memory"              # In-memory bucketed storage
  bucket_duration: "1h"             # Hourly buckets for trend data
  per_module:
    - call_count: counter           # Total calls
    - error_count: counter          # Total errors
    - latency_ms: histogram         # Call duration histogram
    - last_called_at: timestamp     # Last call time
  aggregate:
    - total_calls: counter
    - total_errors: counter
    - avg_latency_ms: gauge

A UsageMiddleware SHOULD automatically record call data into the UsageCollector during Step 10 (Middleware After). The collected data is consumed by system.usage.summary and system.usage.module system modules.

10.5 Trace ID Format

trace_id MUST be a 32-character lowercase hexadecimal string, aligned with the W3C Trace Context trace-id field for direct interoperability with distributed tracing backends (Jaeger, Tempo, Honeycomb, Datadog, OTLP) and OpenTelemetry SDKs.

trace_id_spec:
  format: "32-char lowercase hex"      # MUST
  pattern: "^[0-9a-f]{32}$"
  example: "4bf92f3577b34da6a3ce929d0e0e4736"

  distributed:
    w3c_trace_context: "REQUIRED"
    traceparent_header: "traceparent: 00-{trace_id}-{span_id}-{flags}"

  generation:
    - "Top-level calls MUST generate a random 128-bit trace_id when no valid trace_parent is supplied"
    - "Child calls MUST inherit the parent call's trace_id unchanged"
    - "All-zero (00000000000000000000000000000000) is invalid under W3C Trace Context. APCore also reserves all-f (ffffffffffffffffffffffffffffffff). Implementations MUST reject both values as APCore trace IDs."

  external_trace_parent_handling:
    # Applies only when Context.create receives an explicit trace_parent argument.
    - "Input matching ^[0-9a-f]{32}$ and unequal to either reserved value above MUST be accepted as-is"
    - "All other inputs MUST cause the SDK to generate a fresh trace_id and SHOULD log a warning at WARN level"
    - "Implementations MUST NOT raise or reject the inbound request on invalid trace_parent — execution MUST continue with a regenerated trace_id"
    - "Implementations MUST NOT perform dashed-UUID stripping, case folding, or similar normalization at Context.create — such normalization, if needed, is the responsibility of the TraceParent header parser or the user's ContextFactory"

Note: The field layout follows W3C Trace Context, with the additional APCore all-f reservation. Implementations SHOULD treat the trace ID format as a versioned contract.

10.6 Sensitive Data Redaction

Implementations MUST redact fields marked as x-sensitive in logs and trace outputs.

A field is marked when its schema carries x-sensitive: true, or when any branch of an anyOf, oneOf or allOf in its schema does — which is where an optional field (Secret | None) puts the marker. Properties declared inside a combinator branch are fields of the object like those declared directly, and a value described by several branches is redacted when any of them marks it sensitive. The walk does not decide which branch the value matched (D-152).

Local $ref pointers, plain-name anchors supported by the effective draft, and in-document resource $id scopes participate in this walk. Index only actual schema positions for the declared or inherited draft; an unknown keyword or literal default/const/examples value must not introduce a resource or shadow an anchor. Cyclic references terminate without schema expansion or network/file retrieval. The object root is a container, preserving the public object-return contract; a marker describing a nested field can replace that entire field. Modern positional arrays and declared legacy tuples apply sensitivity only at the positions their item schemas describe, including their respective tails.

Algorithm: redact_sensitive(data, schema)

Input:
  data   — Data object to redact
  schema — Corresponding JSON Schema (contains x-sensitive marking)

Output:
  redacted_data — Redacted object copy

Steps:
  1. redacted ← deep_copy(data)
  2. redact_fields(redacted, schema)
  3. Return redacted

redact_fields(object, schema):
  For each view in schema_views(schema):
    For each (name, field_schema) in view.properties:
      If name exists in object:
        object[name] ← redact_value(object[name], field_schema)

redact_value(value, schema):
  If value is null: return null
  views ← schema_views(schema)
  If any view carries x-sensitive: true: return "***REDACTED***"
  If value is an object: redact_fields(value, schema)
  If value is an array:
    For each view in views and each element index:
      item_schema ← item_schema_at(view, index)
      If item_schema exists:
        value[index] ← redact_value(value[index], item_schema)
  Return value

schema_views(schema):
  Follow local $ref targets and all anyOf/oneOf/allOf branches.
  Carry each schema's resource base and declared/inherited dialect.
  Visit each schema node at most once for the current data node.
  Reset that visited set for every child data node, so recursive data
  receives redaction independently. Never retrieve an external resource.

item_schema_at(schema, index):
  Draft 2020-12: prefixItems[index] within the prefix; dictionary items
  beyond the prefix. Draft-07/2019-09: tuple items[index] within the tuple;
  dictionary additionalItems beyond the tuple. Dictionary items without
  positional schemas applies to every element. Ignore keywords outside
  the effective dialect and opaque default/const/examples data.

Complexity: O(s + n*g), where s is indexed schema size, n is data size,
and g bounds the schema views visited per data node

10.6.1 Configured Redaction Rules (obs.redaction.*)

§10.6 covers redaction driven by the schema (x-sensitive). This section covers redaction driven by configuration (D-53).

Redaction is applied as the union of three independent rules: (a) x-sensitive schema annotations (§10.6), (b) obs.redaction.sensitive_keys matched against field names, and (c) obs.redaction.regex_patterns matched against field values. A field redacted by any one of them is redacted.

sensitive_keys — a hybrid, deliberately

Each entry is interpreted per-entry, by its own spelling:

Entry contains Interpreted as Matched against
* or ? a glob-dialect pattern, A25 (§9.2.3) the whole field name
neither a substring the normalized field name
  1. Both branches are case-insensitive, and the fold MUST be applied to the pattern and to the field name alike. Rationale: folding only the field name is a silent bypass — a capitalised entry such as "*Token*" is valid and simply matches nothing, so the field is logged in plaintext with no warning.
  2. The glob branch is anchored: the pattern must match the entire field name. key is a substring entry and matches api_key; *key* is a pattern entry and matches it too; key* matches neither api_key nor keyring's sibling api_keyring. This is what makes the two branches usefully different rather than redundant.
  3. The substring branch normalizes both sides before comparing: lower-case, and - and whitespace mapped to _, so "X-API-Key" matches the entry api_key. Implementations SHOULD additionally collapse separators so a camelCase field (AccessKey) matches a snake_case entry (access_key).
  4. [, ], {, } and \ are literals in the glob branch, per §9.2.3 requirement 4. Passing them through to a host regular-expression engine unescaped MUST NOT happen. Rationale: in RegExp syntax [!p] means "! or p" while in a glob dialect it means "not p", so passing it through would redact the field the operator excluded and leak the ones they meant to catch. Under this section [!p]assword contains no * or ?, so it is a substring entry and matches a field literally named that — inert rather than inverted, which is the correct outcome for a construct this dialect does not have.
  5. An empty entry MUST be ignored. It is not a substring that matches every field.
regex_patterns
  1. Each entry is a regular expression in the regex dialect of §9.2.3, matched by unanchored search, case-insensitively, against a field's value. A value that matches is replaced by replacement.
  2. The value rule applies to string values only. A number, boolean, null, object or array MUST NOT be tested against regex_patterns, and MUST NOT be converted to a string in order to test it. Containers are descended into instead, so a string inside an object or array is still reached by this rule at its own position.

Rationale: the conversion to a string cannot be specified portably — for the single value {"a": 1} host languages render {'a': 1}, [object Object] and {"a":1}, and for true they render True and true. A rule defined over a per-language rendering is one rule per language, which §9.2.3 exists to prevent. 3. Entries SHOULD stay inside §9.2.3 requirement 6c's portable subset — no lookaround, no backreferences, no inline flag groups. 4. A pattern the engine cannot compile MUST NOT be dropped in silence (§9.2.3 requirement 6d). It MUST produce a diagnostic naming the pattern and the engine's error, and validate_config() MUST report it. Rationale: a regex_patterns entry that fails to compile is indistinguishable, from the outside, from one that compiles and matches nothing — and the observable difference is credentials in plaintext in a log. 5. Compilation SHOULD happen once, when the configuration is read, so the diagnostic fires at load rather than per log record. Where an implementation suppresses a repeated diagnostic, the suppression MUST NOT outlive the configuration it was raised for. Rationale: a process-wide "already reported" set silences the second configuration that loads the same broken pattern — the reload case and the multi-tenant case, exactly the two where an operator most needs to be told. 6. The scan limit obs.redaction.max_regex_scan_length defaults to 65536 UTF-8 bytes per string value and accepts nonnegative safe integers. If at least one value regex is active and the encoded string exceeds the limit, SDKs MUST replace the entire value before any regex scan.

Protected fields

Five correlation fields are never redacted, whatever an operator's patterns say:

trace_id   span_id   caller_id   module_id   target_id

Implementations MUST exempt them from rules (b) and (c) alike, at every nesting depth. Rationale: a sensitive_keys entry as ordinary as *id* would otherwise erase exactly the identifiers that make the record correlatable, and a log that cannot be correlated cannot be used to investigate the incident the redaction was configured for. The exemption covers the protected field's own value only: a container reached through a protected key is still descended into, and sensitive fields inside it are still redacted.

Where the rules apply
  1. The union of §10.6's x-sensitive rule and this section's two configured rules MUST be applied at both of the surfaces §10.6 names, using the same rules at each:

a. log emission — the structured logger's record, including the extra object; and

b. the executor's input/output capture point — whatever fills the context's redacted_inputs and redacted_output, at execution pipeline steps 3, 7 and 9.

  1. An implementation MUST NOT honour the configured sensitive_keys / regex_patterns / replacement at one of those surfaces and only the default sensitive_keys list at the other. Rationale: the same field, in the same execution, would be a secret in the log line and plaintext in the captured input. The capture point fills what the audit trail carries — governance events, error histories, and any middleware reading context.redacted_inputs — so a rule honoured only at log emission redacts the log line an operator is watching and stores the secret in the record they are not.

  2. Where the capture point cannot reach a configuration — a directly constructed executor with none supplied — the default obs.redaction.sensitive_keys list (declared in schemas/apcore-config.schema.json) applies, exactly as at log emission. "No configuration" means the defaults, never no redaction.

  3. §10.6's redact_sensitive(data, schema) states the schema-driven rule only. An implementation of the capture point therefore also needs the configured (or default) rules as an input; a two-argument signature that cannot receive them does not satisfy requirement 1.

  4. Built-in logging middleware logs the captured values (D-131). A logging middleware shipped by an implementation MUST log context.redacted_inputs and context.redacted_output — never the raw inputs or output it is handed — so that the x-sensitive rule and the configured rules both apply to what it writes. A field marked x-sensitive MUST NOT appear in its output unredacted, whether or not a redaction configuration was supplied.

10.7 Sampling Strategy

Implementations MUST support the following four sampling strategies, named by observability.tracing.strategy (§9.1.1) and reaching the decision through §10.1.1 requirement 5. The strategy chooses whether the rate is consulted at all, which is why the rate alone cannot express this table:

strategy Decision sampling_rate
full (default) every call chain is recorded (recommended for development) not consulted
proportional recorded with probability sampling_rate consulted
error_first errors always recorded, successful calls with probability sampling_rate consulted
off nothing is recorded not consulted

sampling_rate is a probability only; it is never an on/off switch. The configuration key that names the strategy is strategy.

Sampling decision MUST be made at call chain root node, child calls MUST inherit parent call's sampling decision.

10.8 Span Naming Convention

Implementations SHOULD follow these Span naming conventions:

span_naming:
  pattern: "apcore.{component}.{operation}"
  examples:
    module_execute: "apcore.module.execute"
    acl_check: "apcore.acl.check"
    middleware_before: "apcore.middleware.before"
    middleware_after: "apcore.middleware.after"
    schema_validate: "apcore.schema.validate"
    registry_discover: "apcore.registry.discover"

  attributes:
    - "module_id"        # MUST
    - "method"           # MUST (execute|describe)
    - "duration_ms"      # MUST
    - "success"          # MUST (boolean)
    - "error_code"       # SHOULD (when failed)
    - "caller_id"     # SHOULD

11. Extension Mechanism

11.1 Middleware/Interceptors

middleware:
  order: "Onion model (first in, last out)"

  hooks:
    - name: "before"
      params: [module_id, inputs, context]
      can_modify: [inputs, context]
      can_abort: true

    - name: "after"
      params: [module_id, inputs, output, context]
      can_modify: [output]

    - name: "on_error"
      params: [module_id, inputs, error, context]
      can_retry: true

11.2 Middleware Registration and Priority

Middleware is registered in code, on the client or on the Executor. No key in apcore.yaml registers a middleware; the one middleware configuration can install is the tracing middleware of §10.1.1.

middleware_registration:
  # Registration (code only)
  methods:
    add: "use(middleware)"                    # client or Executor
    add_callback: "use_before(fn) / use_after(fn)"   # single-phase adapters, priority 100
    remove: "remove(middleware)"              # removes exactly the registered instance

  # Priority is a property of the middleware, not an argument of use()
  priority:
    range: "0-1000"
    higher_first: true           # Higher number executes first in the before phase
    default: 100
    ties: "Equal priorities keep registration order"
    out_of_range: "Rejected at construction or registration"

  # Execution order example
  execution_order:
    request: "[1000] → [900] → [800] → [100] → Module"
    response: "Module → [100] → [800] → [900] → [1000]"

Each SDK's method names and the duplicate-registration rules are in middleware-system.md § Registration and Removal.

11.3 Custom Extension Points

extension_points:
  # Extension point definitions
  points:
    schema_loader:
      description: "Custom Schema loading method"
      interface: "load(module_id: str) -> Schema"
      use_case: "Load Schema from remote service/database; Binding file Schema loading"
      default: "YAMLSchemaLoader"

    id_converter:
      description: "Custom ID conversion rules"
      interface: "to_canonical(local_id, lang) -> str"
      use_case: "Support new programming language"
      default: "DefaultIDConverter"

    module_loader:
      description: "Custom module loading method"
      interface: "load(module_id: str) -> Module"
      use_case: "Remote loading, dynamic compilation; Function-based module loading; Binding file target resolution and module loading"
      default: "DirectoryModuleLoader"

    executor:
      description: "Custom execution method"
      interface: "execute(module, method, input, context) -> output"
      use_case: "Distributed execution, sandbox isolation"
      default: "LocalExecutor"

    acl_checker:
      description: "Custom permission checking"
      interface: "check(caller, target, action, context) -> bool"
      use_case: "Integrate external permission system"
      default: "YAMLACLChecker"

  # Extension point registration (code only)
  registration:
    code:
      example: |
        extensions = ExtensionManager()
        extensions.register("discoverer", RemoteDiscoverer(url="https://..."))
        extensions.apply(registry, executor)

Extensions are registered in code. No key in apcore.yaml registers an extension, and the implementations registered for one point are not chained (§11.7) (D-143).

NOTE — ExtensionManager Extension Point Names: The extension point names above (schema_loader, id_converter, module_loader, executor, acl_checker) are the conceptual taxonomy. ExtensionManager registers the following built-in extension points:

Conceptual name ExtensionManager name Rationale
schema_loader discoverer Unified discovery replaces separate schema/module loading
module_loader module_validator Validation is the primary customization need at load time
acl_checker acl Shortened for ergonomic API use
(no equivalent) middleware First-class middleware extension point for runtime pipeline customization
(no equivalent) span_exporter Observability export as a dedicated extension point
(no equivalent) approval_handler The approval gate's handler (§7) as an extension point
(no equivalent) policy_evaluator Opt-in evaluation of validated execution arguments (§7.4.1)
(no equivalent) capability_search_provider Optional ranking of capability candidates (§6.10)
id_converter (not an extension point) Not a common runtime customization need
executor (not an extension point) Local execution covers the supported use cases

Implementations declaring Level 2 conformance use the ExtensionManager names in the table.

11.4 Framework Built-in Middleware

Validation and access control are not middleware. They are steps of the execution pipeline (§7.4): acl_check (Step 4), approval_gate (Step 5), input_validation (Step 7) and output_validation (Step 9). Each of them is removable, through pipeline.remove (§5.16.1) or a custom strategy, and removing acl_check or approval_gate warns (§5.16 requirement 7). context_creation, module_lookup, execute and return_result cannot be removed.

No middleware is installed by default. An implementation installs middleware the application did not register itself only in these cases:

Middleware Installed when
Tracing middleware The loaded configuration sets observability.tracing.enabled: true (§10.1.1)
Usage and error-history middleware sys_modules.enabled: true (§9.15.3)
Platform-notify middleware sys_modules.events.enabled: true (§9.15.3)

Every other middleware an implementation ships — logging, metrics, retry, circuit breaker — is installed by the application with use() (§11.2). See middleware-system.md § Built-in Middleware.

middleware.disabled is deprecated (§9.2.4). It names built-in middleware that are not installed, and no implementation reads it; declaring it warns once per configuration load. Remove a registered middleware with remove(), or a pipeline step with pipeline.remove (D-137).

11.5 Middleware Execution State Machine

Middleware chain execution MUST follow this state machine:

                                     Error branch
  ┌──────┐    ┌────────┐    ┌─────────┐    ┌──────┐    ┌──────┐
  │ init │───▶│ before │───▶│ execute │───▶│ after│───▶│ done │
  └──────┘    └───┬────┘    └────┬────┘    └──┬───┘    └──────┘
                  │              │             │
                  │ abort        │ error       │ error
                  ▼              ▼             ▼
              ┌──────┐    ┌──────────┐    ┌──────┐
              │ done │    │ on_error │───▶│ done │
              └──────┘    └──────────┘    └──────┘

State descriptions:
  init     — Initialize middleware chain, prepare execution context
  before   — Execute all middleware before() in order
  execute  — Execute module's execute() method
  after    — Execute all middleware after() in reverse order
  on_error — Execute all middleware on_error() in reverse order
  done     — Execution complete, return result or error

Rules:
  - before phase: If middleware returns non-None → Use as replacement input
  - before phase: If middleware throws exception → Skip subsequent before and execute, enter on_error
  - after phase: If middleware returns non-None → Use as replacement output
  - on_error phase: If middleware returns non-None → Use as fallback result, stop error propagation

11.6 Extension Point Interface Formalization

Implementations SHOULD support the following extension points. Each supported extension point MUST define a clear interface contract:

Extension Point: SchemaLoader
  load(module_id: String) → Schema
  supports(module_id: String) → Boolean
  priority: Integer

Extension Point: ModuleLoader
  load(module_id: String) → Module
  supports(file_path: String) → Boolean
  priority: Integer

Extension Point: IDConverter
  to_canonical(local_id: String, language: String) → String
  from_canonical(canonical_id: String, language: String) → String

Extension Point: ACLChecker
  check(caller_id: String, target_id: String, context: Context) → Boolean

Extension Point: Executor
  execute(module: Module, method: String, inputs: Map, context: Context) → Map

NOTE: The interface contracts above use the conceptual names. See the mapping table in §11.3 for the ExtensionManager names.

11.7 Extension Loading Order

Extensions are registered in code with ExtensionManager.register(point_name, extension) and wired with apply(registry, executor) (§11.3):

  1. A single-valued point (discoverer, acl, module_validator, approval_handler, policy_evaluator, capability_search_provider) holds one implementation; registering another replaces it.
  2. A multi-valued point (middleware, span_exporter) holds every registered implementation in registration order.
  3. apply() MUST install every registered implementation — the one a single-valued point holds, and each implementation of a multi-valued point in registration order. A point with no registered implementation keeps the framework default.

There is no priority ordering among the implementations of one point, no chaining strategy (first_success, all, fallback), and no registration from apcore.yaml (D-143). Algorithm A16 describes apply().

11.8 Edge Case Handling

Implementations MUST handle middleware edge cases according to the following table:

11.8.1 on_error Cascade

Scenario Behavior Level
on_error() itself throws exception Log ERROR, continue to next on_error() in chain MUST
on_error() returns non-None value Stop propagation, use return value as module final output MUST
on_error() returns None Continue propagating error downward MUST
All on_error() return None Throw original error to caller_id MUST

11.8.2 before() Edges

Scenario Behavior Level
before() returns None Keep inputs unchanged, continue chain MUST
before() returns partial field dict Replace inputs entirely MUST
before() returns non-dict type Throw GENERAL_INTERNAL_ERROR MUST
before() throws ModuleError Trigger on_error() chain, skip module execution MUST
before() modifies context.data Allowed, modifications visible to subsequent middleware and module MUST

11.8.3 after() Edges

Scenario Behavior Level
after() returns None Keep result unchanged, continue chain MUST
after() returns partial field dict Replace result entirely MUST
after() throws ModuleError Trigger on_error() chain, replace original result MUST
after() returns value not matching output_schema Returned as is. output_validation (Step 9) runs before middleware_after (Step 10), so a replacement output from after() is not validated against output_schema (§7.4); a middleware that replaces the output owns its shape MUST
Scenario Behavior Level
before() runs past the global deadline before() is not interrupted. execute (Step 8) checks the deadline before invoking the module and throws MODULE_TIMEOUT; the on_error() chain runs MUST
execute() exceeds its timeout Throw MODULE_TIMEOUT (§12.7.5); the on_error() chain runs MUST
after() runs past the global deadline after() is not interrupted and no MODULE_TIMEOUT is thrown MUST
on_error() is slow on_error() is not timed MUST

Note: - The per-module timeout covers the module's execute() only. The global deadline is set by context_creation (Step 1) and inherited by nested calls, so time spent in Steps 2–7, before() included, consumes it - Timeout enforcement algorithm see §12.7.5 and algorithms.md A22


12. SDK Implementation Guide

12.1 Required Core Components

Component Responsibility Phase
IDConverter Canonical ID ↔ Local ID conversion (class or utility function) Phase 1
SchemaLoader Load file-backed schemas (Configuration Profile) Phase 1
Registry In-memory registration and lookup (Core Profile), external module discovery (Discovery Profile) Phase 1
Executor Module invocation, Schema validation Phase 1
ACLChecker Permission checking Phase 2
MiddlewareManager Middleware management Phase 2
TracingProvider Trace context Phase 2
MetricsCollector Metrics collection Phase 2

12.2 Core Component Interface Contracts

The following interface definitions use language-agnostic pseudocode. An SDK MUST provide equivalent implementations for the requirements of each profile it declares (§1.8).

Interface: IDConverter
  /**
   * Convert language-native ID to Canonical ID
   * @param local_id  — Native format ID (e.g., "executor::validator::db_params")
   * @param language  — Source language identifier (python|rust|go|java|typescript)
   * @return canonical_id — Dot-separated snake_case format
   * @throws INVALID_ID — If local_id doesn't conform to language naming convention
   */
  to_canonical(local_id: String, language: String) → String

  /**
   * Convert Canonical ID to language-native ID
   * @param canonical_id — Dot-separated snake_case format
   * @param language     — Target language identifier
   * @return local_id    — Language-native format
   */
  from_canonical(canonical_id: String, language: String) → String

  /**
   * Implementation Note: SDKs MAY implement IDConverter as a standalone
   * utility function (e.g., normalize_to_canonical_id()) rather than a
   * class, provided the same conversion semantics are satisfied.
   */

Interface: SchemaLoader
  /**
   * Load specified module's Schema definition
   * @param module_id — Canonical ID
   * @return schema   — Parsed Schema object (contains input_schema, output_schema, description)
   * @throws SCHEMA_NOT_FOUND — If Schema file doesn't exist
   * @throws SCHEMA_INVALID   — If Schema format is invalid
   */
  load(module_id: String) → Schema

  /**
   * Validate Schema itself for validity
   * @param schema — Schema object to validate
   * @return errors — Error list, empty list means valid
   */
  validate(schema: Schema) → List<ValidationError>

Interface: Registry
  /**
   * Register a module under a canonical ID.
   *
   * `version` and `metadata` are OPTIONAL parameters an implementation MAY
   * accept; §5.4 governs multi-version coexistence, and resolving BY version
   * remains optional. Accepting the parameters and resolving by version are
   * separate capabilities — see features/registry-system.md
   * § "Multi-version registration".
   *
   * When `metadata` is accepted, a `dependencies` entry — a list of
   * {module_id, version?, optional?} objects — MUST reach the registered
   * module's descriptor as a PARSED field, so that
   * `get_definition(module_id).dependencies` returns what the caller declared
   * in the SDK's dependency type rather than as raw input.
   *
   * Rationale: dependencies are structural data the framework itself consumes
   * for load and reload ordering, not extension metadata. Carrying them only
   * inside the descriptor's `metadata` map — arbitrary extension data — pushes
   * the {module_id, version?, optional?} parse onto every consumer and lets the
   * two views drift apart; dropping them from the descriptor degrades a
   * dependency-ordered reload to its sort's seed order.
   *
   * The ordered side effects, the in-flight reservation and the visibility
   * rule are specified in features/registry-system.md
   * § "Contract: Registry.register".
   *
   * @param module_id — Canonical ID
   * @param module    — Module instance
   * @param version   — Optional declared version (§5.4)
   * @param metadata  — Optional metadata map; `dependencies` MUST survive
   * @throws INVALID_ID          — If module_id fails validation
   * @throws DUPLICATE_MODULE_ID — If module_id is already registered
   */
  register(module_id: String, module: Module, version: String?, metadata: Map?) → void

  /**
   * Scan extension directory, discover and register all modules
   * @param config — Framework configuration
   * @throws EXTENSION_ROOT_NOT_FOUND — If extension root directory doesn't exist
   */
  discover(config: Config) → void

  /**
   * Get specified module
   * @param module_id — Canonical ID
   * @return module   — Module instance
   * @throws MODULE_NOT_FOUND — If module not registered
   */
  get(module_id: String) → Module

  /**
   * List all registered module IDs
   * @return ids — Canonical ID list
   */
  list() → List<String>

  /**
   * Get a human-readable module description (for AI/LLM use).
   *
   * Returns a rendered description STRING, not a structured object: the
   * machine-readable accessor is `get_definition`, which returns the
   * ModuleDescriptor (D-77).
   *
   * A module MAY supply its own `describe()` (§5.6), whose declared return is
   * an introspection MAPPING. An implementation MUST return that override only
   * when it is itself a string, and MUST otherwise fall through to the
   * generated envelope — it MUST NOT stringify the mapping, and MUST NOT
   * return the mapping through an interface declared as returning a string.
   * See features/registry-system.md "Contract: Registry.describe".
   *
   * @param module_id — Canonical ID
   * @return description — Human-readable description string
   * @throws MODULE_NOT_FOUND — No module registered under module_id
   */
  describe(module_id: String) → String

Interface: Executor
  /**
   * Call a module through the execution pipeline.
   *
   * Note: Python exposes this as `call()` (sync) and `call_async()`
   * (async); TypeScript and Rust expose a single asynchronous `call()`.
   * The separate `execute(module_id, method, ...)`
   * signature is folded into `call()` — the executor always runs the
   * module's `execute()` method through the full pipeline.
   *
   * `context` MUST be bound to at most one Executor. When `context.executor`
   * is non-null and refers to a DIFFERENT Executor instance, the call MUST
   * raise `CONTEXT_BINDING_ERROR`. Rationale: a single legal outcome keeps
   * the behaviour assertable by a conformance case.
   *
   * @param module_id — Canonical ID
   * @param inputs    — Input parameters (conform to input_schema)
   * @param context   — Execution context, bound to at most one Executor
   * @return output   — Output result (conform to output_schema)
   * @throws INPUT_VALIDATION_FAILED  — Input validation failed
   * @throws OUTPUT_VALIDATION_FAILED — Output validation failed
   * @throws ACL_DENIED               — Permission denied
   * @throws MODULE_EXECUTION_ERROR   — Module execution exception
   */
  call(module_id: String, inputs: Map, context: Context) → Map

  /**
   * [SHOULD] Non-destructive preflight check over the strategy's pure steps.
   * The standard execution checks are Steps 1–4 and 7. The result also
   * reports the effective approval requirement and any permitted module-level
   * preflight and preview. See §12.8 for the language-specific guide.
   *
   * Runs: context creation (Step 1), call chain guard (Step 2), module
   * lookup (Step 3), ACL enforcement (Step 4), input schema validation
   * (Step 7), and — only when the ACL permitted the call — module.preflight()
   * and module.preview() for advisory warnings and predicted changes
   * (§12.8.5.1).
   *
   * MUST NOT: invoke the module's execute(), run middleware, invoke the
   * ApprovalHandler, or modify external state. The module's own preflight()
   * and preview() are the only module code it runs (§12.8.5.1).
   *
   * All check failures are collected into the result rather than thrown,
   * so the caller_id can see every problem in a single round-trip.
   *
   * @param module_id — Canonical ID
   * @param inputs    — Input parameters to validate
   * @param context   — Optional execution context (for call-chain checks)
   * @return result   — PreflightResult with per-check status
   */
  validate(module_id: String, inputs: Map, context: Context?) → PreflightResult

/**
 * Result of Executor.validate() preflight check.
 *
 * PreflightResult SHOULD be duck-type compatible with ValidationResult
 * (i.e., it has `valid: Boolean` and `errors: List`), so that consumers
 * written against ValidationResult can read it unchanged.
 */
Type: PreflightCheckResult
  check: String              // "executor_binding" | "module_id" | "module_preflight" | "module_preview",
                             // or the check a pure pipeline step reports under: context_creation → "context",
                             // call_chain_guard → "call_chain", module_lookup → "module_lookup",
                             // acl_check → "acl", approval_gate → "approval", input_validation → "schema";
                             // any other pure step (output_validation, return_result, a custom step)
                             // reports under its own step name
  passed: Boolean
  error: Map?                // Error details when passed=false; null when passed=true
  warnings: List<String>     // Non-fatal advisory messages (default: empty list)

Type: Change
  action: String             // Free-form verb describing the kind of change (e.g. "write", "delete", "send", "charge")
  target: String             // Free-form identifier of what is changed (e.g. "users.42", "stripe:charge:ch_abc")
  summary: String            // Human-readable single-line summary (REQUIRED — floor for destructive modules)
  before: Any?               // Optional snapshot of prior state; OMIT for unobservable side effects
  after: Any?                // Optional predicted new state; OMIT when unknown (e.g. server-assigned IDs)
  // x-* extension fields permitted (consistent with §4.6 conventions); no other
  // key is permitted. Encoding and round-trip rules: §12.8.5.1.

Type: PreviewResult
  changes: List<Change>      // REQUIRED. Module's prediction of what would change if the call were executed, in order

Type: PreflightResult
  valid: Boolean             // True only if ALL checks passed
  checks: List<PreflightCheckResult>
  requires_approval: Boolean // Governance-effective approval requirement for this call — §7.9.5
  predicted_changes: List<Change>  // Populated from the module's preview() by Executor.validate() (default: empty list).
                                   // ALWAYS empty when the acl check failed — §12.8.5.1

Interface: ACLChecker
  /**
   * Check invocation permission
   * @param caller_id — Caller module ID or identity
   * @param target_id — Target module ID
   * @param context   — Execution context
   * @return allowed  — Whether allowed
   */
  check(caller_id: String, target_id: String, context: Context) → Boolean

Interface: MiddlewareManager
  /**
   * Register middleware
   * @param middleware  — Middleware instance
   *
   * Note: Priority is explicit (0-1000, higher executes first), as defined
   * in §11.2. Registration order is used only as a tiebreaker when two
   * middleware have equal priority. Execution follows the onion model.
   */
  add(middleware: Middleware) → void

  /**
   * Execute middleware chain in priority order.
   *
   * SDKs MAY implement this as a single run_chain() method or as
   * separate phase methods (execute_before, execute_after, execute_on_error)
   * called by the Executor at the appropriate pipeline steps. Both
   * approaches are conformant provided the onion-model execution order
   * is preserved.
   */
  run_chain(module_id: String, inputs: Map, context: Context, next: Function) → Map

Interface: TracingProvider
  /**
   * Create new Span
   * @param name       — Span name (follows §10.8 naming convention)
   * @param context    — Execution context (contains trace_id, parent_span_id)
   * @return span      — Span object
   */
  start_span(name: String, context: Context) → Span

  /**
   * End Span and record result
   * @param span       — Span to end
   * @param attributes — Additional attributes
   */
  end_span(span: Span, attributes: Map) → void

Interface: MetricsCollector
  /**
   * Record counter metric
   * @param name   — Metric name
   * @param labels — Label key-value pairs
   * @param value  — Increment value (default 1)
   */
  increment(name: String, labels: Map, value: Integer) → void

  /**
   * Record histogram metric
   * @param name   — Metric name
   * @param labels — Label key-value pairs
   * @param value  — Observed value
   */
  observe(name: String, labels: Map, value: Float) → void

Cross-Language Naming Conventions

The protocol specification uses snake_case for canonical definitions. Each language SDK MUST translate to its native naming convention:

Protocol (canonical) TypeScript Python Rust
module_id moduleId module_id module_id
input_schema inputSchema input_schema input_schema
output_schema outputSchema output_schema output_schema
get_definition() getDefinition() get_definition() get_definition()
call_async() — (call() is asynchronous) call_async() — (call() is asynchronous)
requires_approval requiresApproval requires_approval requires_approval
open_world openWorld open_world open_world

An implementation in another language applies the same rule: the canonical name in that language's idiomatic casing.

Rule: Bridge/adapter packages (e.g., apcore-mcp-typescript) MUST use the same naming conventions as their language's core SDK. A TypeScript MCP bridge MUST use camelCase to match apcore-typescript, not snake_case from the protocol spec.

Standard Registry Event Names

The registry event set is closed (D-80). Registry implementations MUST support register and unregister, and MUST support file_changed when their watch() emits it:

Event Name Triggered Callback Signature
"register" After module successfully registered (module_id, module) -> None
"unregister" Before module is removed (module_id, module) -> None
"file_changed" A watched file changed and watch() does not re-register the module itself (module_id, {file_path}) -> None

An implementation whose watch() re-registers the module emits unregister / register and MUST NOT also emit file_changed for the same change. on / off MUST reject any event name the implementation does not support with GENERAL_INVALID_INPUT. The full contract is in registry-system.md § Registry events.

All SDKs MUST export the event names they support as named constants (e.g., TypeScript: REGISTRY_EVENTS.REGISTER, Python: REGISTRY_EVENTS["REGISTER"], Rust: RegistryEvents::REGISTER). Consumers MUST NOT hardcode event name strings.

Error Code Constants Export Requirement

All SDKs MUST export the framework error codes defined in Section 8 as enumerated constants. This prevents magic string dependencies and enables IDE autocomplete.

Example (TypeScript):

export const ErrorCodes = {
  MODULE_NOT_FOUND: "MODULE_NOT_FOUND",
  SCHEMA_VALIDATION_ERROR: "SCHEMA_VALIDATION_ERROR",
  // ... all codes from Section 8
} as const;

Context Factory Protocol

For web framework integrations (Django, Flask, FastAPI, NestJS, Express), SDKs SHOULD provide a ContextFactory protocol:

Protocol ContextFactory:
    create_context(request: Any) -> Context

This enables framework-specific context creation (e.g., extracting Identity from Django request.user, JWT tokens, or API keys) without coupling apcore core to any web framework.

The lifecycle is: request arrives → ContextFactory.create_context(request) → Executor.call(module_id, inputs, context) → response.

Streaming Execution Protocol

Modules MAY support incremental output by implementing a stream method alongside the required execute method:

stream(inputs, context) → AsyncIterable<Record>

Semantics:

  • Each yielded record is a partial result chunk; the framework does not prescribe chunk structure.
  • The complete result is the recursive deep merge of all yielded chunks. Implementations MUST recurse into nested objects and MUST replace (not concatenate) arrays at matching keys. Recursion depth MUST be capped to prevent stack exhaustion via adversarial chunk shapes; the canonical default is 32. See ./algorithms.md §A24 deep_merge_chunks for pseudocode and ../../conformance/fixtures/stream_aggregation.json for the cross-language test cases.
  • execute() MUST remain implemented as the non-streaming fallback.
  • Module descriptors SHOULD declare annotations.streaming = true when stream() is provided.

Executor.stream() pipeline:

  1. Steps 1–7 identical to call(): context creation, call chain guard, module lookup, ACL, approval gate, before-middleware, input validation.
  2. If module lacks stream(): fall back to call(), yield single chunk, return.
  3. Iterate module.stream(inputs, context), yield each chunk to caller.
  4. After all chunks: validate accumulated output against output_schema, run after-middleware on accumulated result.

Cross-language signatures:

Language Executor method signature
TypeScript async *stream(moduleId, inputs?, context?, versionHint?): AsyncGenerator<Record<string, unknown>>
Python async def stream(module_id, inputs?, context?, version_hint?) -> AsyncIterator[dict[str, Any]]
Rust fn stream(&self, module_id: &str, inputs: Value, ctx: Option<&Context<Value>>, version_hint: Option<&str>) -> Pin<Box<dyn Stream<Item = Result<Value, ModuleError>> + Send + '_>>

MCP bridge behavior:

When bridging Executor.stream() to MCP, implementations SHOULD use the standard notifications/progress mechanism:

  1. Client includes _meta.progressToken in the tools/call request to opt into streaming.
  2. Server calls Executor.stream() and for each yielded chunk, sends notifications/progress with message containing the JSON-serialized chunk.
  3. The final CallToolResult contains the complete accumulated result.
  4. If the client does not provide progressToken, the bridge accumulates internally and returns an atomic result.

12.3 Cross-language Implementation Requirements

All SDK implementations MUST satisfy the following requirements regardless of language:

Requirement Level
JSON Schema Draft 2020-12 validation MUST
YAML parsing MUST
Directory as ID MUST
ID Map cross-language conversion MUST
ACL engine MUST
Middleware onion model MUST
Structured logging MUST
Error code specification MUST
OpenTelemetry integration SHOULD
Executor.validate() preflight SHOULD

12.4 Consistency Testing Requirements

Each SDK implementation MUST pass the following consistency test suite to ensure cross-language behavior consistency:

Consistency Test Suite:

1. ID Conversion Tests:
   - Directory path → Canonical ID (10+ cases, including edge cases)
   - Cross-language ID conversion (5+ cases per language)
   - Invalid ID detection (format errors, too long, reserved words)

2. Schema Validation Tests:
   - Valid input passes validation
   - Invalid input rejected (type error, missing field, extra field)
   - x-sensitive field marking recognition
   - $ref reference resolution (including circular reference detection)

3. ACL Tests:
   - Wildcard matching (`*` matches any run of characters, `.` included — Algorithm A08)
   - First-match-wins evaluation: rule order, not effect, decides
   - Default policy takes effect
   - Identity type matching (user, service, agent, api_key, system)

4. Middleware Tests:
   - Onion model execution order
   - before phase modifying input
   - after phase modifying output
   - on_error phase fallback handling
   - Priority sorting correctness

5. Executor Tests:
   - Normal execution flow in pipeline order (ACL → approval → before-middleware → input validation → execute → output validation → after-middleware)
   - Error propagation and error codes
   - Context propagation (trace_id, call_chain)
   - Circular call detection
   - Call depth limiting

6. Observability Tests:
   - trace_id is valid 32-char lowercase hex
   - Sensitive data redaction
   - Structured log format

7. Preflight (validate) Tests:
   - Valid module + valid inputs → PreflightResult.valid=true, all checks passed
   - Invalid module_id format → module_id check failed; the later checks still run (§12.8.1 principle 2)
   - Unknown module → module_lookup check failed; no schema / module_preflight / module_preview check
   - ACL denial → acl check failed, valid=false
   - ACL denial and invalid inputs → both the acl and the schema check fail; checks that passed before them stay reported
   - ACL denial → NO module_preflight / module_preview check, predicted_changes empty (§12.8.5.1)
   - Module with requires_approval → requires_approval=true; the ApprovalHandler is not invoked
   - Schema validation failure → schema check failed with error details
   - PreflightResult.errors matches filtered failed checks (duck-type ValidationResult)
   - validate() MUST NOT invoke the module's execute() or run middleware

12.5 Implementation Roadmap

Phase 1: Core MVP
├── IDMap (Directory as ID + cross-language conversion)
├── SchemaLoader (YAML → language-native Schema)
├── Registry (directory scanning, registration)
└── Executor (invocation, validation)

Phase 2: Core Complete
├── ACLChecker (permission checking)
├── MiddlewareManager (middleware)
├── ErrorHandler (error handling)
└── ObservabilityProvider (tracing, logging, metrics)

Phase 3: CLI & DX
├── CLI tools (init, create, run)
├── Schema validation tools
└── Developer documentation

Phase 4: Advanced
├── Module hot reloading
├── OpenTelemetry integration
└── Performance optimization

12.6 Language-specific Guidelines

Each SDK implementation SHOULD use the idiomatic schema validation, async model, and package management conventions of its target language. Specific library choices are documented in each SDK's own repository.

12.7 Concurrency Model Specification

This section defines apcore's concurrency model and thread safety requirements, ensuring SDK implementers correctly implement the framework in multi-threaded/coroutine environments.

12.7.1 Module Instance Lifecycle

Singleton Model (MUST):

  • Each module_id MUST correspond to unique module instance (singleton)
  • Instance created at discover() or first invocation, destroyed at unregister() or app shutdown
  • on_load() hook MUST be called only once during instance lifecycle

Reentrancy (MUST):

  • execute() method MUST support concurrent reentrant calls (thread-safe)
  • Module internal state (if any) SHOULD use thread-safe mechanisms (locks, atomic variables, etc.) for protection
  • Implementations MUST NOT assume execute() calls are serial

Example — Thread-safe counter module:

# Python example (similar for other languages)
import threading

class CounterModule:
    def __init__(self):
        self._count = 0
        self._lock = threading.Lock()

    def on_load(self, context):
        # Called only once
        print("Counter module loaded")

    def execute(self, inputs, context):
        # Multi-thread safe
        with self._lock:
            self._count += 1
            return {"count": self._count}

Lifecycle Guarantees:

Phase Call Count Concurrency Description
__init__() 1 time Single-thread Instance creation
on_load() 1 time Single-thread Module initialization
on_resume(state) 0..1 time Single-thread Restore state from previous instance (hot-reload only)
execute() 0..N times Multi-thread Business logic
on_suspend() 0..1 time Single-thread Export state before hot-reload
on_unload() 0..1 time Single-thread Resource cleanup

Note: During hot-reload, on_suspend() and on_unload() run on the old instance; on_resume(state) runs on the new instance after its on_load(). Full sequence: old.on_suspend() → old.on_unload() → new.__init__() → new.on_load() → new.on_resume(state).

12.7.2 Context.data Sharing Semantics

Reference Sharing (MUST):

  • context.data MUST be the same dict/Map object across entire call chain (reference sharing)
  • Parent module modifications to context.data visible to child modules, vice versa
  • When child() creates new Context, data field MUST copy reference (not deep copy)

Isolation (MUST):

  • Different top-level call() invocations MUST use independent context.data instances
  • Concurrently executing call chains MUST NOT share context.data (avoid race conditions)

Example — Context.data Sharing:

# Top-level calls
context1 = Context(data={})
executor.call("module_a", {}, context1)  # context1.data independent

context2 = Context(data={})
executor.call("module_b", {}, context2)  # context2.data independent

# Sharing within call chain
# module_a.execute():
context.data["key"] = "value"  # Write
sub_context = context.child("module_c")
executor.call("module_c", {}, sub_context)

# module_c.execute():
print(context.data["key"])  # Reads "value" (reference sharing)

Concurrent Access Protection (SHOULD):

  • If context.data might be accessed by multiple threads (e.g., async middleware), SHOULD use thread-safe Map implementation
  • Python's dict is partially thread-safe in CPython (GIL protected), but SHOULD avoid relying on implementation details

12.7.3 Hot Reload with State Migration

State Migration Hooks (MAY):

Modules that hold in-memory state (counters, caches, connection pools) can implement on_suspend() / on_resume() to preserve state across hot-reload cycles:

Hot-Reload Sequence:
  1. old_instance.on_suspend() → state (dict or null)
  2. old_instance.on_unload()
  3. (reload module code from disk)
  4. new_instance.__init__()
  5. new_instance.on_load()
  6. If state is not null: new_instance.on_resume(state)

Constraints: - on_suspend() return value MUST be JSON-serializable (no functions, connections, file handles) - on_resume() MUST tolerate missing or extra keys (new version may have different state shape) - If on_suspend() raises, log ERROR and proceed with unload (state is lost) - If on_resume() raises, log ERROR and continue (module starts with fresh state) - Framework MUST NOT call on_resume() if on_suspend() returned null or was not implemented

# Example: Counter module with state preservation
class CounterModule(Module):
    def on_load(self):
        self._count = 0
        self._cache = {}

    def on_suspend(self) -> dict | None:
        """Export state before hot-reload"""
        return {"count": self._count, "cache": self._cache}

    def on_resume(self, state: dict) -> None:
        """Restore state after hot-reload"""
        self._count = state.get("count", 0)
        self._cache = state.get("cache", {})

    def execute(self, inputs, context):
        self._count += 1
        return {"count": self._count}

12.7.4 Hot Reload Race Conditions

Problem: During unregister(), module might be executing in other threads.

This section defines the compatibility unregister() entry point. The opt-in managed operations use the policies in §12.7.9.

Safe Unload Algorithm (MUST):

Algorithm: safe_unregister(module_id, registry)

Steps:
  1. Mark module as "unloading" state
  2. Remove from registry (new call() will throw MODULE_NOT_FOUND)
  3. Wait for all executing calls to complete:
     - Maintain reference count (number of executing calls)
     - Block until count reaches zero or timeout (default 5 seconds)
  4. Call on_suspend() hook (if implemented) → save returned state
  5. Call on_unload() hook
  6. Release module instance

Return:
  - If successfully unloaded → true, state (dict or null)
  - If timeout → Log ERROR, force unload, return false, null

For detailed algorithm see algorithms.md A21 — safe_unregister()

Operation Concurrency Table:

Operation A Operation B Behavior Description
call() unregister() If A already started execution, continue to completion; if not started, throw MODULE_NOT_FOUND MUST
register() register() same ID Latter throws DUPLICATE_MODULE_ID MUST
unregister() unregister() same ID Idempotent, succeed silently MUST
get() unregister() If get executes first, return instance; if unregister executes first, throw MODULE_NOT_FOUND SHOULD

12.7.5 Timeout Enforcement

Timeout Levels:

Level Scope Default Configuration
Per-module timeout The module's execute() (Step 8) 30000ms The module's declared resources.timeout, else executor.default_timeout
Global deadline The whole call tree, from context_creation (Step 1) of the root call 60000ms executor.global_timeout; set on the Context at Step 1 when it carries none, inherited by nested calls

The per-module timeout is clamped to the time left before the global deadline. 0 disables either limit. ACL evaluation and schema validation are not separately timed.

Timeout Enforcement Algorithm (MUST):

Algorithm: enforce_timeout(module_id, inputs, context, timeout_ms)

Input:
  context    — the call's own Context; context.cancel_token is the call's own
               token, a child of its caller's (requirement 4)
  timeout_ms — the per-module timeout, clamped to the time left before
               context.global_deadline

Steps:
  1. If context.global_deadline has passed:
     a. Cancel context.cancel_token
     b. Throw MODULE_TIMEOUT without invoking the module
  2. Invoke module.execute(inputs, context) and start a timer of timeout_ms
  3. If execute() completes first → Cancel the timer, return its result
  4. If the timer fires first:
     a. Cancel context.cancel_token
     b. Throw MODULE_TIMEOUT

Return:
  - Success → Module output
  - Failure → MODULE_TIMEOUT error

For detailed algorithm see algorithms.md A22 — enforce_timeout()

Requirements:

  1. When the timer fires, or the global deadline has passed, implementations MUST throw MODULE_TIMEOUT immediately. They MUST NOT wait for the module to exit; there is no grace period (D-133).
  2. Implementations MUST cancel the timed-out call's own cancel_token before throwing MODULE_TIMEOUT, so a module that checks its token stops its work (D-133).
  3. There is no forced termination. A module that ignores its token may keep running after its caller has received MODULE_TIMEOUT; what it returns is discarded (D-133).
  4. Every call MUST receive its own cancel_token, a child of its caller's token: the token of the calling module's Context for a nested call, and for a root call the token the application supplied to Context.create (§5.7), when it supplied one. Cancelling a token MUST cancel every token derived from it, and cancelling a child MUST NOT cancel its parent. A timeout therefore cancels the timed-out call and the calls beneath it, never its caller: a nested call's MODULE_TIMEOUT reaches the calling module as an error it can catch, and the caller continues (D-133).
  5. A call whose cancel_token is already cancelled when execute (Step 8) is reached MUST NOT invoke the module and throws EXECUTION_CANCELLED (§8.2).

Cooperative cancellation. A long-running module SHOULD check its Context's cancel_token and exit when it is cancelled.

12.7.6 Middleware Chain Atomicity

Call-level Isolation (MUST):

  • Each call()'s middleware chain execution MUST not interleave with other call()'s chain execution
  • Middleware chain's before → execute → after sequence MUST complete atomically (not interrupted by other calls)

Instance Sharing (MUST):

  • Middleware instances shared at application level (similar to module singleton)
  • Middleware MUST be thread-safe, support concurrent calls

Example — Middleware Concurrent Execution:

Thread 1: before1 → before2 → execute(A) → after2 → after1
Thread 2:                before1 → before2 → execute(B) → after2 → after1
                       ↑ Interleaving allowed (different calls)

# Forbidden:
Thread 1: before1 → before2 → [interrupted by Thread 2]
Thread 2:                      before1 → ...

State Isolation (SHOULD):

  • Middleware SHOULD store call-level state through context.data (e.g., request ID, timer)
  • MUST NOT use middleware instance variables to store call-level state (causes race conditions)

12.7.7 Sync/Async Mixing

Bridging Strategy (MUST):

Implementations MUST support mixed calls of sync and async modules, bridging according to these rules:

Caller Called Module Bridging Strategy Description
Sync Sync Direct call No overhead
Sync Async Block and wait (await) Sync caller_id blocks until async completes
Async Sync Thread pool offload Avoid blocking event loop
Async Async Direct await No overhead

Language Mapping:

Language Sync Model Async Model Bridging Mechanism
Python Regular function async def asyncio.run() / run_in_executor()
TypeScript Blocking code (rare) Promise / async/await Direct await (JavaScript is async by default)
Rust Regular function async fn block_on() / spawn_blocking()

An implementation in another language applies the same four bridging rules with its own primitives.

Performance Considerations:

  • Sync→Async bridging blocks caller_id thread, SHOULD avoid frequent use in async contexts
  • Async→Sync bridging needs thread pool, SHOULD configure reasonable thread pool size (default CPU cores × 2)

12.7.8 Resource Cleanup Guarantees

Implementations MUST guarantee resource cleanup according to this table:

Exit Scenario on_unload() Called finally Block Executed File/Network Closed Memory Released Level
Normal completion ✅ Called ✅ Executed ✅ Guaranteed ✅ GC reclaimed MUST
Timeout (cooperative cancel) ✅ Called ✅ Executed ✅ Guaranteed ✅ GC reclaimed MUST
Process crash/kill ❌ Not called ❌ Not executed ❌ Leak ❌ Lost N/A

Best Practices:

  • Modules SHOULD use RAII (Resource Acquisition Is Initialization) pattern to manage resources
  • SHOULD acquire resources in on_load(), release in on_unload()
  • SHOULD avoid opening long-term resources in execute() (e.g., database connections), use connection pools instead

Example — Resource Cleanup:

class DatabaseModule:
    def on_load(self, context):
        self.pool = create_connection_pool()  # Long-term resource

    def execute(self, inputs, context):
        with self.pool.get_connection() as conn:  # Short-term resource, auto-released
            return conn.query(inputs["sql"])

    def on_unload(self):
        self.pool.close()  # Cleanup long-term resource

12.7.9 Managed Module Lifecycle

Managed lifecycle operations bind each selected module ID to its loaded generation (D-153). An owned operation MUST continue when a caller stops waiting or its wait budget expires. An expired wait MUST return a snapshot, including pending phases. Clients sharing a Registry MUST join the same Registry shutdown and run teardown once per generation. Each client owns its event flush budget and outcome.

The host interfaces use independent monotonic budgets measured in integer milliseconds from 0 through 2147483647. A wait budget is optional and applies to one waiter. A drain budget applies to one generation and defaults to 5000 ms. A batch's optional operation budget limits dispatch and caps each entry's drain wait by the remaining time. The coordinator MUST report an entry that was never dispatched as not_started and continue to account for any started entry. A shutdown event flush budget defaults to 5000 ms and applies to one client's delivery stage. An explicit cancellation grace applies only to cancel_then_force and defaults to 1000 ms.

When managed shutdown, removal, or reload starts draining a generation, the Registry MUST close admission before invoking the optional drain hook. Existing invocations retain their leases during the drain. The hook receives the operation ID, module ID, reason (shutdown, unregister, or reload), a monotonic remaining-time query, and a hook-scoped cancellation signal. A successful drain requires both hook settlement and release of the existing leases. If the deadline expires while the hook is active, the Registry MUST signal that hook and await its settlement before recovery, suspension, or unload. Expiry of a caller's wait budget MUST NOT signal the hook or cancel the operation. A continue_waiting policy treats drain expiry as an observation threshold and keeps draining. A host that explicitly chooses cancel_then_force authorizes the Registry to signal only the admitted invocations of the retiring generation when drain time expires. The Registry waits up to the configured grace for lease release before unloading, and MUST report any remaining leases at unload. The coordinator MUST keep tracking those executions and their finalizers until settlement. The cancellation signal MUST NOT propagate to the parent invocation or other generations.

For managed reload, a drain-hook failure or an expired deadline under abort_reload selects recovery before on_suspend or on_unload. If both observations first occur together, drain failure takes priority. A module providing a drain hook MUST also expose the paired recovery hook to participate in managed reload. The Registry MUST validate the selected capabilities before closing admission and recheck generation ownership before acting. Recovery receives the operation ID, module ID, a fresh hook signal, and the abort reason drain_timeout or drain_error. Admission MUST stay closed until recovery completes successfully and the same generation still owns the ID in an open Registry. A recovery failure leaves the old generation unavailable for calls and available for explicit cleanup. The original generation keeps its in-memory state and skips on_load during this pre-unload recovery.

After a successful reload drain, existing suspend, unload, load, and resume hooks retain their order and semantics (§12.7.3 and §12.7.4). The replacement MUST NOT accept calls before load and applicable resume have settled. The Registry MUST check that it still owns the replacement slot and is open before publishing. A replacement load failure after detaching the old generation follows D-112 compensation, including a new on_load on the old instance before republishing it. A managed report records primary failure and compensation separately. Async hook adapters MUST preserve sequencing and admission boundaries when a hook awaits.

The optional lifecycle input of system.control.reload_module is a closed object with these fields. Normal Executor ACL, approval, validation, and audit apply.

Field Type Default Meaning
drain_timeout_ms Integer from 0 through 2147483647 5000 Per-generation drain deadline in milliseconds.
on_drain_timeout abort_reload or continue_waiting abort_reload Recover the original generation or continue draining.

The Executor MUST preserve invocation errors, including absent exact selectors, conflicting selectors, failed governance, and invalid lifecycle options. A request selecting a module with an unpaired drain hook MUST fail with GENERAL_INVALID_INPUT before admission changes. Omitting lifecycle preserves the existing wire result and RELOAD_FAILED semantics. For an accepted managed reload, a terminal failure MUST return normal output with success: false and lifecycle_report. A successful or no-match operation MUST return success: true and lifecycle_report. Single-module output carries the exact module_id. Bulk output carries module_id: null and lists only successfully replaced IDs in reloaded_modules. A failure for one bulk target MUST NOT prevent attempts on subsequent targets. The report follows ../../schemas/sys-control-reload-module.schema.json, includes a stable operation ID, an ordered row for each selected generation, and records event_flush as not_applicable. A timed-out Executor invocation keeps its regular invocation error. The owned operation continues after the caller stops waiting. Reports and lifecycle event data MUST NOT include call inputs, migration state, cancellation tokens, or hook exception text.

An enabled EventEmitter uses the canonical events in §9.16.2. The Registry emits drain start after admission closes, timeout after the deadline wins, recovery after its disposition is known, and replacement failure after any compensation settles. It MUST emit each transition at most once per operation and generation. Module events use the event envelope's module_id. Each participating client MUST emit its resources-completed event once to its own enabled emitter before shutting it down. That event carries the shared Registry operation ID, and each client report records its own event flush outcome. The Registry.on() callback set remains the closed set in D-80.

12.8 Executor.validate() Cross-Language Implementation Guide

The validate() preflight method (§12.2, SHOULD level) evaluates the strategy's pure steps. The standard execution checks are context creation, call-chain guard, module lookup, ACL, and input validation (Steps 1–4 and 7). The approval gate is impure and is skipped. requires_approval reports the governance-effective requirement without consulting the ApprovalHandler or requesting, resuming, or recording an approval decision. The invocation pipeline performs that decision on a formal call. Preflight can also run the optional module-level preflight() and preview() of §12.8.5.1 when ACL permits disclosure.

With an installed policy evaluator, a successful ACL and schema traversal also evaluates post_validation_policy (Step 7.5) and unions its approval requirement into the report. The optional module callbacks require that policy authorizes disclosure (§7.4.1).

12.8.1 Design Principles

  1. Collect, don't throw. All check failures are appended to a checks list. The caller_id sees every problem in one call.
  2. Every check runs. validate() evaluates each pure step and records its check whatever an earlier check reported: a failing check does not stop the checks after it, and a check that passed is never dropped because a later one failed. A check that needs the module — schema, module_preflight, module_preview — is not recorded when module_lookup failed, because there is nothing to check; the one other exception is principle 5 (D-134).
  3. Reuse existing internals. validate() calls the same helper functions used by the call() pipeline (regex check, registry lookup, ACL check, schema validation). No new capabilities are required.
  4. Duck-type compatibility. PreflightResult SHOULD expose .valid (Boolean) and .errors (List) so consumers written against ValidationResult can read it unchanged.
  5. Authorization gates disclosure. A failed acl check does not stop the checks the Executor computes on its own, but it MUST stop module-level introspection — see §12.8.5.1. validate() is a preflight, not a way around the ACL.

Implementations MUST follow principle 2: a PreflightResult reports every check the dry run could evaluate, passed and failed, in pipeline order (D-134).

12.8.2 Error Handling Mapping

Each check in validate() calls the same helper functions used by the call() pipeline. Failures are appended to the checks list rather than thrown/returned immediately.

Error Model Pattern
Exception-based (try/catch) try { helper(); push(passed) } catch(e) { push(failed, e) }
Error-return (Rust) match helper() { Ok(_) => push(passed), Err(e) => push(failed, e) }

Note: Error-return patterns are more natural than try/catch for this "collect all errors" flow.

12.8.3 PreflightResult Type

PreflightResult MUST contain the following fields:

Field Type Description
valid boolean true if all checks passed
checks list of PreflightCheckResult Ordered list of check results
requires_approval boolean Whether the call requires approval — the governance-effective value of §7.9.5
predicted_changes list of Change Changes predicted by the module's preview() (§12.8.5.1), in order. Always present: an empty list when none were predicted, never omitted or null, in memory and when serialized (D-141)
errors (computed) list of error objects Filtered view: only checks where passed is false

12.8.4 PreflightCheckResult Type

PreflightCheckResult MUST contain the following fields:

Field Type Description
check string Check name (e.g., "module_id", "acl", "schema", "module_preflight", "module_preview")
passed boolean Whether the check passed
error error object or null Error details when passed is false
warnings list of strings Non-fatal advisory messages (default: empty list)

12.8.5 Schema Validation

validate() Check 6 (schema) reuses the same JSON Schema validation that call() Step 7 already performs. No additional schema library is required beyond what the SDK already uses.

12.8.5.1 Module-Level Preflight (Check 7)

After schema validation, validate() MAY invoke the module's optional preflight(inputs, context) method (§5.6). This check is advisory:

  • If preflight() returns a non-empty list of strings, they are stored as warnings on a module_preflight check result with passed: true.
  • If preflight() returns an empty list, a module_preflight check result with passed: true and no warnings is added.
  • If the module does not define preflight(), no module_preflight check is added. An implementation whose language cannot tell a default method from an implemented one MAY instead add a module_preflight check with passed: true and no warnings (D-141).
  • If preflight() raises an exception, the exception is caught and reported as a warning (not a failure).

Module-level preview (module_preview). After preflight(), validate() invokes the module's optional preview(inputs, context) method (§5.6) when the module implements it. This check is advisory, and it never fails validation:

  • If preview() returns a PreviewResult, its changes become predicted_changes, in the order returned, and a module_preview check result with passed: true is added.
  • If the module does not implement preview(), or preview() returns null, predicted_changes is empty and no module_preview check is added (D-141).
  • If preview() raises — a synchronous throw, an asynchronous rejection, or a panic — the exception is caught and reported as a warning on a module_preview check result with passed: true, and predicted_changes is empty.
  • preview() is invoked for a streaming module exactly as for any other: it predicts side effects, not output.
  • Implementing preview() does not set or imply the x-supports-dry-run convention (§4.6); the two are independent signals.

Change records. action, target and summary are required strings. action and target are free-form — module authors define their own taxonomy. summary is the floor: even a module wrapping an opaque external API can produce {action: "send", target: "smtp:[email protected]", summary: "Send order confirmation email to [email protected]"}. before and after are optional and module-class specific; they are omitted when the prior state is unobservable or the new state is unknown.

A Change MAY carry any number of additional keys matching ^x-, with arbitrary values; any other key that is not a declared field is invalid. Implementations MUST preserve x-* keys when a Change is serialized and deserialized: a Change carrying x-foo round-trips with that key and value unchanged. Each SDK uses its idiomatic encoding for this — for example, an extra-allowing model with a prefix check, a flattened map, or a schema with patternProperties: {"^x-": {}} and additionalProperties: false.

Authorization gates module-level introspection

preflight() and preview() (§5.6) are module-authored code, and what they return describes what calling the module would do — the target a side effect would land on, the argv a command-wrapping module would execute, the records a query would touch. When the acl check has failed, validate() MUST NOT:

  • invoke the module's preflight() or preview() method,
  • emit a module_preflight or module_preview check result, or
  • populate predicted_changes — it MUST be empty.

Everything else keeps the collect-don't-throw behaviour of §12.8.1. The failed acl check itself MUST still be reported, so the caller learns why the preflight came back invalid, and the checks the Executor computes on its own (schema, call_chain, module_lookup) are unaffected. What is withheld is exactly the part a denied caller has no authority to learn.

The rule is about authorization, not about validity in general. A failed schema check does not suppress module-level introspection: a caller the ACL permits is a caller entitled to hear what the module would do, even when its inputs are malformed. requires_approval likewise does not suppress it — an approval gate means the caller is authorized and awaiting a human decision, which is precisely the decision predicted_changes exists to inform.

12.8.6 Naming Convention

Follow each language's idiomatic casing for PreflightCheckResult and PreflightResult fields:

Field (Protocol) Python TypeScript Rust
check check check check
passed passed passed passed
error error error error
valid valid valid valid
checks checks checks checks
requires_approval requires_approval requiresApproval requires_approval
predicted_changes predicted_changes predictedChanges predicted_changes
errors (computed) errors (property) errors errors()

Convention: An implementation in another language follows the same rule: the protocol field name in that language's idiomatic casing.


13. Versioning

13.1 Version Number Specification

{major}.{minor}.{patch}[-{prerelease}]

major: Incompatible API changes
minor: Backward-compatible feature additions
patch: Backward-compatible bug fixes
prerelease: draft, alpha, beta, rc

13.2 Compatibility Promise

  • Within major version: Protocol backward compatible
  • Schema evolution: Support version declaration, old version Schema readable by new SDK
  • Deprecation policy: Keep at least 2 minor versions for deprecation period

13.3 Version Negotiation Algorithm

When SDK loads configuration or Schema, MUST perform version negotiation:

Algorithm: negotiate_version(declared_version, sdk_version)

Input:
  declared_version — Version declared in configuration/Schema (e.g., "1.2.0")
  sdk_version      — Current SDK's supported highest version (e.g., "1.3.0")

Output:
  effective_version — Effective version number, or throw VERSION_INCOMPATIBLE error

Steps:
  1. Parse declared_version as (major_d, minor_d, patch_d)
  2. Parse sdk_version as (major_s, minor_s, patch_s)
  3. If major_d ≠ major_s:
     → Throw VERSION_INCOMPATIBLE ("Major version incompatible")
  4. If minor_d > minor_s:
     → Throw VERSION_INCOMPATIBLE ("SDK version too low, please upgrade")
  5. If minor_d < minor_s:
     → Issue DEPRECATION_WARNING (if minor_s - minor_d > 2)
     → effective_version ← declared_version (backward compatibility mode)
  6. If minor_d == minor_s:
     → effective_version ← max(declared_version, sdk_version)
  7. Return effective_version

13.4 Schema Migration

When Schema version changes, implementations SHOULD support automatic migration:

Algorithm: migrate_schema(schema, from_version, to_version)

Input:
  schema       — Original Schema object
  from_version — Original version number
  to_version   — Target version number

Output:
  migrated_schema — Migrated Schema, or throw MIGRATION_FAILED error

Steps:
  1. If from_version == to_version → Return schema (no migration needed)
  2. migration_path ← Find migration path from from_version to to_version
     (e.g., 1.0 → 1.1 → 1.2, each step has corresponding migration function)
  3. If migration_path empty → Throw MIGRATION_FAILED ("No available migration path")
  4. current_schema ← deep_copy(schema)
  5. For each (step_from, step_to, migrate_fn) in migration_path:
     a. current_schema ← migrate_fn(current_schema)
     b. Validate current_schema conforms to step_to version's Schema specification
     c. If validation fails → Throw MIGRATION_FAILED with step info
  6. Return current_schema

Migration types:
  - add_field:     Add field (provide default value)
  - rename_field:  Rename field (keep old name as alias)
  - remove_field:  Remove field (mark as deprecated for at least 2 minor versions)
  - change_type:   Type change (only allowed in major version changes)

13.5 Backward/Forward Compatibility Matrix

Change Type Backward Compatible Forward Compatible Version Impact Description
Add optional field Yes Yes patch/minor New SDK ignores unknown fields, old SDK uses defaults
Add required field No No major Old SDK can't provide new required field
Remove optional field Yes No minor Old SDK passes removed field, new SDK ignores
Remove required field Yes No minor Old SDK still passes field, new SDK ignores
Expand field type (e.g., string → string|number) Yes No minor Old SDK only sends string, new SDK accepts more types
Narrow field type (e.g., string|number → string) No Yes major Old SDK might send number, new SDK rejects
Add error code Yes No minor Old SDK might not recognize new error code
Remove error code No Yes major Old SDK's dependent error code disappears
Add extension point Yes Yes minor Doesn't affect existing extension points
Modify extension point interface No No major All extension point implementations need adaptation
Add middleware Hook Yes Yes minor Old middleware doesn't implement new Hook
Modify middleware Hook signature No No major All middleware needs adaptation

Compatibility Rules:

  1. SDK MUST load a configuration carrying keys it does not declare (forward compatibility foundation): under the default _config.strict: false an unknown key is retained and readable through get(), and under _config.strict: true it is rejected with CONFIG_INVALID (§9.6.3, §9.10). Documents whose key set this specification closes — an ACL rule (§6.1.5), an execution policy (§7.9.1), the pipeline section (§5.16.1) — reject an unknown key regardless of _config.strict. SDK MUST ignore unknown Schema properties.
  2. SDK MUST provide reasonable defaults for all new fields (backward compatibility foundation)
  3. SDK SHOULD gracefully handle unknown error codes
  4. SDK MUST NOT remove published public APIs in minor/patch versions

14. Appendix

A. Complete Example Project Structure

my-ai-project/
├── apcore.yaml              # Framework configuration
├── extensions/                   # Extension directory
│   ├── api/
│   │   └── handler/
│   │       ├── task_submit.py
│   │       └── task_submit_meta.yaml
│   ├── orchestrator/
│   │   └── engine/
│   │       ├── task_flow.py
│   │       └── task_flow_meta.yaml
│   └── executor/
│       ├── validator/
│       │   ├── db_params.py
│       │   └── db_params_meta.yaml
│       └── handler/
│           ├── db_task.py
│           └── db_task_meta.yaml
├── schemas/                      # Schema definitions
│   ├── api.handler.task_submit.schema.yaml
│   ├── orchestrator.engine.task_flow.schema.yaml
│   ├── executor.validator.db_params.schema.yaml
│   └── executor.handler.db_task.schema.yaml
├── acl/                          # Permission configuration
│   └── global_acl.yaml
└── tests/

B. JSON Schema Validation Files

See .schema.json files in schemas/ directory.

C. Implementations

  • SDKs: Python, TypeScript, Rust. This specification and the conformance fixtures define the shared contract.
  • Surface adapters (independently versioned): apcore-mcp, apcore-a2a, apcore-cli; framework integrations bind HTTP endpoints to modules.

D. Module Exposure Methods Reference (Non-core, Reference Only)

apcore modules can be exposed in multiple forms for external invocation. The mappings below describe how a module projects onto common AI protocols. The core SDKs do not include these adapters; the ecosystem adapters (apcore-mcp, apcore-a2a) implement them.

D.1 MCP (Model Context Protocol) Mapping

# Module → MCP Tool mapping
mcp_mapping:
  tool:
    name: "{module.id}"                  # or the display overlay's resolved MCP alias (§5.13)
    description: "{module.description}"  # or the display overlay's resolved MCP description (§5.13)
    inputSchema: "{module.input_schema}"
    outputSchema: "{module.output_schema}"

    # annotations mapping (MCP ToolAnnotations; `title` is not mapped)
    annotations:
      readOnlyHint: "{module.annotations.readonly}"
      destructiveHint: "{module.annotations.destructive}"
      idempotentHint: "{module.annotations.idempotent}"
      openWorldHint: "{module.annotations.open_world}"

    # apcore-mcp: hints with no ToolAnnotations equivalent travel in the tool's _meta,
    # each present only when the annotation is true
    _meta:
      requiresApproval: "{module.annotations.requires_approval}"
      streaming: "{module.annotations.streaming}"

  # Example
  example:
    # apcore Module
    module:
      id: "executor.email.send_email"
      description: "Send emails via SMTP"
      input_schema: { ... }
      annotations:
        readonly: false
        destructive: false
        idempotent: false
        open_world: true

    # Map to MCP Tool
    mcp_tool:
      name: "executor.email.send_email"
      description: "Send emails via SMTP"
      inputSchema: { ... }
      outputSchema: { ... }
      annotations:
        readOnlyHint: false
        destructiveHint: false
        idempotentHint: false
        openWorldHint: true

D.2 A2A (Agent-to-Agent) Mapping

# Module → A2A Skill mapping
a2a_mapping:
  skill:
    id: "{module.id}"
    name: "{display.a2a.alias}"            # display overlay (§5.13); otherwise the module ID humanized ("image.resize" → "Image Resize")
    description: "{module.description}"    # or the display overlay's resolved A2A description (§5.13)
    tags: "{module.tags}"                  # plus apcore:readonly / apcore:destructive / apcore:idempotent /
                                           # apcore:requires-approval for each of those annotations that is true
    examples: "{module.examples[*].title}" # at most 10
    inputModes: ["application/json"]       # "text/plain" added for a string-root input_schema; ["text/plain"] when there is none
    outputModes: ["application/json"]      # ["text/plain"] when the module has no output_schema

An A2A AgentSkill has no schema member, so input_schema and output_schema do not appear on the skill. A module whose requires_approval annotation is true is withheld from the public Agent Card and listed on the authenticated extended card.

D.3 OpenAI Function Calling Mapping

# Module → OpenAI Function mapping
openai_mapping:
  chat_completions:
    type: function
    function:
      name: "{module.id.replace('.', '-')}"
      description: "{module.description}"
      parameters: "{module.input_schema}"  # after to_strict_schema() (§4.16)
      strict: true
  responses:
    type: function
    name: "{module.id.replace('.', '-')}"
    description: "{module.description}"
    parameters: "{module.input_schema}"  # after to_strict_schema() (§4.16)
    strict: true

  # annotations mapping (OpenAI Agents SDK)
  agents_sdk:
    needs_approval: "{module.annotations.requires_approval}"

D.4 Anthropic Claude Tool Mapping

# Module → Anthropic Tool mapping
anthropic_mapping:
  tool:
    name: "{module.id.replace('.', '-')}"
    description: "{module.description}"
    input_schema: "{module.input_schema}"
    input_examples: "{module.examples[*].inputs}"

D.5 LangChain Tool Mapping

# Module → LangChain Tool
from langchain_core.tools import StructuredTool

def module_to_langchain_tool(module):
    return StructuredTool.from_function(
        func=module.execute,
        name=module.id,
        description=module.description,
        args_schema=module.input_schema,  # Pydantic model
        tags=module.tags,
        metadata=module.metadata,
    )

E. Module Definition Methods Comparison

apcore supports three module definition methods to meet different scenario needs:

Dimension Class-based (Class Definition) Function-based (Functional) External Binding (External Binding)
Definition Method Inherit Module base class @module / module() YAML binding file
Schema Source Native model / YAML Type annotation auto-generation YAML explicit definition / auto_schema
Code Invasiveness High (need inherit base class) Low (add decorator or function call) Zero (no source code modification)
Applicable Scenarios New module development Existing function/method wrapping Existing application zero-modification integration
Lifecycle Hooks on_load / on_unload Not supported Not supported
Advanced Features Full support Partial support (annotations, tags, etc.) Full support (via YAML configuration)
Cross-language Each language implements base class Each language implements module() Universal YAML format

Cross-language Syntax Reference:

Each language SDK SHOULD provide idiomatic module definition syntax. The following illustrates the general patterns:

Pattern Class-based Decorator/Attribute Function Call External Binding
Description Inherit/implement Module interface Language-native annotation Wrap existing callable YAML binding file
Example (Python) class M(Module) @module(id=...) module(fn, id=...) YAML
Example (TypeScript) class M implements Module — module({ id: ..., inputSchema, outputSchema, execute }) YAML
Example (Rust) impl Module for M — FunctionModule::new(annotations, input_schema, output_schema, handler) YAML

Revision History

The specification and the SDK have independent version numbers. CHANGELOG.md records which SDK release ships each specification version. The change rationale appears in CHANGELOG.md and the decision register.

Version Date Summary Records
2.0.0 (draft revision 5) Unreleased Define in-process call budgets, progress and elicitation, and limit configured regex scans (§5.7.1, §7.4.2, §8.2, §10.6.1). #244, Changelog
2.0.0 (draft revision 4) Unreleased Define trusted identity delegation, ACL scope enforcement, and authority binding for discovery and approvals (§6.11, §7.4.1). D-155, Changelog
2.0.0 (draft revision 3) Unreleased Add silent ACL visibility, caller-scoped summaries and schema lookup, and system.manifest.search (§6.10, §11.3). D-154, Changelog
2.0.0 (draft revision 2) Unreleased Add the opt-in post-validation policy evaluator, final-input approval binding, and preflight semantics (§7.2–§7.4.1, §11.3, §12.8). Changelog
2.0.0 (draft revision 1) Unreleased Define an in-memory Core Profile and opt-in extensions (§1.8, §12). Deny calls requiring approval when the handler is absent, and require approval for destructive modules by default (§6.6.3.1, §7.4, §7.9). Require invocation-scoped approval resumption and use a non-secret correlation ID in telemetry (§7, §9.16.2). Specify managed drain, recovery, scoped forced removal, reload reports and lifecycle events (§6.7, §9.16.2, §12.7.9). Assign provider projections to Surfaces (§4.17 and Appendix D). Resolve path-typed configuration against one project root (§9.2.2). Clarify pipeline configuration, preflight and approval argument scope (§5.16.1, §7.3–7.4, §12.8), configured redaction (§6.1.8, §10.6.1) and trace IDs (§10.5). Align schema examples with Draft 2020-12 and the validation error format (§4.2, §4.14, §8.1). D-153, #113, Changelog
1.66.0 2026-10-19 A23 preserves optional enum, const, reference and applicator constraints inside an anyOf-null wrapper; required fields remain unchanged. #124
1.65.0 2026-10-08 Add public bare-name canonicalization with structured, non-throwing results in all SDKs; preserve A02, ASCII-only case conversion and existing underscores, and reject non-ASCII, invalid starts and overlong output (§2.2.1). Rust #40
1.64.0 2026-10-08 Algorithm A02 is exhaustive and ASCII-scoped: it preserves existing underscores and non-ASCII characters through case conversion, then rejects a result outside the Canonical ID grammar; it never repairs arbitrary identifiers (§2.2). The repairing class-name conversion is named snake_case_name and is distinct from A02's snake_case_identifier (§2.1.1). #122
1.63.0 2026-09-30 The three SDKs aligned: a timeout cancels the call's own child token and returns at once (§12.7.5); validate() reports every check (§12.8); explicit retryable defaults (§8.6); JSON-mode input validation (type-mapping §17.3); id_map.overrides is path-typed (§2.2, §9.2.1); binding files reject unknown keys and inference failures (§5.12); export profiles (§4.17); preflight reporting (§12.8.5.1); per-step MODULE_TIMEOUT (§5.16.1); built-in namespaces (§9.15); subscriber circuit events (§9.16.2); env-var dispatch (§9.8.2); marked-class discovery (§2.1.1); the ephemeral contract (§2.5.1); error details shape (§8.1); x-sensitive inside combinators (§10.6, A13); middleware.disabled and extensions.auto_discover deprecated (§9.2.4). Removed what no implementation has: the validate span, config-file extension registration and chaining (§10.1, §11.3, §11.7). D-133 – D-152
1.62.0 2026-09-30 The specification is corrected to behaviour all three SDKs share, including MUSTs no implementation met: reserved words apply to the first segment only and __ is allowed (§2.5, §2.7); entry-point failures raise MODULE_LOAD_ERROR (§5.2); schema inference follows each language's type source (§5.12.5); APCORE_-prefixed env_prefix values are allowed, only duplicates are rejected (§9.8.2); unknown configuration fields are retained unless _config.strict (§13.5); duplicate registration raises DUPLICATE_MODULE_ID (§12.7.4); after() output is not re-validated and timeouts wrap execute() only (§11.8); validate() must not invoke execute() (§12.2). No behaviour change. D-132
1.61.0 2026-09-30 Security: providers are bound into the gate they configure, and governance_state() reports what the running gate holds (§6.6.5.5); configure cannot weaken acl_check / approval_gate (§5.16.1); built-in logging middleware logs redacted values (§10.6.1 req. 5). D-129 – D-131
1.60.0 2026-09-30 Editorial: history and implementation narrative removed from normative text; revision history condensed; the declarative-configuration and ephemeral-module documents merged into this specification. No behaviour change. —
1.59.0 2026-09-18 The deprecation warning is emitted when a definition is read, and its dedupe key includes the notice. D-89
1.58.0 2026-09-18 The audit-entry schema declares correlation_id. D-111
1.57.0 2026-09-17 unregister removes an extension by identity, not equality. D-128
1.56.0 2026-09-17 Security: a symlink is recorded once, under its real path. D-127
1.55.0 2026-09-16 A version_hint an implementation does not resolve by must not be silently ignored. D-126
1.54.0 2026-09-16 Security: the governance union (annotation ∪ descriptor metadata) binds every SDK and every governance reader. D-125
1.53.0 2026-09-16 The local-$ref node fallback is scoped to the document it was declared in. D-124
1.52.0 2026-09-16 shutdown() attempts every task cancellation before reporting; a hot-reloaded module is not visible before on_load() completes. D-122, D-123
1.51.0 2026-09-16 Fourteen policy decisions: unknown extension points, health thresholds, failed-reload restore, bulk-reload audit, storage namespaces, error timestamps, annotation tolerance, and more. D-108 – D-121
1.50.0 2026-09-15 Sixteen cross-language corrections, five of them security fixes: approval-source union, binding annotations, config dot-path pollution, symlink confinement, redaction list, x-sensitive beside $ref, global_deadline, local $ref resolution. D-92 – D-107
1.49.0 2026-09-15 Eighteen cross-language contracts stated: describe, ExtensionManager.apply, registry events, dependency sort, ContextFactory, TaskStoreError, call-chain guard signature, and more. D-74 – D-91
1.48.0 2026-09-14 logging.level / logging.format withdrawn with no replacement key. D-67, #118
1.47.0 2026-09-14 §9.1.3: a declared configuration key must reach its mechanism from a Config; acl.default_effect in apcore.yaml deprecated. D-73, #118
1.46.0 2026-09-14 §9.6.3 _config.allow_unknown; extensions.roots and id_map.overrides wired from configuration. D-69 – D-71, #118
1.45.0 2026-09-11 §6.3.2: the ACL file's audit: block is the one audit configuration home, with a delivery contract. D-66, #118
1.44.0 2026-09-11 §10.1.1: tracing is configured from observability.tracing.* (enabled, strategy, sampling_rate, exporter, otlp_endpoint). D-68, #118
1.43.0 2026-09-11 §5.16: a configured pipeline: section takes effect. D-72, #118
1.42.0 2026-09-11 §3.5 / §3.6: extensions.ignore_patterns is applied during discovery. #118
1.41.0 2026-09-10 §10.6.1: where obs.redaction.* rules apply. #120
1.40.0 2026-09-09 §10.6.1: regex_patterns apply to string values only. #117
1.39.0 2026-09-09 §9.2.4 Deprecated Configuration Keys: removal window opened for keys no implementation reads. #118
1.38.0 2026-09-09 §9.1.2 Declarative Validation Limits. #118
1.37.0 2026-09-09 §9.2.3 Pattern-Valued Values and algorithm A25 match_glob. #116, #117
1.36.0 2026-09-06 Binding field is target; corrections to path resolution and discovery found by the first conformance drivers. #113 – #115
1.35.0 2026-09-06 §5.12.6: bindings.dir is loaded from configuration; §9.2.2 Path Resolution Base. #113, #114
1.34.0 2026-09-06 §9.2.1 Path-Typed Configuration Keys. #113
1.33.0 2026-09-05 §6.1.4.1 / §6.2.1: which rules the unevaluable-condition backstop covers. #112
1.32.0 2026-09-05 §7.3.1: ApprovalRequest carries caller_id and action. D-03
1.31.0 2026-09-04 §6.2.1: a pattern array with no operands is rejected. #112
1.30.0 2026-08-31 §6.1.5: effect accepts only allow or deny. #111
1.29.0 2026-08-31 §6.1.1: an unevaluable allow rule keeps its approval requirement. #109
1.28.0 2026-08-28 §6.1.6–§6.1.8, §6.8.1, §6.9: argument-scoped approval rules. #108
1.27.0 2026-08-28 §6.1: unknown or reserved ACL rule keys are rejected. #107
1.26.0 2026-08-28 §2.6: reserved-word detection applies to the first segment only. #99
1.25.0 2026-08-28 Corrections to 1.22.0–1.24.0 found while implementing them. #100, #102
1.24.0 2026-08-27 §7.9.6: policy resolution can see the call's arguments. #102
1.23.0 2026-08-27 §6.8: an ACL's default_effect can be read back. #101
1.22.0 2026-08-27 §6.1.1 / §6.1.2: unevaluable ACL conditions fail closed. #100
1.21.0 2026-08-27 APCore.remove removes middleware by identity in every SDK. —
1.20.0 2026-08-27 Registry.register contract matches each SDK's sync/async shape. —
1.19.0 2026-08-27 §9.14: the unknown-key check walks every nesting level. —
1.18.0 2026-08-27 §12.2: dependencies reach the descriptor as a parsed field. #90
1.17.0 2026-08-27 §9.15.3: sys_modules activation flags default to false, matching the schema. —
1.16.0 2026-08-25 §6.6.5.1: unprotected_control_surface formula corrected. #97
1.15.0 2026-08-25 §6.6.5 Governance State Query; configured and enforced gates are separate facts. #97
1.14.0 2026-08-25 §6.7.1 Usage Module Output Contract. #96
1.13.0 2026-08-17 §12.8.5.1: a failed ACL check withholds module-level preflight and preview. #96
1.12.0 2026-08-14 §11: the type-coercion knob's behaviour is normative where it exists. #95
1.11.0 2026-08-14 §12.2: cross-executor context rebind is a MUST. #92
1.10.0 2026-08-13 §12.2: Registry.register stated, with dependencies metadata. version_hint statement corrected in 1.55.0. #90, D-126
1.9.0 2026-08-12 First non-draft release: $ref recursion vs cycles, SCHEMA_MAX_DEPTH_EXCEEDED, strict-export object detection, required configuration keys, get_declared(). #79
1.9.0-draft 2026-05-06 – 2026-07-13 §2.5 ephemeral.* namespace, §4.4 discoverable, §5.6 preview(), §12.8 predicted_changes; §9.9.5 reserved-namespace query; §7.9 Execution Policy; §9.16.2 governance events. #60, #76, #77
1.8.0-draft 2026-05-04 §5 streaming: recursive deep merge with a depth cap (A24); §7.4 Step 11 result contract. #49 – #51
1.7.0-draft 2026-05-04 §6.1 / §6.2.1 compound ACL operators $or / $not; validate() runs Steps 1–5 and 7. #46, #47
1.6.0-draft 2026-03-29 – 2026-04-08 §9.4–§9.14 Config Bus; §2.7 canonical ID maximum length raised to 192. —
1.5.0-draft 2026-03-20 §5.13 Display Overlay. —
1.4.0-draft 2026-03-06 Approval gate becomes pipeline Step 5; Executor.validate() preflight (§12.2, §12.8). —
1.3.0-draft 2026-03-01 §7 Approval System. —
1.2.0-draft 2026-02-09 §4.16 Strict Mode Export, §4.17 Export Profiles. —
1.1.0-draft 2026-02-07 §5.11 Function-based Module Definition, §5.12 External Schema Binding. —
1.0.0-draft 2026-02-05 Initial draft. —