From e59d07a66f0e14b71b3ec7389e5fd4c08c312bfb Mon Sep 17 00:00:00 2001 From: tercel Date: Mon, 30 Nov 2026 09:38:32 +0800 Subject: [PATCH] fix(core): resolve Atlas audit findings Signed-off-by: tercel --- conformance/README.md | 8 +- conformance/check_driver_coverage.py | 23 +++-- conformance/fixtures/acl_agent_scoping.json | 1 + .../acl_argument_scoped_approval.json | 1 + conformance/fixtures/acl_audit_delivery.json | 1 + .../fixtures/acl_effect_value_closure.json | 1 + conformance/fixtures/acl_evaluation.json | 1 + conformance/fixtures/acl_handler_error.json | 1 + conformance/fixtures/acl_pattern_arity.json | 1 + conformance/fixtures/acl_root_discovery.json | 1 + .../fixtures/acl_rule_key_closure.json | 1 + .../fixtures/allow_unknown_namespaces.json | 1 + .../annotations_extra_round_trip.json | 1 + .../fixtures/approval_request_fields.json | 1 + conformance/fixtures/artifact_reference.json | 1 + .../fixtures/async_task_cancellation.json | 1 + .../fixtures/async_task_evolution.json | 1 + conformance/fixtures/binding_errors.json | 1 + .../fixtures/binding_file_validation.json | 1 + .../fixtures/binding_schema_ref_scope.json | 1 + .../fixtures/bindings_dir_resolution.json | 1 + conformance/fixtures/call_budget.json | 1 + conformance/fixtures/call_chain.json | 1 + conformance/fixtures/canonicalize_name.json | 1 + .../fixtures/capability_discovery.json | 1 + conformance/fixtures/config_defaults.json | 1 + conformance/fixtures/config_env.json | 1 + .../fixtures/config_key_governance.json | 1 + .../fixtures/config_path_typed_keys.json | 1 + conformance/fixtures/config_project_root.json | 1 + conformance/fixtures/context_create.json | 1 + .../fixtures/context_serialization.json | 1 + .../fixtures/context_trace_parent.json | 1 + conformance/fixtures/contextual_audit.json | 1 + .../dependency_version_constraints.json | 1 + .../document_version_negotiation.json | 1 + conformance/fixtures/durable_input.json | 1 + conformance/fixtures/env_prefix_dispatch.json | 1 + conformance/fixtures/ephemeral_modules.json | 1 + conformance/fixtures/error_codes.json | 1 + conformance/fixtures/error_details_shape.json | 1 + .../fixtures/error_fingerprinting.json | 1 + .../fixtures/error_recovery_metadata.json | 1 + conformance/fixtures/error_serialization.json | 1 + .../fixtures/event_management_hardening.json | 1 + conformance/fixtures/event_naming.json | 1 + .../fixtures/executor_trace_cancellation.json | 1 + .../fixtures/extension_point_lookup.json | 1 + .../fixtures/gate_provider_binding.json | 1 + conformance/fixtures/gate_step_configure.json | 1 + conformance/fixtures/glob_matching.json | 1 + conformance/fixtures/governance_state.json | 1 + .../fixtures/id_conflict_reserved_words.json | 1 + conformance/fixtures/id_map_from_config.json | 1 + conformance/fixtures/identity_delegation.json | 1 + conformance/fixtures/identity_system.json | 1 + .../fixtures/json_input_native_types.json | 1 + .../fixtures/middleware_hardening.json | 1 + .../middleware_on_error_recovery.json | 1 + conformance/fixtures/module_lifecycle.json | 1 + .../fixtures/module_output_normalization.json | 1 + .../fixtures/multi_module_discovery.json | 1 + .../fixtures/multi_root_discovery.json | 1 + conformance/fixtures/normalize_id.json | 1 + .../fixtures/observability_hardening.json | 1 + .../fixtures/openai_strict_compat.json | 1 + conformance/fixtures/overrides_store.json | 1 + conformance/fixtures/pattern_matching.json | 1 + .../fixtures/pipeline_failfast_config.json | 1 + conformance/fixtures/pipeline_hardening.json | 1 + .../fixtures/pipeline_section_wiring.json | 1 + .../fixtures/pipeline_step_middleware.json | 1 + .../fixtures/post_validation_policy.json | 1 + .../fixtures/preflight_check_reporting.json | 1 + .../fixtures/preflight_disclosure.json | 1 + conformance/fixtures/redaction_config.json | 1 + .../fixtures/registry_load_ordering.json | 1 + conformance/fixtures/schema_content_hash.json | 1 + .../fixtures/schema_export_envelope.json | 1 + .../fixtures/schema_hardening_cache.json | 1 + .../schema_hardening_constraints.json | 1 + .../fixtures/schema_hardening_formats.json | 1 + .../fixtures/schema_hardening_recursive.json | 1 + .../fixtures/schema_hardening_union.json | 1 + .../fixtures/schema_keyword_parity.json | 1 + .../fixtures/schema_strict_conversion.json | 1 + conformance/fixtures/schema_validation.json | 1 + .../fixtures/sensitive_keys_default.json | 1 + conformance/fixtures/specificity.json | 1 + conformance/fixtures/storage_backend.json | 1 + conformance/fixtures/stream_aggregation.json | 1 + conformance/fixtures/stream_completion.json | 1 + .../fixtures/stream_post_processing.json | 1 + .../fixtures/system_modules_hardening.json | 1 + .../fixtures/timeout_cancellation.json | 1 + .../fixtures/toggle_state_isolation.json | 1 + conformance/fixtures/trace_context.json | 1 + conformance/fixtures/tracing_from_config.json | 1 + conformance/fixtures/usage_contract.json | 1 + conformance/fixtures/usage_exporter.json | 1 + conformance/fixtures/version_negotiation.json | 1 + python/src/apcore/_sync_bridge.py | 23 ++++- python/src/apcore/async_task.py | 8 +- python/src/apcore/bound_module.py | 10 +-- python/src/apcore/context.py | 21 ++++- python/src/apcore/decorator.py | 86 ++++++++++++------- python/src/apcore/executor.py | 9 +- python/tests/test_async_task.py | 24 ++++-- python/tests/test_bound_module.py | 39 ++++++++- python/tests/test_executor_async.py | 57 ++++++++++++ python/tests/test_governance_state.py | 23 +++++ python/tests/test_realtime_context.py | 28 +++++- rust/src/async_task.rs | 2 +- rust/src/builtin_steps.rs | 15 +++- rust/src/sys_modules/mod.rs | 50 ++++++++++- rust/tests/call_budget.rs | 32 +++++++ rust/tests/post_validation_policy.rs | 70 ++++++++++++++- typescript/src/builtin-steps.ts | 17 +++- typescript/src/context.ts | 13 ++- typescript/src/durable-input.ts | 11 +-- typescript/src/executor.ts | 11 ++- typescript/src/identity.ts | 19 ++-- .../tests/conformance-durable-input.test.ts | 9 ++ .../conformance-identity-delegation.test.ts | 2 +- .../tests/test-capability-discovery.test.ts | 16 ++++ .../tests/test-context-interactions.test.ts | 22 +++++ .../tests/test-identity-delegation.test.ts | 8 +- .../tests/test-post-validation-policy.test.ts | 41 +++++++++ 128 files changed, 701 insertions(+), 95 deletions(-) diff --git a/conformance/README.md b/conformance/README.md index 03c9da0a..cf69d95b 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -12,10 +12,10 @@ All fixture files use **JSON** format (`.json`), with one intentional exception: SDK conformance runners **must** load `.json` files with a JSON parser. The `.yaml` file is consumed directly by binding-loader tests, not by the generic conformance runner. -The `profile` field identifies the runtime profile exercised by a fixture. -`core` fixtures can run against a default in-memory SDK installation. -Configuration, Discovery, Events, and System Modules fixtures use their -declared extension. Adapter wire projections are verified in Surfaces. +Each JSON fixture declares its primary runtime `profile`. Use `core` for +in-memory SDK behavior and `config`, `discovery`, `system-modules`, `events`, +or `observability` for extension behavior. Some fixtures exercise cooperating +profiles during setup. Adapter wire projections are verified in Surfaces. > **Note for tooling authors:** Some ecosystem skill docs describe conformance fixtures as YAML; this is incorrect. The canonical format for all conformance test cases is JSON. The README is the authoritative format reference. diff --git a/conformance/check_driver_coverage.py b/conformance/check_driver_coverage.py index a7f43da1..15d8db58 100644 --- a/conformance/check_driver_coverage.py +++ b/conformance/check_driver_coverage.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Report which conformance fixtures are not driven by all three SDKs. +"""Check conformance fixture profiles and report gaps in SDK driver coverage. A conformance fixture exists to prove three implementations agree. One that only two SDKs load is not doing that job — it is proving two implementations agree, @@ -13,7 +13,8 @@ python3 conformance/check_driver_coverage.py [--sdk-root DIR] [--strict] -Without --strict this reports and exits 0, so the existing backlog does not +Missing or unknown fixture profiles always fail. Without --strict, driver gaps +are reported without failing, so the existing backlog does not block unrelated work. With --strict it exits 1 on any gap — the setting to switch on once the backlog is closed, so new fixtures cannot land undriven. `--baseline` accepts the current gap set and fails only on NEW gaps, which is the @@ -36,6 +37,7 @@ REPO = Path(__file__).resolve().parent.parent FIXTURES = REPO / "conformance" / "fixtures" BASELINE = REPO / "conformance" / "driver_coverage_baseline.json" +PROFILES = {"core", "config", "discovery", "system-modules", "events", "observability"} SDKS = { "python": ("apcore-python", ("tests",), (".py",)), @@ -158,6 +160,17 @@ def main() -> int: ap.add_argument("--write-baseline", action="store_true") args = ap.parse_args() + fixtures = sorted(FIXTURES.glob("*.json")) + invalid_profiles = [] + for path in fixtures: + profile = json.loads(path.read_text(encoding="utf-8")).get("profile") + if not isinstance(profile, str) or profile not in PROFILES: + invalid_profiles.append(path.name) + if invalid_profiles: + for name in invalid_profiles: + print(f"{name}: invalid or missing runtime profile", file=sys.stderr) + return 1 + present = [s for s, (repo, *_) in SDKS.items() if sdk_dir(args.sdk_root, repo).is_dir()] if len(present) < 3: print(f"Need all three SDK checkouts under {args.sdk_root} " @@ -166,7 +179,7 @@ def main() -> int: gaps: dict[str, list[str]] = {} full = 0 - for path in sorted(FIXTURES.glob("*.json")): + for path in fixtures: stem = path.stem missing = [s for s in SDKS if not drivers_for(args.sdk_root, s, stem)] if missing: @@ -174,11 +187,11 @@ def main() -> int: else: full += 1 - total = len(list(FIXTURES.glob("*.json"))) + total = len(fixtures) print(f"{total} fixtures — {full} driven by all three SDKs, {len(gaps)} with gaps") vacuous: list[str] = [] - for path in sorted(FIXTURES.glob("*.json")): + for path in fixtures: for sdk, (repo, *_rest) in SDKS.items(): for rel in drivers_for(args.sdk_root, sdk, path.stem): q, d = quarantine_ratio(sdk_dir(args.sdk_root, repo) / rel) diff --git a/conformance/fixtures/acl_agent_scoping.json b/conformance/fixtures/acl_agent_scoping.json index ba4a41e1..f1d61d5a 100644 --- a/conformance/fixtures/acl_agent_scoping.json +++ b/conformance/fixtures/acl_agent_scoping.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "AI-agent tool-governance ACL scenario (issue #72). One canonical default-deny ruleset (mirrors examples/acl/agent-tool-governance.yaml) scopes tool access by caller pattern + identity roles + call-chain depth. The shared `rules` / `default_effect` apply to every case; each case is a (caller_id, caller_identity, call_depth, target_id) -> expected access decision (true = allow, false = deny). Locks the agent-governance scenario as a cross-language contract: all SDKs and framework integrations MUST produce identical decisions. Exercises ACL first-match-wins (spec §6) with conditions {roles, max_call_depth} and the @external special caller. Privilege gradient: @external < reader < data_admin.", "default_effect": "deny", "rules": [ diff --git a/conformance/fixtures/acl_argument_scoped_approval.json b/conformance/fixtures/acl_argument_scoped_approval.json index 47754f5b..63a417b7 100644 --- a/conformance/fixtures/acl_argument_scoped_approval.json +++ b/conformance/fixtures/acl_argument_scoped_approval.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Argument-scoped approval — PROTOCOL_SPEC §6.1.1 / §6.1.6 / §6.1.7 / §6.1.8 / §6.8.1 / §6.9 (spec v1.28.0 apcore#108, extended v1.29.0 apcore#109). Authorization and approval requirement are two orthogonal results: `effect` carries the first, the orthogonal optional `approval` field the second, and the built-in structure-only `arguments` condition decides whether a rule matches THIS call.\n\n**Every case runs TWICE.** The `arguments` condition can only be answered when a governance projection is available, and §6.1.8 case 1 makes `check()` a public entry point that may be called without one — so the same rules and the same call have two well-defined answers, and both are contracts. Run 1 supplies a projection derived from `arguments` (key set, optionally types — never values, §6.1.8 rule 2) by whatever route the SDK uses; §6.1.8 rule 4 leaves that idiomatic. Run 2 supplies NO PROJECTION AT ALL. `arguments: null` means the case has no projection to supply in either run, so the two runs coincide and both columns hold the same values.\n\nDriver contract. Build an ACL from `rules` in order with the given `default_effect`. For each run call the STRUCTURED accessor with caller_id/target_id and assert `access`, the approval requirement and `matched_rule_index` (null when the decision came from `default_effect`); assert the LEGACY boolean; and assert the AuditEntry's `handler_error` is non-null exactly where the run's column says so — §6.3.1 makes it the if-and-only-if marker of an unevaluable condition, which is what keeps 'the handler said no' and 'no answer was obtainable' tellable apart after the fact. Keys ending `_no_projection` belong to run 2; the unsuffixed ones to run 1.\n\n**An SDK whose legacy boolean cannot receive a projection asserts run 2's `expected_legacy_check_no_projection` and skips only `expected_legacy_check`.** apcore-rust is that SDK: `ACL::check(caller_id, target_id, ctx)` has no parameter for one and passes `None` to `check_access` internally, which is conforming — §6.1.8 rule 4 fixes only that the condition sees the projection, and §6.1.8 case 1 contemplates `check()` being called without one. Both structured columns remain fully assertable there via `check_access(..., Some(&projection))` and `check_access(..., None)`. This split replaces a driver-side skip. The skip was honest and reconciled against the fixture, but it left 17 of 20 cases unverified on one SDK, and #109 — an unevaluable `allow` rule discarding the `approval: required` it carried, so a broader rule granted the call unapproved — was sitting in exactly those cases. A skip justified as 'this SDK is being asked a different question' still owes the other question an answer, because the difference may itself be the bug.\n\nWhere `expected_validation_finding_path` is non-null, assert `validate_rules()` reports a finding at that condition path — §6.1.8 descends to `arguments.` where one predicate is at fault and stops at `arguments` where none can be named. Where `expected_validation_finding_paths` is non-null, assert the rule's findings are EXACTLY those paths in that order — §6.1.8 rule 3 requires every faulty predicate to be reported, not just the first. Validation is context-free, so it has one column, not two.\n\n`callers_raw` / `targets_raw` carry a deliberately malformed pattern field in place of the well-formed key, which a statically typed SDK cannot represent; those cases carry `skip_if_unrepresentable`. Both fields are covered because §6.1.1 rule 5's malformed-scope clause names both and they are separate code paths.\n\nThree cases use `default_effect: allow` against the house rule, and say so in their notes: a `deny` rule TAKING EFFECT under §6.1.1, and a pending approval requirement riding through the default under §6.1.1 rule 5, are not observable against a `deny` default, because not-granting produces the same answer.\n\nLesson recorded from the #107 fixture: it reached for `approval` as its example of a rule key 'from a proposal that has not landed', and v1.28.0 landed that proposal, so the case asserted the opposite of the spec. Do not draw negative examples from live proposals.", "test_cases": [ { diff --git a/conformance/fixtures/acl_audit_delivery.json b/conformance/fixtures/acl_audit_delivery.json index d822fd9d..11aea802 100644 --- a/conformance/fixtures/acl_audit_delivery.json +++ b/conformance/fixtures/acl_audit_delivery.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "PROTOCOL_SPEC §6.3.2 (spec v1.45.0, apcore#118 decision D-66): ACL audit DELIVERY. §6.3.1 has always specified the record — thirteen fields, `handler_error` and `approval_required` with precise semantics — and nothing specified how it is delivered. `ACL(audit_logger=…)` was the entire surface: no default sink, no statement of what happens when delivery fails, and no meaning for the `audit:` block's `enabled` / `include_denied` / `log_level`, which were declared in TWO places and read in neither. The sharpest consequence was measured, not inferred: a failing audit callback propagated out of `check()` and turned an ALLOWED call into an error, in all three SDKs. Drivers MUST load a real ACL FILE and drive real `check()` calls: reading the parsed block back off a config object proves the parser works, which was never the question. `input.callback` selects what the driver installs programmatically — `none`, `collecting` (records every entry it receives), or `failing` (raises/throws/panics on every entry).", "test_cases": [ { diff --git a/conformance/fixtures/acl_effect_value_closure.json b/conformance/fixtures/acl_effect_value_closure.json index 83ffbbec..5b9ffd12 100644 --- a/conformance/fixtures/acl_effect_value_closure.json +++ b/conformance/fixtures/acl_effect_value_closure.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "An ACL rule's `effect` value is a CLOSED set, at every entry point (PROTOCOL_SPEC §6.1.5, spec v1.30.0, #111). `allow` and `deny` are the only legal values — §6.1's field table has always said **MUST** and `schemas/acl-config.schema.json` has always declared the enum — and a rule carrying anything else **MUST** be rejected with `ACLRuleError` naming the rule index and the offending value.\n\n**The entry point is the substance of this fixture, not a detail.** #107 closed the rule KEY set; this closes a legal key's VALUE, and it was found because the check already existed and was reachable from only one of three doors. Drivers **MUST** exercise each door in `entry_points` that the SDK exposes: `load` (an ACL file), `construct` (building the ACL/rule directly in code) and `add_rule` (runtime insertion). §6.1.6 rule 3 is the governing text — accepting a rule through one door while rejecting it at two is worse than either — and an SDK whose `add_rule` returns nothing by its own contract provides a fallible variant beside it or fails loudly in whatever way that language signals an unconstructable value.\n\n`expected_load: ok` means the rule is accepted at every listed door; `reject` means it is rejected at every listed door. There is deliberately no per-door expectation: a value legal through one entry point and illegal through another is the defect, so the fixture cannot have a shape that can express it.\n\n**An unrecognised `effect` MUST NOT be resolved to a decision.** Reading it as `deny` looks safe and is not: under `default_effect: allow` a rule written to permit becomes one that denies everything it matches, and on a `deny` rule the fallback is only accidentally right — correct until someone revisits which way it points. Where a case is rejected there is no access decision to assert, which is the point.\n\n`default_effect` is closed on the same terms. All three SDKs already validated it at every door before v1.30.0, which is what made a rule's `effect` guarding only the file path an internal inconsistency as well as a cross-language one; `default_effect` cases are pinned here so that behaviour stops being correct-by-convention.", "test_cases": [ { diff --git a/conformance/fixtures/acl_evaluation.json b/conformance/fixtures/acl_evaluation.json index ce688a6d..15d9d17d 100644 --- a/conformance/fixtures/acl_evaluation.json +++ b/conformance/fixtures/acl_evaluation.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "ACL rule evaluation (first-match-wins, spec §6)", "test_cases": [ { diff --git a/conformance/fixtures/acl_handler_error.json b/conformance/fixtures/acl_handler_error.json index 62005bfe..e868ef00 100644 --- a/conformance/fixtures/acl_handler_error.json +++ b/conformance/fixtures/acl_handler_error.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "ACL condition evaluation failure — cross-language SECURITY golden test (spec v1.22.0 / v1.25.0, #100). A condition that CANNOT BE EVALUATED is not the same as a condition that is FALSE, and the rule's `effect` decides what the difference means: an unevaluable condition MUST resolve the rule toward refusing access — a `deny` rule takes effect and the call is DENIED; an `allow` rule does not match and MUST NOT grant. \"Unevaluable\" is a PRINCIPLE, not a closed list (§6.1.1): no resolvable handler, a handler that raises/throws/panics, an async handler unresolvable on the sync path, a value malformed for its key, or a `conditions` that is not a mapping. §6.1.4's precheck is context-independent and runs BEFORE §6.5's no-context check, so a malformed rule is unevaluable even for a caller that supplied no context. Driver contract: register a handler under `throwing_condition_key` whose evaluate() raises/throws/panics; register NOTHING for `unknown_condition_key`. Build an ACL from `rules` with the given `default_effect`, wire an audit sink, call check(caller_id, target_id) — passing a context only when `with_context` is true — and when it is true, the context MUST carry exactly the identity given by that case's `context_identity` (id, type, roles). Several cases turn on whether a `roles` condition is SATISFIED, so a driver that supplies a bare identity-less context will get the wrong decision and the failure will look like over-gating when it is not. Assert the decision equals `expected`, that AuditEntry.handler_error is non-null when `expected_audit_handler_error_present` is true, and — where `expected_handler_error_paths` is present — that handler_error names exactly those condition paths, in that order (§6.1.1 rule 2 orders by path). Cases whose rule carries `callers_raw` / `targets_raw` supply that value in place of the normal list, to exercise §6.1.4.1: a driver in a language where the malformed value is not representable (apcore-rust's `Vec`) MUST skip those cases and say so, rather than reporting them as passing.", "throwing_condition_key": "__test_throwing_condition__", "test_cases": [ diff --git a/conformance/fixtures/acl_pattern_arity.json b/conformance/fixtures/acl_pattern_arity.json index 0abfb0f2..6ab674b1 100644 --- a/conformance/fixtures/acl_pattern_arity.json +++ b/conformance/fixtures/acl_pattern_arity.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "A `callers` / `targets` pattern array's ARITY is closed (PROTOCOL_SPEC §6.2.1, spec v1.31.0, #112). An array MUST carry at least one operand: the array itself MUST NOT be empty, `$or` at index 0 MUST be followed by at least one pattern, and `$not` at index 0 MUST be followed by exactly one. Anything else is rejected with `ACLRuleError` at EVERY entry point that accepts a rule — file loading, direct construction and runtime insertion — on §6.1.6 rule 3's reasoning.\n\n**Why rejection and not a non-match.** Through v1.30.0 all three SDKs returned `false` from the matcher for `[]`, `[\"$or\"]` and `[\"$not\"]`, so the rule was inert: the outcome tracked `default_effect` exactly and `validate_rules()` reported nothing. On an `allow` rule that is merely useless. On a `deny` rule under `default_effect: allow` the call the operator wrote the rule to block is PERMITTED. Two normative statements required that reading and are replaced rather than reinterpreted: §6.5's edge-case table required an empty list to make the rule \"never match\", and §6.2.1's table called `[\"$not\"]` \"fail-closed\" — true of an `allow` rule and false of a `deny` one, a label predating §6.1.1 (v1.22.0) naming the asymmetry.\n\n**`$not` takes exactly one operand.** §6.2.1 previously made `[\"$not\", p1, p2, …]` implementation-defined — consult `p1`, ignore the rest. All three SDKs do exactly that, so the form is consistent across implementations and consistently WIDER THAN WRITTEN: `targets: [\"$not\", \"secrets.a\", \"secrets.b\"]` on an `allow` rule reads as \"anything but secrets.a\", and `secrets.b` is granted. Measured in apcore-python 0.28.\n\n**A pattern array is FLAT: the operators do not nest and there is no precedence.** `$or` / `$not` nest arbitrarily in `conditions` and not at all here, and the specification never said so, so `[\"$or\", \"$not\", \"a\"]` reads to an author as or-of-not and was in fact an OR of two literals — matching `a`, and also matching a module literally named `$not`, which §6.2.1's own reserved-token clause forbids. All three SDKs route a non-index-0 element straight to the glob matcher, so all three violate that clause. A reserved token outside index 0 is now rejected, which makes the clause hold by construction.\n\n**Two tiers, and they are not the same mechanism.** TIER 1 is structural — length, element types, token positions — a finite predicate, already declared by the schema, rejected at every door. TIER 2 is semantic: an array that is well-formed under every tier-1 rule and still matches no legal module ID, of which `[\"$not\", \"*\"]` is the sharpest example — legal arity, exactly one operand, matches nothing, identical fail-open. Tier 2 is reported by `validate_rules()` and **MUST NOT** be rejected or change any decision, because its predicate cannot be closed without freezing the pattern language, and an incomplete predicate at a door means the same ACL file loads in one language and fails in another. The criterion is normative and the listed shapes are a MUST-detect minimum, not a closed set — enumerating where a principle belonged is the mistake §6.1.1 corrected in v1.25.0.\n\n**Two case shapes, discriminated by `kind`.**\n\n`kind: \"closure\"` — build the rule and offer it at each door listed in `entry_points` that the SDK exposes: `load` (an ACL file), `construct` (building the ACL/rule directly in code) and `add_rule` (runtime insertion). `expected_load: \"ok\"` means accepted at every listed door, `\"reject\"` means rejected at every listed door. There is deliberately no per-door expectation: a shape legal through one entry point and illegal through another is the defect, so the fixture cannot express it. Where a case is rejected there is no access decision to assert, which is the point. A `closure` case that also carries `expected_validation_finding_paths` is a tier-2 case: it MUST load, and `validate_rules()` MUST then report exactly those paths.\n\n`kind: \"backstop\"` — the one route no constructor intercepts. Build the rule with the WELL-FORMED value in `rule`, then assign the value in `mutate` to the named field on the already-constructed rule (every SDK's rule type permits this: a non-frozen dataclass, a mutable interface, `pub` fields) and only then call `check(caller_id, target_id)`. The arity fault is now a §6.1.4.1 precheck fault: the rule is UNEVALUABLE and §6.1.1's effect table decides — a `deny` rule takes effect, an `allow` rule does not grant. **Two decision surfaces, and they can diverge.** `expected_access` binds to the STRUCTURED accessor's `access` field and is the string `\"allow\"` / `\"deny\"`; `expected_legacy_check` binds to the legacy boolean `check()`. They differ whenever access is `allow` with `approval_required: true`, because §6.8.1 makes the boolean fail-closed there — `mutated_empty_targets_on_approval_rule_raises_pending_requirement` is that case, and a driver that reads the boolean as if it were `access` fails it alone and passes every other backstop case. This is the same two-key convention `acl_argument_scoped_approval.json` uses. Assert `access` on the structured accessor and the boolean separately, that the audit entry's `handler_error` is non-null when `expected_audit_handler_error_present` is true, that the reported paths equal `expected_handler_error_paths`, and that `validate_rules()` reports exactly `expected_validation_finding_paths` — each finding carrying a NULL key and BOTH resolvability flags false (§6.1.3 rule 3's keyless structural fault).\n\n**Validation order is pinned by `expected_refused_axis` and `expected_refused_rule_index`.** A rule bad on more than one axis MUST be refused for the first of `effect` -> `approval` -> `callers` / `targets`, and a rule SET with more than one bad rule MUST be refused for the lowest-indexed bad rule — the index chooses the rule, then the axis order chooses the fault inside it. `expected_load` sees neither, so where a case carries these keys the driver MUST additionally assert that the raised error names that axis and that rule index. `expected_refused_axis` takes `effect`, `approval`, `callers`, `targets` or `default_effect`: the first two name axes, the next two name a FIELD within the single pattern axis (so `callers` also asserts the pattern axis fired), and `default_effect` is not a rule axis at all — it is judged before any rule. \"Axis\" is not limited to the ones this fixture names: it is every per-rule check a door performs, which for a loader includes the rule key set (§6.1.5) and the missing-field and value-type checks. A driver MUST fail on an axis value it does not recognise rather than skip the case. Three implementations produced three different axis orders before v1.31.0, and one produced two different answers through two of its own doors because its loader validated rule by rule while its constructor swept axis by axis.\\n\\n**A case carries either `rule` (one) or `rules` (an ordered list).** The `rules` form exists for the cross-rule half above and is offered at the `load` and `construct` doors only, since `add_rule` takes one rule at a time and cannot express it.\n\n**Both fields, deliberately, and the mirror is complete.** §6.2.1 constrains `callers` and `targets` identically, and an implementation that validates only `targets` would otherwise pass nearly every reject case here. Tier 2 is mirrored too — `[\"$not\", \"*\"]` matches nothing on either field. All EIGHT structural shapes rejected on `targets` are therefore also rejected on `callers`: empty array, `$or` with no operand, `$not` with no operand, multi-operand `$not`, empty element, empty element under `$or`, reserved token after an operator, reserved token in a flat list. A `*_in_callers_is_rejected` case mirrors its `targets` twin and carries the rationale by reference rather than repeating it. A driver MUST NOT collapse a mirrored pair — two of them are reachable by no other case: `empty_pattern_string_under_or_in_callers_is_rejected` fails only if a `$or`'s OPERANDS are scanned on the `callers` side, and `reserved_token_after_operator_in_callers_is_rejected` fails only if positions are still checked AFTER a leading operator is consumed.\n\n**Every `closure` case is representable in every SDK.** apcore-rust's `Vec` makes §6.1.4.1's TYPE fault unbuildable but places no constraint on length or element content, so every shape in the closure set is constructible in all three. There is no `skip_if_unrepresentable` on a closure case and a driver MUST NOT introduce one.\n\n**The `backstop` cases need one route an SDK may legitimately not have, and the answer is NOT a skip.** They require mutating a rule that is ALREADY INSTALLED in an ACL. apcore-python (non-frozen dataclass reachable through its rule list) and apcore-typescript (mutable interface) have that route. **apcore-rust does not**: `ACL.rules` is a private field, `ACL::rules()` returns `&[ACLRule]`, there is no `rules_mut`, and `ACL` derives nothing — the rule's FIELDS are public and the SHAPE is constructible, but the mutated rule cannot be INSTALLED. That is a stronger position than the fixture asks for, not a gap in it.\n\nAn SDK in that position satisfies these cases **by construction** and MUST assert the closure rather than skip: that its rule accessor hands back an immutable view with no mutable counterpart, and that offering the already-mutated rule to `add_rule` is **rejected** at the door by tier 1. It MUST report those assertions as passing, never as skipped — \"N skipped\" and \"N satisfied by construction\" are different claims, and only the second one is evidence. The backstop BEHAVIOUR is still required of such an SDK and MUST be covered by its own in-crate/internal tests, because this section constrains what a conformance driver can reach, not what the implementation must do.", "test_cases": [ { diff --git a/conformance/fixtures/acl_root_discovery.json b/conformance/fixtures/acl_root_discovery.json index c1058b0b..e707b17d 100644 --- a/conformance/fixtures/acl_root_discovery.json +++ b/conformance/fixtures/acl_root_discovery.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "Config-driven ACL discovery (D-64, Recommendation A; issue #74). Each case describes the acl.root config value plus the filesystem state at the resolved path; `expected` captures whether an ACL is attached to the Executor and whether enforcement is therefore active. CRITICAL INVARIANT: a missing acl.root path attaches NO ACL (acl_attached=false) and MUST NOT synthesize an empty default-deny ACL — even when acl.default_effect is 'deny' — otherwise every inter-module call in a project with no ACL would be silently denied. acl.root is a directory by convention; the loaded file is /global_acl.yaml (PROTOCOL_SPEC §3.1 `acl/{scope}_acl.yaml`), but acl.root MAY point directly at a YAML file. acl.root defaults to './acl' in all three SDKs (Rust no longer hard-requires it). Auto-discovery is skipped when the caller supplies their own Executor, so an explicitly-wired ACL is never clobbered. The Config project root provides the base for a relative acl.root (§9.2.2). The rule-evaluation semantics of a loaded ACL are covered by acl_evaluation.json; this fixture covers only the discovery/attachment behavior.", "default_acl_root": "./acl", "acl_policy": { diff --git a/conformance/fixtures/acl_rule_key_closure.json b/conformance/fixtures/acl_rule_key_closure.json index e7f1851e..f574c349 100644 --- a/conformance/fixtures/acl_rule_key_closure.json +++ b/conformance/fixtures/acl_rule_key_closure.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "ACL rule keys are a CLOSED set (PROTOCOL_SPEC §6.1, spec v1.27.0, #107). Loading a rule that carries any key outside `callers`, `targets`, `effect`, `approval`, `description`, `conditions` MUST fail with ACLRuleError. (`approval` joined the set in spec v1.28.0, §6.1.6; this fixture originally used it as its example of an unrecognised key, which stopped being true the moment #108 landed — an example must be chosen so that it cannot become valid later.) A key nothing evaluates is otherwise dropped in silence, which widens an `allow` rule with no warning — the §6.1.1 defect class on the pattern side. `id`, `actions` and `priority` were reserved in earlier revisions and are evaluated by no implementation; they are rejected like any other unknown key, and an implementation SHOULD name them as reserved. Driver contract: build an ACL FILE containing `rule` under `rules:` with the given `default_effect`, load it through the SDK's file-loading entry point, and assert that loading succeeds when `expected_load` is \"ok\" and raises/returns an ACL rule error when it is \"reject\". Where the SDK exposes the message, assert it names the offending key.", "closed_rule_keys": [ "callers", diff --git a/conformance/fixtures/allow_unknown_namespaces.json b/conformance/fixtures/allow_unknown_namespaces.json index a3f6d53f..80308737 100644 --- a/conformance/fixtures/allow_unknown_namespaces.json +++ b/conformance/fixtures/allow_unknown_namespaces.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "PROTOCOL_SPEC §9.6.3 `_config.allow_unknown` — the behaviour matrix for an unregistered top-level namespace (spec v1.46.0, apcore#118 decision D-69). BOTH halves of the `strict: false` row were inert in all three SDKs, and the fixture pins both: `allow_unknown: false` is documented as \"silently ignored (not stored)\" and the namespace was stored anyway, so `get()` answered for it; `allow_unknown: true` is documented as \"stored, accessible, **WARN logged**\" and no implementation logged anything. Fixing one without the other leaves the row half true. **Namespace mode only, by construction**: §9.6.3 is about 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.14's walk under `strict`. `strict`'s own clause (b) says it \"applies in legacy mode too\", which is the specification saying clause (a) does not; the last case pins that boundary so the scoping is a decision rather than an omission.", "test_cases": [ { diff --git a/conformance/fixtures/annotations_extra_round_trip.json b/conformance/fixtures/annotations_extra_round_trip.json index e8f3d840..2985227f 100644 --- a/conformance/fixtures/annotations_extra_round_trip.json +++ b/conformance/fixtures/annotations_extra_round_trip.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cross-language ModuleAnnotations.extra wire-format round-trip (spec \u00a74.4). Locks the canonical nested form and verifies Python/TypeScript/Rust SDKs produce and consume identical JSON. See planning notes for the rationale (Rust previously used #[serde(flatten)], Python/TS used nested). Spec MUST: extension keys are serialized as a nested 'extra' object; flattened root-level extension keys are forbidden for producers. `discoverable` (\u00a74.4) is a canonical field and is part of every full wire form below; drivers compare it like any other field.", "test_cases": [ { diff --git a/conformance/fixtures/approval_request_fields.json b/conformance/fixtures/approval_request_fields.json index fe2ea59d..890286e7 100644 --- a/conformance/fixtures/approval_request_fields.json +++ b/conformance/fixtures/approval_request_fields.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "ApprovalRequest carries `caller_id` and `action` (decision D-03, docs/spec/2026-05-decision-log.md — status quo: docs/features/approval-system.md's Contract block already required both; every SDK's ApprovalRequest carried neither). Populated by BuiltinApprovalGate at Executor Step 4.5, from the same Context and module_id already available at that call site: `caller_id = context.caller_id` (null for a top-level/external call, per PROTOCOL_SPEC §5.7 — Context.caller_id is None/null until Context.child() sets it), `action = module_id` (the target module being invoked, so a handler can read `request.action` without cross-referencing `request.module_id` under a second name). Both fields are additive on an already-`#[non_exhaustive]` (Rust) / already-keyword-constructed (Python, TypeScript) type, so no existing construction call breaks.\n\nA driver invokes the module named by `target_id` from the caller named by `caller_id` (or as a top-level call when `caller_id` is null), with an ApprovalHandler configured that records the `ApprovalRequest` it receives and returns `approved`, and asserts the recorded request's `caller_id` and `action` equal `expected_request_caller_id` and `expected_request_action`.", "driver_contract": { "how_to_invoke": "Register `target_id` as a module with `requires_approval: true` (or force it via the same `ExecutionPolicy(gate_destructive=true)` / ACL `approval: required` mechanism `approval_gate.json` and `acl_argument_scoped_approval.json` use — any path that reaches Step 4.5 with `requires_approval` true is equivalent for this fixture, since the field is populated once, upstream of which path triggered the gate). Configure a recording `ApprovalHandler` whose `request_approval` returns `approved` and captures the `ApprovalRequest` it was handed. When `caller_id` is non-null, invoke `target_id` from within a module of that ID (so `Context.child()` sets `caller_id`); when it is null, invoke `target_id` as a top-level call (a fresh `Context`, never passed through `child()`).", diff --git a/conformance/fixtures/artifact_reference.json b/conformance/fixtures/artifact_reference.json index 953a0405..4001be4f 100644 --- a/conformance/fixtures/artifact_reference.json +++ b/conformance/fixtures/artifact_reference.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Opt-in 2020-12 artifact references and media/size assertions", "test_cases": [ { diff --git a/conformance/fixtures/async_task_cancellation.json b/conformance/fixtures/async_task_cancellation.json index 37878cf6..28d4f74c 100644 --- a/conformance/fixtures/async_task_cancellation.json +++ b/conformance/fixtures/async_task_cancellation.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "AsyncTaskManager capacity and cancellation — cross-language golden test. Locks sync findings A-D-003 (submitting beyond max_tasks MUST raise the typed TASK_LIMIT_EXCEEDED error, not a generic error) and A-D-004 (cancelling a task while it is in retry backoff MUST stop further retry attempts and end in CANCELLED — expressed as a deterministic invariant on attempt count + final status, NOT a latency/timing assertion). Driver contract per case action below.", "test_cases": [ { diff --git a/conformance/fixtures/async_task_evolution.json b/conformance/fixtures/async_task_evolution.json index f340864f..da86b5d5 100644 --- a/conformance/fixtures/async_task_evolution.json +++ b/conformance/fixtures/async_task_evolution.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Async task evolution conformance: pluggable TaskStore, retry with configurable backoff, and Reaper TTL-based cleanup (Issue #34).", "test_cases": [ { diff --git a/conformance/fixtures/binding_errors.json b/conformance/fixtures/binding_errors.json index 9795c704..b1284b52 100644 --- a/conformance/fixtures/binding_errors.json +++ b/conformance/fixtures/binding_errors.json @@ -1,4 +1,5 @@ { + "profile": "discovery", "description": "Binding error message conformance (protocol-spec §5.12.8). Each SDK must produce byte-identical messages for the same error conditions.", "spec_ref": "protocol-spec §5.12.8", "test_cases": [ diff --git a/conformance/fixtures/binding_file_validation.json b/conformance/fixtures/binding_file_validation.json index 675fcc67..a990ff16 100644 --- a/conformance/fixtures/binding_file_validation.json +++ b/conformance/fixtures/binding_file_validation.json @@ -1,4 +1,5 @@ { + "profile": "discovery", "description": "Binding files fail loudly (PROTOCOL_SPEC 5.12.2, 5.12.5, decision D-139). An unknown top-level key or an unknown entry key, an explicit schema pair with one side missing, and an invalid `auto_schema` value fail with BINDING_FILE_INVALID; a target from which no schema can be inferred fails with BINDING_SCHEMA_INFERENCE_FAILED in every mode, implicit included. A permissive fallback turns a typo into a module whose inputs are never validated. Measured before D-139: all three SDKs ignored unknown keys; apcore-typescript defaulted the missing side of a schema pair to `{}` and accepted any `auto_schema` value; apcore-typescript and apcore-rust gave an implicit-mode entry that yielded no schema a permissive object schema.", "spec_sections": [ "PROTOCOL_SPEC 5.12.2", diff --git a/conformance/fixtures/binding_schema_ref_scope.json b/conformance/fixtures/binding_schema_ref_scope.json index f501ae95..66fc07f6 100644 --- a/conformance/fixtures/binding_schema_ref_scope.json +++ b/conformance/fixtures/binding_schema_ref_scope.json @@ -1,4 +1,5 @@ { + "profile": "discovery", "description": "Binding schema references resolve from their declaring file and accept schema files in authorized roots.", "test_cases": [ { diff --git a/conformance/fixtures/bindings_dir_resolution.json b/conformance/fixtures/bindings_dir_resolution.json index e1eb1bfc..3b8144e3 100644 --- a/conformance/fixtures/bindings_dir_resolution.json +++ b/conformance/fixtures/bindings_dir_resolution.json @@ -1,4 +1,5 @@ { + "profile": "discovery", "description": "PROTOCOL_SPEC §5.12.6 — the binding-directory resolution contract. Through v1.34.0 §5.12.6 carried a MUST with no subject and no trigger (\"if bindings.dir is configured, implementations MUST scan files matching pattern in that directory\"), and no SDK satisfied it: bindings.dir is registered in all three key surfaces and read by no code path, while BindingLoader is exported public API in all three and called from no internal one. v1.35.0 names both: a binding loader invoked WITHOUT an explicit directory argument MUST resolve the directory from bindings.dir under §9.2 precedence (env APCORE_BINDINGS_DIR > config file > default ./bindings) and MUST match files against bindings.pattern through the same chain (default *.binding.yaml); an explicit argument still wins; and implementations MUST NOT scan a binding directory automatically at client or framework initialisation. SCOPE: this fixture asserts WHICH directory and pattern a loader resolves, and WHETHER a scan happens. The relative path base is covered separately by config_project_root.json (§9.2.2).", "spec_sections": [ "PROTOCOL_SPEC §5.12.6", diff --git a/conformance/fixtures/call_budget.json b/conformance/fixtures/call_budget.json index acd48a8b..3401c856 100644 --- a/conformance/fixtures/call_budget.json +++ b/conformance/fixtures/call_budget.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Shared call-tree accounting through the public governed call entry point.", "test_cases": [ { diff --git a/conformance/fixtures/call_chain.json b/conformance/fixtures/call_chain.json index cd5c69d2..768d2da7 100644 --- a/conformance/fixtures/call_chain.json +++ b/conformance/fixtures/call_chain.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Guard call chain safety (Algorithm A20)", "test_cases": [ { diff --git a/conformance/fixtures/canonicalize_name.json b/conformance/fixtures/canonicalize_name.json index adaa935f..65fe6de9 100644 --- a/conformance/fixtures/canonicalize_name.json +++ b/conformance/fixtures/canonicalize_name.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Public bare-name canonicalization: one ASCII name becomes a segment or a structured diagnostic, without changing Algorithm A02.", "spec_sections": [ "PROTOCOL_SPEC 2.2.1", diff --git a/conformance/fixtures/capability_discovery.json b/conformance/fixtures/capability_discovery.json index 3493bbb9..3230b58c 100644 --- a/conformance/fixtures/capability_discovery.json +++ b/conformance/fixtures/capability_discovery.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "ACL-aware discovery uses the normal trusted caller frame, proves visibility without call arguments, and withholds non-public or unauthorized definitions without audit or execution effects.", "driver_contract": { "modules": [ diff --git a/conformance/fixtures/config_defaults.json b/conformance/fixtures/config_defaults.json index 41250713..59cd3e07 100644 --- a/conformance/fixtures/config_defaults.json +++ b/conformance/fixtures/config_defaults.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "Config default values conformance — all SDKs MUST return identical defaults when no explicit configuration is provided. Values sourced from schemas/defaults.schema.json.", "test_cases": [ { diff --git a/conformance/fixtures/config_env.json b/conformance/fixtures/config_env.json index 0199d8d6..ec28674f 100644 --- a/conformance/fixtures/config_env.json +++ b/conformance/fixtures/config_env.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "Environment variable to Config path mapping (Algorithm A12-NS, spec §9.8). Tests path resolution and prefix matching only — type coercion is tested separately in schema_validation.json. `global` is not a namespace: it carries only the bare-variable `env_map` (Config.env_map), and declares no env prefix, since the exact prefix `APCORE` belongs to the `apcore` namespace alone (§9.8.2 rule 3, D-146). An `APCORE_` variable no registered prefix matches belongs to `apcore` (§9.8.2 rule 4), which is what `global_prefix_fallback` pins.", "namespaces": [ { diff --git a/conformance/fixtures/config_key_governance.json b/conformance/fixtures/config_key_governance.json index 1563c515..8e8497af 100644 --- a/conformance/fixtures/config_key_governance.json +++ b/conformance/fixtures/config_key_governance.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "Cross-language governance of the configuration key surface. Asserts that each SDK's default table and constraint table stay inside the key set the canonical schemas declare, and that every canonical default is reproduced exactly. This fixture exists because the same defect class recurred four times in one audit cycle: schema.validation.* (declared by no schema, validated by all three SDKs), a frozen version/project default pair invented by Python and TypeScript that made the required-field check unreachable, middleware.circuit_breaker.* (forbidden by apcore-config.schema.json, validated by all three SDKs, read by none), and a missing Rust default table that resolved 15 documented keys to null. Every one of them is a disagreement between schemas/ and an SDK table, and none was detectable by any test.", "driver_contract": { "sources": "The canonical key surface is derived from schemas/apcore-config.schema.json, schemas/defaults.schema.json and schemas/sys-modules.schema.json (the last namespaced under 'sys_modules.'). `allowed_keys` and `canonical_defaults` below are a projection of those files, regenerated and diffed by the doc repo's own test — do NOT hand-edit them, and do NOT treat this fixture as a second source of truth. Fix the schema, regenerate, then fix the SDK.", diff --git a/conformance/fixtures/config_path_typed_keys.json b/conformance/fixtures/config_path_typed_keys.json index 85732254..5098ffad 100644 --- a/conformance/fixtures/config_path_typed_keys.json +++ b/conformance/fixtures/config_path_typed_keys.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "PROTOCOL_SPEC §9.2.1 — the closed set of path-typed configuration keys. A path-typed key is one whose value is a filesystem path; the set is declared by `\"x-apcore-path\": true` in schemas/apcore-config.schema.json or a namespace schema it references, schemas/sys-modules.schema.json (and mirrored in schemas/defaults.schema.json for the three keys that carry defaults there). This fixture exists because the set was previously undeclared, so every consumer that needed it built its own: apcore-cli hand-maintained SANDBOX_PATH_TYPED_VARS with a note that adding a key means editing three SDKs, and nothing detected drift between that list and the schemas. SCOPE: this fixture asserts WHICH keys are path-typed and that each SDK exposes the set. The effective base is exercised separately by config_project_root.json (§9.2.2).", "canonical_sources": [ "schemas/apcore-config.schema.json", diff --git a/conformance/fixtures/config_project_root.json b/conformance/fixtures/config_project_root.json index 3892db8b..3c7115b3 100644 --- a/conformance/fixtures/config_project_root.json +++ b/conformance/fixtures/config_project_root.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "PROTOCOL_SPEC §9.2.2 — discovery fixes one project root per Config for all relative path-typed configuration values. Exercises all discovery tiers, direct loading, a symlinked configuration, defaults, file, environment and mapping values, both extension list forms, absolute paths, and a working-directory change after load.", "spec_sections": [ "PROTOCOL_SPEC §9.2.2", diff --git a/conformance/fixtures/context_create.json b/conformance/fixtures/context_create.json index a6ba05aa..65fbd2e1 100644 --- a/conformance/fixtures/context_create.json +++ b/conformance/fixtures/context_create.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Context.create unified-signature contract across all SDKs. Validates the v0.22.0 normative input list (identity, trace_parent, cancel_token, data, services, global_deadline), the removal of executor and caller_id as inputs, the Executor binding rules (local create, cross-process deserialize, hot-reload restore), and child() propagation. See docs/features/core-executor.md §Contract: Context.create + §Contract: Executor binding to Context, and Issue #66.", "test_cases": [ { diff --git a/conformance/fixtures/context_serialization.json b/conformance/fixtures/context_serialization.json index 3b3f1a0b..3604053c 100644 --- a/conformance/fixtures/context_serialization.json +++ b/conformance/fixtures/context_serialization.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cross-language Context serialization/deserialization round-trip (spec §5.7)", "test_cases": [ { diff --git a/conformance/fixtures/context_trace_parent.json b/conformance/fixtures/context_trace_parent.json index a2a5e0fc..913986d4 100644 --- a/conformance/fixtures/context_trace_parent.json +++ b/conformance/fixtures/context_trace_parent.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Context.create trace_parent input handling — strict 32-char lowercase hex, no auto-normalization at Context.create. See docs/spec/protocol-spec.md §10.5 external_trace_parent_handling.", "test_cases": [ { diff --git a/conformance/fixtures/contextual_audit.json b/conformance/fixtures/contextual_audit.json index bca103ab..4fba6543 100644 --- a/conformance/fixtures/contextual_audit.json +++ b/conformance/fixtures/contextual_audit.json @@ -1,4 +1,5 @@ { + "profile": "system-modules", "description": "Contextual auditing for control-plane modules (Issue #45.2). Verifies that system.control.* modules include caller_id and a redacted identity snapshot in their emitted audit events, defaulting caller_id to '@external' when the caller is unauthenticated. The bare-substring case added for D-93 (spec v1.50.0) is the one that discriminates: the pre-existing bearer_token case is caught by every spelling of the list, which is why a credential leak in one SDK passed this fixture for as long as it did.", "test_cases": [ { diff --git a/conformance/fixtures/dependency_version_constraints.json b/conformance/fixtures/dependency_version_constraints.json index 8efbf793..562ae3c9 100644 --- a/conformance/fixtures/dependency_version_constraints.json +++ b/conformance/fixtures/dependency_version_constraints.json @@ -1,4 +1,5 @@ { + "profile": "discovery", "description": "Dependency version constraint enforcement during load-order resolution (spec \u00a75.3, \u00a75.15.2)", "test_cases": [ { diff --git a/conformance/fixtures/document_version_negotiation.json b/conformance/fixtures/document_version_negotiation.json index d1c65104..cb54f1d9 100644 --- a/conformance/fixtures/document_version_negotiation.json +++ b/conformance/fixtures/document_version_negotiation.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "Configuration and module-schema file loaders negotiate declared protocol versions (spec §13.3).", "test_cases": [ {"id": "legacy_config", "format": "config", "version": "1.0", "expected": {"error_code": null}}, diff --git a/conformance/fixtures/durable_input.json b/conformance/fixtures/durable_input.json index ab32edf5..954ce21d 100644 --- a/conformance/fixtures/durable_input.json +++ b/conformance/fixtures/durable_input.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Host-level durable input prepare and strict owner/deadline binding", "test_cases": [ { diff --git a/conformance/fixtures/env_prefix_dispatch.json b/conformance/fixtures/env_prefix_dispatch.json index 0a4085fe..8133b0bd 100644 --- a/conformance/fixtures/env_prefix_dispatch.json +++ b/conformance/fixtures/env_prefix_dispatch.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "Environment-variable dispatch in namespace mode (PROTOCOL_SPEC 9.8.2 rules 3 and 4, decision D-146). Only the `apcore` namespace may use the exact prefix `APCORE` (CONFIG_NAMESPACE_RESERVED); a prefix that merely begins with `APCORE_` is legal. A variable is dispatched to ONE namespace, the longest matching prefix, and an `APCORE_` variable that matches no registered prefix belongs to `apcore`. Measured before D-146: all three SDKs accepted `APCORE` for any namespace; apcore-python and apcore-typescript applied every `APCORE_*` variable to the `apcore` namespace AND dispatched it by prefix, so `APCORE_MCP_TRANSPORT` landed in both `apcore-mcp.transport` and `apcore.mcp.transport`; apcore-rust wrote an unmatched `APCORE_` variable to a top-level path outside every namespace.", "spec_sections": [ "PROTOCOL_SPEC 9.8.2", diff --git a/conformance/fixtures/ephemeral_modules.json b/conformance/fixtures/ephemeral_modules.json index 068026a5..19cd2aa1 100644 --- a/conformance/fixtures/ephemeral_modules.json +++ b/conformance/fixtures/ephemeral_modules.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "The ephemeral.* namespace contract (PROTOCOL_SPEC 2.5.1, decision D-148). Each registration and unregistration of an ephemeral module produces EXACTLY ONE apcore.registry.module_registered / module_unregistered event on the client's event emitter under the standard bootstrap, whose payload carries `caller_id`, `identity` (a redacted snapshot, or null) and `namespace_class: \"ephemeral\"`; the bare ID `ephemeral` is in the namespace; the privileged registration path and filesystem discovery reject an ephemeral ID with INVALID_MODULE_ID. Measured before D-148: apcore-python delivered no event under the standard bootstrap (nothing wired the registry's emitter) and omitted `namespace_class`; apcore-typescript emitted two events for the bare ID; apcore-rust had no context on register(), so `caller_id` was always \"@external\" and `identity` was missing, and it rejected with GENERAL_INVALID_INPUT.", "spec_sections": [ "PROTOCOL_SPEC 2.5.1", diff --git a/conformance/fixtures/error_codes.json b/conformance/fixtures/error_codes.json index 59351e91..759cef5b 100644 --- a/conformance/fixtures/error_codes.json +++ b/conformance/fixtures/error_codes.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Error code collision detection (Algorithm A17, spec \u00a78.4). Locks the canonical reserved-prefix set of 14 (sync findings A-D-006) and the exact-framework-code rejection that protects one-off codes outside those prefixes (A-D-007). A custom code under a dropped/non-reserved prefix registers OK unless it exactly equals a framework code.", "test_cases": [ { diff --git a/conformance/fixtures/error_details_shape.json b/conformance/fixtures/error_details_shape.json index 817903ee..91b88703 100644 --- a/conformance/fixtures/error_details_shape.json +++ b/conformance/fixtures/error_details_shape.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Error details have one wire shape (PROTOCOL_SPEC 8.1, decision D-149). A SCHEMA_VALIDATION_ERROR carries `details.errors`, a list of items with exactly the keys `path`, `keyword` and `message`: `path` is an RFC 6901 JSON Pointer into the validated instance (`/count`, `/tags/1`, and `\"\"` for the root), `keyword` is the JSON Schema keyword that failed at that location. Measured before D-149 no two SDKs agreed and no SDK was self-consistent: apcore-python emitted `{field, code, message}` with a dotted path on the executor path and `{path, message, constraint, expected, actual}` with root `/` from its validator; apcore-typescript emitted a numeric TypeBox error type as `constraint` and root `/`; apcore-rust emitted `{field, message}` on the executor path and a dotted, bracketed path from its validator. `details` keys are snake_case in every serialized error.", "spec_sections": [ "PROTOCOL_SPEC 8.1" diff --git a/conformance/fixtures/error_fingerprinting.json b/conformance/fixtures/error_fingerprinting.json index a137a264..7218affb 100644 --- a/conformance/fixtures/error_fingerprinting.json +++ b/conformance/fixtures/error_fingerprinting.json @@ -1,4 +1,5 @@ { + "profile": "observability", "description": "Error fingerprinting and deduplication for ErrorHistory (docs/features/error-history.md#error-fingerprinting). Fingerprint = lowercase hex SHA-256(error_code + ':' + module_id + ':' + normalize_message(message)), UTF-8. normalize_message replaces, in this order, UUIDs with , ISO 8601 dates and timestamps with and integers of four or more digits with , then trims and lowercases. The call site is not an input: stack frames differ between Python, V8 and Rust, so including one would give the same error a different fingerprint in each SDK. Two errors with the same fingerprint MUST collapse into a single ErrorEntry (count incremented, last_seen_at updated). Different error_code values, or different module_id values, MUST produce distinct fingerprints.", "driver_contract": { "module_id": "Each error's `caller_id` is the `module_id` argument of ErrorHistory.record — the module whose call failed, which is what the error-history middleware passes. No other value (a stack frame, a caller) is part of the fingerprint." diff --git a/conformance/fixtures/error_recovery_metadata.json b/conformance/fixtures/error_recovery_metadata.json index d04f93b3..c86bf6f4 100644 --- a/conformance/fixtures/error_recovery_metadata.json +++ b/conformance/fixtures/error_recovery_metadata.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Default AI error-recovery metadata per framework error code. When a framework error is constructed without an explicit override, every language SDK MUST produce these defaults: user_fixable is resolved from the error code (caller can fix by changing input/config = true; governance/system/structural/transient = false); retryable is the error class default. Codes whose user_fixable is null are intentionally left unset for the module author to supply (business errors). ai_guidance text is intentionally NOT pinned here (it is human-readable and may carry runtime context) — only retryable and user_fixable are part of the cross-language contract.", "driver_contract": { "construction": "Construct each error the way the SDK constructs it for that code when no override is given: the typed error class in Python and TypeScript (for example ExecutionCancelledError, CircuitBreakerOpenError, the pipeline ConfigurationError), `ModuleError::new(code)` in Rust. Assert BOTH `retryable` and `user_fixable`: `null` means the field is unset.", diff --git a/conformance/fixtures/error_serialization.json b/conformance/fixtures/error_serialization.json index bea1acf3..325fcf8e 100644 --- a/conformance/fixtures/error_serialization.json +++ b/conformance/fixtures/error_serialization.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "ModuleError serialization wire format — cross-language golden test. The serialized form (Python to_dict, TypeScript toJSON, Rust to_dict/serde) MUST use snake_case keys (trace_id, ai_guidance, user_fixable) and MUST snake_case the keys inside `details`, matching the serialization example in docs/features/error-system.md. Null/None optional fields are omitted (sparse output). Locks sync finding A-D-008. Driver contract: construct a ModuleError from `input` (code + message + optional fields), serialize via the SDK's canonical error serializer, then assert each key in `expected_keys_present` is present, each in `expected_keys_absent` is absent, and likewise for the nested `details` object via `expected_detail_keys_present` / `expected_detail_keys_absent`.", "test_cases": [ { diff --git a/conformance/fixtures/event_management_hardening.json b/conformance/fixtures/event_management_hardening.json index b7687e64..9d6eff6a 100644 --- a/conformance/fixtures/event_management_hardening.json +++ b/conformance/fixtures/event_management_hardening.json @@ -1,4 +1,5 @@ { + "profile": "events", "description": "Cross-language SubscriberFactory parity, built-in File/Stdout/Filter subscribers, and circuit-breaker state machine conformance (Issue #36). Event-type patterns on `event_pattern`, `include_events` and `exclude_events` are matched with algorithm A25 (PROTOCOL_SPEC 9.16.3): `*` and `?` only, every other character literal, case-sensitive.", "test_cases": [ { diff --git a/conformance/fixtures/event_naming.json b/conformance/fixtures/event_naming.json index d403b620..2ff507c4 100644 --- a/conformance/fixtures/event_naming.json +++ b/conformance/fixtures/event_naming.json @@ -1,4 +1,5 @@ { + "profile": "events", "description": "Event-name canonicalization (Issue #36 / D-34). Verifies framework events are emitted with the canonical apcore.. form, that legacy names are dual-emitted with deprecated:true during the v0.21.x cycle, that glob subscriptions match canonical names, and that health-threshold events use the apcore.health.* subsystem.", "test_cases": [ { diff --git a/conformance/fixtures/executor_trace_cancellation.json b/conformance/fixtures/executor_trace_cancellation.json index 4b28aff9..8f697b7e 100644 --- a/conformance/fixtures/executor_trace_cancellation.json +++ b/conformance/fixtures/executor_trace_cancellation.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "call_with_trace / callWithTrace cancellation semantics — cross-language golden test. When the pipeline raises ExecutionCancelledError mid-execution, the trace variant MUST propagate it directly (final error code EXECUTION_CANCELLED) and MUST NOT route it through the on_error middleware chain — i.e. an on_error middleware that would normally swallow/recover errors MUST NOT be able to suppress a cancellation. This mirrors call()/call_async (D-19 trace parity, D-20 cancellation short-circuit). Locks sync finding A-D-001 (Python trace variant previously let PipelineStepError-wrapped cancellation reach on_error). Driver contract per case action below.", "test_cases": [ { diff --git a/conformance/fixtures/extension_point_lookup.json b/conformance/fixtures/extension_point_lookup.json index c9733916..f6cf83c5 100644 --- a/conformance/fixtures/extension_point_lookup.json +++ b/conformance/fixtures/extension_point_lookup.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "D-108 — an unknown extension point is an error; an empty one is not (spec v1.51.0, docs/features/extension-system.md '## An unknown extension point is an error; an empty one is not'). `get`, `get_all` and `unregister` MUST reject a point name that was never registered with InvalidInputError(code=GENERAL_INVALID_INPUT), and MUST NOT raise for a registered point that currently holds nothing. The two halves are load-bearing together: an SDK that answers null/empty/false for a misspelled name turns a typo into a wiring bug that first surfaces at apply(), and an SDK that raises for an empty point breaks every host that probes before registering. Runner: build a FRESH ExtensionManager per case, with the six built-in points ('discoverer', 'middleware', 'acl', 'span_exporter', 'module_validator', 'approval_handler') and nothing registered. For each name in `setup`, register one SDK-native extension of that point's declared type (any trivial instance will do; keep a reference to it). Then perform `operation` on `point_name`. `unregister_target` selects the object handed to `unregister`: 'setup' = the exact object registered by `setup` (same identity), 'stranger' = a freshly built extension of the same type that was NEVER registered. Assertions: when `expected.error_code` is a string the call MUST fail with the framework error carrying that code — an SDK that returns null / an empty collection / false instead is a FAILURE, and so is an SDK that raises a generic language error (KeyError, bare Error) that carries no code. When `expected.error_code` is null the call MUST NOT raise, and the remaining `expected` key is the answer: `value` is 'none' or 'present' for `get`, `count` is the length for `get_all`, `removed` is the boolean for `unregister`.", "test_cases": [ { diff --git a/conformance/fixtures/gate_provider_binding.json b/conformance/fixtures/gate_provider_binding.json index 5a8aca5c..14135d6e 100644 --- a/conformance/fixtures/gate_provider_binding.json +++ b/conformance/fixtures/gate_provider_binding.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Governance providers reach the gate they configure (PROTOCOL_SPEC 6.6.5.4, decision D-129). An ACL, ApprovalHandler or ExecutionPolicy given to an Executor MUST be bound into the built-in gate step of the RUNNING strategy, however that strategy was supplied -- by preset name, by default, or as a pre-built strategy instance -- and governance_state() MUST report the provider the running gate step actually holds. Before D-129 an explicit strategy instance received none of the executor's providers: a deny-all ACL let every call through while governance_state() reported acl_configured and builtin_acl_gate_wired as true.", "driver_contract": { "path": "Construct a real Executor through the public constructor, register the module `demo.target` (a trivial module returning {\"ok\": true}), make one real call as caller `@external` (no caller_id), then read governance_state(). Asserting only governance_state() is not enough: the defect this fixture pins is a call that RAN while the accessor said a gate stood in front of it.", diff --git a/conformance/fixtures/gate_step_configure.json b/conformance/fixtures/gate_step_configure.json index c8bcef35..df6b1d89 100644 --- a/conformance/fixtures/gate_step_configure.json +++ b/conformance/fixtures/gate_step_configure.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "A pipeline `configure` entry cannot weaken a governance gate (PROTOCOL_SPEC 5.16.1, decision D-130). On the built-in gate steps `acl_check` and `approval_gate`, `ignore_errors` turns a denial into a warning and lets the call run, `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. Each MUST be rejected with PIPELINE_CONFIGURATION_ERROR (`pure: true` only on approval_gate: acl_check is pure by default because validate() runs it) while the configuration is turned into a strategy; only `timeout_ms` is configurable on a gate step. Removing a gate step (`remove:`) stays allowed with the existing warning (5.16 requirement 7). Non-gate steps are unaffected.", "driver_contract": { "path": "Build the strategy from `input.yaml` through the SDK's public config path (the same path pipeline_failfast_config.json uses). Assert `expected.raises` at that point, without executing any call.", diff --git a/conformance/fixtures/glob_matching.json b/conformance/fixtures/glob_matching.json index 70510170..172d3ca3 100644 --- a/conformance/fixtures/glob_matching.json +++ b/conformance/fixtures/glob_matching.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Algorithm A25 `match_glob` — PROTOCOL_SPEC 9.2.3. The single matcher for every glob-dialect pattern-valued value in the specification: `bindings.pattern`, `obs.redaction.sensitive_keys` glob entries, event `event_pattern` / `include_events` / `exclude_events`, and `system.control.reload_module`'s `path_filter`. It is NOT the matcher for ACL rule patterns or `match_modules`, which match module IDs with A08 and are pinned by `pattern_matching.json`.\n\nTwo metacharacters and no others: `*` (zero or more characters, crossing `.` and `/`) and `?` (exactly one). Every other character is a literal, `[ ] { } \\ ! ^ -` included. The match is anchored to the whole value. Every string is a valid pattern: A25 has no parse phase and MUST NOT raise or skip.\n\nWHY THIS FIXTURE EXISTS (#116, #117). Before v1.37.0 the specification typed these values with the bare word \"glob\" and named no algorithm, so each SDK delegated to its host library — `pathlib.Path.glob`, `fnmatch`, the `glob` crate, a translated `RegExp` — and inherited that library's dialect. The corpus could not see it: every pattern value in every fixture was `*`, a literal, or leading-star-plus-literal-suffix, which is the one family on which a real glob, a leading-star strip and a first-star removal all coincide. Cases here are therefore chosen by one rule: A CASE EARNS ITS PLACE ONLY IF IT FAILS AGAINST AT LEAST ONE IMPLEMENTATION AS SHIPPED. Of the 32 cases, 13 are marked DISCRIMINATING in their `_why` and name the shipped implementation each one separates; the remaining 19 are marked CONTROL and exist to keep the discriminating cases from being satisfiable by a degenerate matcher.", "test_cases": [ { diff --git a/conformance/fixtures/governance_state.json b/conformance/fixtures/governance_state.json index f070b4f4..cc06c5d5 100644 --- a/conformance/fixtures/governance_state.json +++ b/conformance/fixtures/governance_state.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Executor.governance_state() -- configured vs. actually wired (PROTOCOL_SPEC 6.6.5). `acl != null` means an ACL object is attached, NOT that ACL evaluation runs: the gates are pipeline steps, and the `internal` / `testing` / `minimal` presets remove them. Every field, the derived flag included, MUST be identical across the three SDKs for every case. The accessor is a pure read -- a case that changes executor state has been driven wrong. v1.16.0: the approval half of the derived flag requires all_control_modules_require_approval, because approval_gate is per-module conditional while acl_check is not (6.6.5.1.1).", "driver_contract": { "path": "MUST call the real accessor on a real Executor whose strategy, ACL, handler and policy were set through the public API. Reconstructing the nine booleans in the driver asserts the driver's arithmetic, not the SDK's.", diff --git a/conformance/fixtures/id_conflict_reserved_words.json b/conformance/fixtures/id_conflict_reserved_words.json index 6166592c..384feee6 100644 --- a/conformance/fixtures/id_conflict_reserved_words.json +++ b/conformance/fixtures/id_conflict_reserved_words.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Reserved-word detection in `detect_id_conflicts` (PROTOCOL_SPEC §2.6 step 2, Algorithm A02 family). A reserved word claims a NAMESPACE, not a token, so step 2 tests the FIRST SEGMENT ONLY and segments after the first are unrestricted even when they equal a reserved word. Narrowed in spec v1.26.0 (#99): the algorithm previously read \"for each segment\", which no SDK implemented and which would make ordinary IDs such as `executor.schema.validate` illegal. Driver contract: for each case, run the SDK's public `register()` path — NOT `register_internal()`, which skips the reserved check by design — with `new_id`, having first registered every id in `existing_ids` (absent means none). `expected` is null when registration succeeds, otherwise the conflict `type`. Assert the outcome and, on a conflict, the reported type. `reserved_words` is the canonical set below; a driver MUST read it from the fixture rather than from its own SDK, so a divergent local list fails the case instead of silently agreeing with itself.", "reserved_words": [ "system", diff --git a/conformance/fixtures/id_map_from_config.json b/conformance/fixtures/id_map_from_config.json index 4a03890b..3beab9f4 100644 --- a/conformance/fixtures/id_map_from_config.json +++ b/conformance/fixtures/id_map_from_config.json @@ -1,4 +1,5 @@ { + "profile": "discovery", "description": "PROTOCOL_SPEC §9.1.1 `id_map.overrides` reaches the ID-map mechanism (spec v1.46.0, apcore#118 decision D-71). The MECHANISM was implemented in all three SDKs and the three agreed closely — stage 2 of discovery rewrites a discovered `canonical_id`, and each SDK had a loader for the map file. What none of them had was the CONFIG PATH: the map arrived only through a constructor argument (`Registry(id_map_path=…)` / `idMapPath` / `DefaultDiscoverer::with_id_map`). Measured before the fix: with `id_map.overrides` pointing at a valid map that renames `executor/orig/mod.py`, discovery still registered `executor.orig.mod`. The fourth instance of the shape apcore#118 keeps finding — the mechanism is implemented, the configuration key does not reach it — and the one where a driver calling the loader directly would prove the loader works, which was never the question. Drivers MUST discover from a real directory with a real `apcore.yaml`, and read the registered module IDs.", "test_cases": [ { diff --git a/conformance/fixtures/identity_delegation.json b/conformance/fixtures/identity_delegation.json index 323751f3..ace4e128 100644 --- a/conformance/fixtures/identity_delegation.json +++ b/conformance/fixtures/identity_delegation.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Trusted delegation attenuates explicit scope and binds ACL access to the current actor and root subject.", "driver_contract": "Restore input.identity inside a native Context, then check the root subject and active depth. Where rules are supplied, evaluate an external caller targeting delegation.target using those rules and the supplied or default deny effect.", "test_cases": [ diff --git a/conformance/fixtures/identity_system.json b/conformance/fixtures/identity_system.json index 2d281735..053149a2 100644 --- a/conformance/fixtures/identity_system.json +++ b/conformance/fixtures/identity_system.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Identity construction, field access, and context propagation (AC-014, AC-015)", "test_cases": [ { diff --git a/conformance/fixtures/json_input_native_types.json b/conformance/fixtures/json_input_native_types.json index 18392245..0cce5867 100644 --- a/conformance/fixtures/json_input_native_types.json +++ b/conformance/fixtures/json_input_native_types.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Input validation accepts the JSON the contract describes (type-mapping 17.3 R6, decision D-136). Inputs arrive as JSON, so a date-time, UUID or enum field receives a string, and the module-invocation boundary MUST accept every string the contract's schema accepts — also when the module's contract comes from native types (a date-time class, a UUID class, an enum class) rather than from a JSON Schema document. R5 (no coercion) still holds for what the schema rejects. Measured before D-136: apcore-python validated a natively typed model in pydantic's strict PYTHON mode, which rejects an ISO string for a datetime field, a string for a UUID field and a plain string for an Enum field, so a contract-valid JSON call failed with SCHEMA_VALIDATION_ERROR. Modules declared with a JSON Schema document were unaffected, in all three SDKs.", "spec_sections": [ "type-mapping 17.3", diff --git a/conformance/fixtures/middleware_hardening.json b/conformance/fixtures/middleware_hardening.json index c988c504..b077bfd0 100644 --- a/conformance/fixtures/middleware_hardening.json +++ b/conformance/fixtures/middleware_hardening.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Middleware architecture hardening conformance: context namespacing, CircuitBreakerMiddleware state machine, TracingMiddleware span lifecycle, and async handler detection (Issue #42).", "test_cases": [ { diff --git a/conformance/fixtures/middleware_on_error_recovery.json b/conformance/fixtures/middleware_on_error_recovery.json index 6cdbf057..fd7f9ad4 100644 --- a/conformance/fixtures/middleware_on_error_recovery.json +++ b/conformance/fixtures/middleware_on_error_recovery.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Middleware after-chain error recovery. Verifies that when module execution raises an error, after-middleware still runs and that the first dict returned by any after-middleware replaces the error result (first-dict-wins).", "algorithm": "A11", "test_cases": [ diff --git a/conformance/fixtures/module_lifecycle.json b/conformance/fixtures/module_lifecycle.json index 3f4d99ed..3bfdfbc6 100644 --- a/conformance/fixtures/module_lifecycle.json +++ b/conformance/fixtures/module_lifecycle.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Public lifecycle operations coordinate admission, state transfer, recovery, teardown, cancellation, and event reporting across the three SDKs.", "test_cases": [ { diff --git a/conformance/fixtures/module_output_normalization.json b/conformance/fixtures/module_output_normalization.json index 9de5fc5c..08381baf 100644 --- a/conformance/fixtures/module_output_normalization.json +++ b/conformance/fixtures/module_output_normalization.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Typed module results are delivered as JSON objects through calls, fallback streaming, and native streaming.", "test_cases": [ { diff --git a/conformance/fixtures/multi_module_discovery.json b/conformance/fixtures/multi_module_discovery.json index 80bcb934..c08a2306 100644 --- a/conformance/fixtures/multi_module_discovery.json +++ b/conformance/fixtures/multi_module_discovery.json @@ -1,4 +1,5 @@ { + "profile": "discovery", "description": "Multi-class discovery: ID derivation, snake_case conversion, conflict detection, and backward compatibility (PROTOCOL_SPEC §2.1.1). Opt-in is the per-class `multi_class` marker (D-107, spec v1.50.0); the file-level `multi_class_enabled` input these cases used to carry was the toggle decision-log D-06 withdrew, and pinning it kept all three SDKs passing against a model the spec says does not exist.", "test_cases": [ { diff --git a/conformance/fixtures/multi_root_discovery.json b/conformance/fixtures/multi_root_discovery.json index 9473fe3f..fe45b0a6 100644 --- a/conformance/fixtures/multi_root_discovery.json +++ b/conformance/fixtures/multi_root_discovery.json @@ -1,4 +1,5 @@ { + "profile": "discovery", "description": "PROTOCOL_SPEC §9.1.1 `extensions.roots` — multi-root discovery WITH namespace isolation (spec v1.46.0, apcore#118 decision D-70). `$defs/ExtensionsConfig`'s own description leads with it: \"Supports single root (backward compatible) or multiple roots with namespace isolation.\" Every entry carries a namespace — auto-derived from the last path segment for a bare string, explicit in the object form — and every SDK already had the scanner that applies it (`scan_multi_root` / `scanMultiRoot`). What was missing differed by SDK, which is why this fixture pins both halves: apcore-python and apcore-typescript read the key at all (a multi-root project worked on one SDK of three, silently), and apcore-rust read the paths and DROPPED the namespaces, so module IDs were unprefixed there and prefixed in the other two. `roots` and `root` are exclusive `oneOf` branches, so a document carrying `roots` is in multi-root mode. Drivers MUST discover from a real directory tree and read the registered module IDs.", "test_cases": [ { diff --git a/conformance/fixtures/normalize_id.json b/conformance/fixtures/normalize_id.json index b1d92dcb..efad6573 100644 --- a/conformance/fixtures/normalize_id.json +++ b/conformance/fixtures/normalize_id.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cross-language ID normalization (Algorithm A02)", "test_cases": [ { diff --git a/conformance/fixtures/observability_hardening.json b/conformance/fixtures/observability_hardening.json index b1b207b4..96ae786f 100644 --- a/conformance/fixtures/observability_hardening.json +++ b/conformance/fixtures/observability_hardening.json @@ -1,4 +1,5 @@ { + "profile": "observability", "description": "Observability hardening cross-language conformance: pluggable storage, BatchSpanProcessor, O(log N) ErrorHistory eviction, error fingerprinting, configurable redaction, and K8s/Prometheus integration hooks (Issue #43).", "test_cases": [ { diff --git a/conformance/fixtures/openai_strict_compat.json b/conformance/fixtures/openai_strict_compat.json index ffacf424..f6a0d389 100644 --- a/conformance/fixtures/openai_strict_compat.json +++ b/conformance/fixtures/openai_strict_compat.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cross-language parity for OpenAI structured-outputs strict-mode compatibility detection (protocol-spec §5.12.5). Drives the detector that backs BindingStrictSchemaIncompatibleError on the `auto_schema: strict` binding path.", "keyword_set_source": { "url": "https://developers.openai.com/api/docs/guides/structured-outputs", diff --git a/conformance/fixtures/overrides_store.json b/conformance/fixtures/overrides_store.json index f925efaa..24585ba0 100644 --- a/conformance/fixtures/overrides_store.json +++ b/conformance/fixtures/overrides_store.json @@ -1,4 +1,5 @@ { + "profile": "system-modules", "description": "OverridesStore cross-SDK conformance: pluggable persistence for system.control.update_config and system.control.toggle_feature. The interface is the whole-map form all three SDKs ship (decision D-47): `load() -> mapping` and `save(mapping)`. An earlier revision of this fixture and of features/system-modules.md described a per-key surface — set(key,value) / get(key) / get_all() / delete(key) — that NO SDK implements; three independent implementations agreeing against a spec sentence is the spec being wrong, not three bugs.", "test_cases": [ { diff --git a/conformance/fixtures/pattern_matching.json b/conformance/fixtures/pattern_matching.json index 71e35ad8..dd3196ef 100644 --- a/conformance/fixtures/pattern_matching.json +++ b/conformance/fixtures/pattern_matching.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "ACL pattern matching (Algorithm A09)", "test_cases": [ { diff --git a/conformance/fixtures/pipeline_failfast_config.json b/conformance/fixtures/pipeline_failfast_config.json index a51f5c17..49f43c86 100644 --- a/conformance/fixtures/pipeline_failfast_config.json +++ b/conformance/fixtures/pipeline_failfast_config.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "Pipeline YAML fail-fast conformance (issue #33 §1.2): a `pipeline:` section that names a step which does not exist in the active strategy MUST raise at parse time, not warn and continue. `configure` is an OBJECT MAP keyed by step name — that is what schemas/apcore-config.schema.json $defs/PipelineConfig declares and what all three SDKs parse (apcore-python pipeline_config.py:187, apcore-typescript pipeline-config.ts:244, apcore-rust pipeline_config.rs:320). An earlier revision of this fixture used an array of {name, ...} objects, which no SDK accepts.", "test_cases": [ { diff --git a/conformance/fixtures/pipeline_hardening.json b/conformance/fixtures/pipeline_hardening.json index d42a9dda..2f237458 100644 --- a/conformance/fixtures/pipeline_hardening.json +++ b/conformance/fixtures/pipeline_hardening.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Pipeline execution hardening: fail-fast, replace-step, run_until termination", "test_cases": [ { diff --git a/conformance/fixtures/pipeline_section_wiring.json b/conformance/fixtures/pipeline_section_wiring.json index 8ec92526..7bd9e4cf 100644 --- a/conformance/fixtures/pipeline_section_wiring.json +++ b/conformance/fixtures/pipeline_section_wiring.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "PROTOCOL_SPEC §5.16 requirements 6 and 7 (spec v1.43.0, apcore#118 decision D-72): a `pipeline:` section in the LOADED CONFIGURATION reaches the strategy the executor runs. Three fixtures already pin the builder — `pipeline_failfast_config.json`, `pipeline_hardening.json`, `pipeline_step_middleware.json` — and all three hand the section straight to `build_strategy_from_config(section, …)`. That is exactly the blind spot: the builder was never the broken part. Its first parameter is a dict the CALLER supplies, and in all three SDKs nothing extracted that dict from a `Config`, so `pipeline: remove: [acl_check]` in apcore.yaml left all eleven steps in place while every builder fixture stayed green. Every case here therefore MUST be driven through the SDK's own client/executor construction from `input.config` — a driver that calls the builder directly reproduces the defect and passes. The asymmetry is why these are MUSTs: failing to REMOVE a step is fail-safe, failing to INSERT one is not, because a declared audit, rate-limit or authorization step that never runs is invisible from inside the running system.", "test_cases": [ { diff --git a/conformance/fixtures/pipeline_step_middleware.json b/conformance/fixtures/pipeline_step_middleware.json index c4ffc376..720540b8 100644 --- a/conformance/fixtures/pipeline_step_middleware.json +++ b/conformance/fixtures/pipeline_step_middleware.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Pipeline StepMiddleware lifecycle (Issue #33): before_step / after_step / on_step_error invocation order, recovery semantics, error propagation, and async support. The callbacks are before_step(step_name, state), after_step(step_name, state, result), on_step_error(step_name, state, error) — all three SDKs agree, and `state` is the PipelineState view. There is NO step-inputs parameter: a Step is execute(ctx), so nothing exists for a middleware to replace. References features/middleware-system.md 'Pipeline Step Middleware'.", "test_cases": [ { diff --git a/conformance/fixtures/post_validation_policy.json b/conformance/fixtures/post_validation_policy.json index ecd9cd57..5d7472c2 100644 --- a/conformance/fixtures/post_validation_policy.json +++ b/conformance/fixtures/post_validation_policy.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Exercise the opted-in post-validation policy through the public Executor call, preflight, stream and scoped resumption paths.", "driver_contract": { "module_id": "demo.policy", diff --git a/conformance/fixtures/preflight_check_reporting.json b/conformance/fixtures/preflight_check_reporting.json index ac6f90e4..c4a7ac67 100644 --- a/conformance/fixtures/preflight_check_reporting.json +++ b/conformance/fixtures/preflight_check_reporting.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Executor.validate() reports every check (PROTOCOL_SPEC 12.8.1 principle 2, decision D-134) and reports module-level preflight/preview as 12.8.3 / 12.8.5.1 say (decision D-141). Before D-134 all three SDKs ran the dry run fail-fast: the first failing check ended it, and apcore-python and apcore-typescript also discarded every check that had passed before it. The one exception stays: after a failed `acl` check, module-level preflight() and preview() are withheld (12.8.5.1, pinned by preflight_disclosure.json). D-141: a module without preflight() MAY still yield a passed `module_preflight` check; preview() returning null adds no `module_preview` check; `predicted_changes` is always present, empty when nothing is predicted.", "spec_sections": [ "PROTOCOL_SPEC 12.8.1", diff --git a/conformance/fixtures/preflight_disclosure.json b/conformance/fixtures/preflight_disclosure.json index 63dedd34..5895aff3 100644 --- a/conformance/fixtures/preflight_disclosure.json +++ b/conformance/fixtures/preflight_disclosure.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Executor.validate() MUST NOT disclose module-level introspection to a caller the ACL denied (PROTOCOL_SPEC §12.8.5.1). preflight() and preview() are module-authored code whose output names what a call would do — the resolved binary and argv of a command-wrapping module, the target of a write. Module lookup (Step 3) precedes the ACL check (Step 4), so guarding these hooks on 'lookup succeeded' alone runs them for a denied caller and returns what they say. All three SDKs did exactly that until spec v1.13.0. The rule is about AUTHORIZATION, not validity: a failed schema check does not suppress introspection, because a caller the ACL permits is entitled to hear what the module would do even when its inputs are malformed.", "driver_contract": { "path": "MUST drive the real Executor.validate() against a real Registry and a real ACL — not a hand-assembled PreflightResult. The defect this fixture pins lives in validate()'s own gating, so a driver that constructs the result itself asserts nothing.", diff --git a/conformance/fixtures/redaction_config.json b/conformance/fixtures/redaction_config.json index 87c63ab1..8f4ceb23 100644 --- a/conformance/fixtures/redaction_config.json +++ b/conformance/fixtures/redaction_config.json @@ -1,4 +1,5 @@ { + "profile": "config", "description": "Redaction configuration via obs.redaction.regex_patterns and obs.redaction.sensitive_keys. Replaces the legacy hardcoded _secret_ key prefix. PROTOCOL_SPEC 10.6.1 governs the matching: `sensitive_keys` is a per-entry hybrid — an entry containing `*` or `?` is a glob-dialect pattern matched with algorithm A25 (anchored to the whole field name), an entry containing neither is a case-insensitive substring match against the normalized name; `regex_patterns` is an UNANCHORED, case-insensitive SEARCH over the string form of the value. The 'full regex match' this description claimed until v1.37.0 described no implementation — all three search — and every regex case here was anchored with ^...$, so the corpus could not tell. trace_id, caller_id, target_id, module_id and span_id MUST NEVER be redacted. See docs/features/redaction.md#configured-rules-obsredaction.", "test_cases": [ { diff --git a/conformance/fixtures/registry_load_ordering.json b/conformance/fixtures/registry_load_ordering.json index d00eacc4..45777383 100644 --- a/conformance/fixtures/registry_load_ordering.json +++ b/conformance/fixtures/registry_load_ordering.json @@ -1,4 +1,5 @@ { + "profile": "discovery", "description": "Registry on_load ordering invariants (Issue #65). Verifies the strong-guarantee: a module MUST NOT become visible to discovery APIs until all on_load callbacks have completed successfully. On callback failure the module MUST NOT become visible and the registry MUST emit apcore.registry.module_load_failed.", "test_cases": [ { diff --git a/conformance/fixtures/schema_content_hash.json b/conformance/fixtures/schema_content_hash.json index fec06c04..9def1519 100644 --- a/conformance/fixtures/schema_content_hash.json +++ b/conformance/fixtures/schema_content_hash.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cross-language schema content-hash canonicalization parity. Each test case provides a schema whose canonical serialization is sensitive to a known divergence source: float rendering (1.0 vs 1), non-ASCII Unicode in strings/keys, large-integer precision, key ordering, and a plain baseline. SDKs MUST canonicalize each schema and compute its content hash; the hashes are compared CROSS-REPO for byte-for-byte agreement. No `expected` hash is recorded here \u2014 each SDK computes it and the harness asserts all three implementations agree. Supports finding A-D-037. See `docs/features/schema-system.md` content-addressable cache and \u00a74.15.", "test_cases": [ { diff --git a/conformance/fixtures/schema_export_envelope.json b/conformance/fixtures/schema_export_envelope.json index 54f46dc7..869f026a 100644 --- a/conformance/fixtures/schema_export_envelope.json +++ b/conformance/fixtures/schema_export_envelope.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cross-language parity for `Registry.export_schema(module_id, strict)` — the exact envelope pinned by schemas/module-schema-export.schema.json. Four keys, no more. This fixture exists because the three SDKs each emitted a different shape: apcore-python added an always-empty `definitions` (a SchemaDefinition field a descriptor does not have, so `$defs` was already inside input_schema where JSON Schema puts it), apcore-typescript added `name`, `version`, `tags`, `annotations` and `examples` — making its export a partial, non-conforming duplicate of system.manifest.module — and apcore-rust emitted the four correct keys. A polyglot caller reading result['input_schema'] got a value on two SDKs and the right answer by accident on the third.", "driver_contract": { "path": "Drive the registry method directly — apcore-python `Registry.export_schema(module_id, strict)`, apcore-typescript `registry.exportSchema(moduleId, strict)`, apcore-rust `Registry::export_schema(name, strict)`. Not the serializing helper, not a profile export: this pins the in-memory envelope.", diff --git a/conformance/fixtures/schema_hardening_cache.json b/conformance/fixtures/schema_hardening_cache.json index 5e29a6ed..6e124a44 100644 --- a/conformance/fixtures/schema_hardening_cache.json +++ b/conformance/fixtures/schema_hardening_cache.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Content-addressable schema cache: deduplication by SHA-256 of canonical JSON. Implementations must return the same cached model for schemas with identical content regardless of load path or key order. PROTOCOL_SPEC §4.15.", "test_cases": [ { diff --git a/conformance/fixtures/schema_hardening_constraints.json b/conformance/fixtures/schema_hardening_constraints.json index 0dc7c973..11b6f493 100644 --- a/conformance/fixtures/schema_hardening_constraints.json +++ b/conformance/fixtures/schema_hardening_constraints.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Rust validator parity: numerical constraints (minimum, maximum, exclusiveMinimum), string constraints (minLength, maxLength, pattern), and not keyword. All three SDKs must reject inputs that violate these constraints. PROTOCOL_SPEC §4.15.", "test_cases": [ { diff --git a/conformance/fixtures/schema_hardening_formats.json b/conformance/fixtures/schema_hardening_formats.json index 53e7fb0b..af55a5bb 100644 --- a/conformance/fixtures/schema_hardening_formats.json +++ b/conformance/fixtures/schema_hardening_formats.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Semantic format mapping: format keyword validation for date-time, date, email, uri, uuid, ipv4, ipv6. `format` is an ANNOTATION, not an assertion — a non-conforming value MUST still validate; warning on it is SHOULD-level, which is what the warn_logged signal records. Authority: type-mapping §11.1. PROTOCOL_SPEC §4.15 carries the same rule as two edge-case rows.", "driver_contract": { "valid": "The `valid` expectation is normative and MUST be driven on the module-invocation path (the SDK's schema conversion + validator). `format` is an annotation, not an assertion (JSON Schema 2020-12 §7.2.1, type-mapping §11.1): a non-conforming value MUST NOT fail validation, and an unrecognised format MUST pass silently.", diff --git a/conformance/fixtures/schema_hardening_recursive.json b/conformance/fixtures/schema_hardening_recursive.json index ac6ce23d..91c93ea0 100644 --- a/conformance/fixtures/schema_hardening_recursive.json +++ b/conformance/fixtures/schema_hardening_recursive.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Recursive schema support: TreeNode self-referencing pattern via $ref, depth 1-5 validation, invalid child types, empty and absent children. PROTOCOL_SPEC §4.15.", "schema": { "$id": "TreeNode", diff --git a/conformance/fixtures/schema_hardening_union.json b/conformance/fixtures/schema_hardening_union.json index f798a690..38d1e382 100644 --- a/conformance/fixtures/schema_hardening_union.json +++ b/conformance/fixtures/schema_hardening_union.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Union type evaluation (anyOf/oneOf/allOf): all-branches exhaustive evaluation, ambiguous-oneOf rejection, no-match errors. PROTOCOL_SPEC §4.15.", "test_cases": [ { diff --git a/conformance/fixtures/schema_keyword_parity.json b/conformance/fixtures/schema_keyword_parity.json index 1d7727dc..8509e1f8 100644 --- a/conformance/fixtures/schema_keyword_parity.json +++ b/conformance/fixtures/schema_keyword_parity.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cross-language parity for JSON Schema keyword handling at the validation boundary (spec §4.15, JSON Schema 2020-12 §6 validation keywords, §10.2/§10.3 applicators and §11 unevaluated locations).", "driver_contract": { "path": "MUST drive the module validation path. Exercise schema-to-native conversion and validation with apcore-python generate_model() + model_validate(strict=True), apcore-typescript jsonSchemaToTypeBox() + SchemaValidator.validate(), and apcore-rust validate_against_schema(). Cases marked exercise_module_boundary also drive public module calls in both directions with a directly declared JSON Schema. Assert payload preservation on success, error code and any expected_keyword on failure, and that rejected input prevents module execution.", diff --git a/conformance/fixtures/schema_strict_conversion.json b/conformance/fixtures/schema_strict_conversion.json index 9c11cecc..02aa17c7 100644 --- a/conformance/fixtures/schema_strict_conversion.json +++ b/conformance/fixtures/schema_strict_conversion.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cross-language parity for Algorithm A23 `to_strict_schema()` (PROTOCOL_SPEC §4.16 / ALGORITHMS A23). Pins the exact strict-mode schema all three SDKs must emit for the same input, byte-for-byte after JSON parsing.", "driver_contract": { "path": "MUST drive the SDK's A23 entry point directly — apcore-python `apcore.schema.to_strict_schema()`, apcore-typescript `toStrictSchema()`, apcore-rust `apcore::to_strict_schema()`. Not the exporter, not the binding wrapper: A23 is the shared deterministic surface.", diff --git a/conformance/fixtures/schema_validation.json b/conformance/fixtures/schema_validation.json index 52f5ada7..7d3dfbcf 100644 --- a/conformance/fixtures/schema_validation.json +++ b/conformance/fixtures/schema_validation.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cross-language schema validation edge cases (spec S4.15)", "test_cases": [ { diff --git a/conformance/fixtures/sensitive_keys_default.json b/conformance/fixtures/sensitive_keys_default.json index 40830498..ff988cf5 100644 --- a/conformance/fixtures/sensitive_keys_default.json +++ b/conformance/fixtures/sensitive_keys_default.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Canonical default obs.redaction.sensitive_keys list (D-54). All 3 SDKs MUST ship the exact 16-entry default when no override is provided. The match is case-insensitive substring against field names. Override (via apcore.yaml obs.redaction.sensitive_keys) MUST replace the default, not merge. The leading _secret_* entry preserves the legacy _secret_-prefix behavior under the canonical default. trace_id, caller_id, target_id, module_id, span_id MUST NEVER be redacted regardless of sensitive_keys content. See docs/features/redaction.md#default-sensitive_keys.", "test_cases": [ { diff --git a/conformance/fixtures/specificity.json b/conformance/fixtures/specificity.json index fae8a896..6d80a23f 100644 --- a/conformance/fixtures/specificity.json +++ b/conformance/fixtures/specificity.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "ACL pattern specificity scoring (Algorithm A10)", "test_cases": [ { diff --git a/conformance/fixtures/storage_backend.json b/conformance/fixtures/storage_backend.json index c09c64ab..76c93e0c 100644 --- a/conformance/fixtures/storage_backend.json +++ b/conformance/fixtures/storage_backend.json @@ -1,4 +1,5 @@ { + "profile": "observability", "description": "StorageBackend cross-SDK conformance: pluggable storage primitive shared by ErrorHistory, UsageCollector, and MetricsCollector. Verifies the four-method contract (save, get, list, delete), namespace isolation, and idempotent delete (Issue #43, D-39).", "test_cases": [ { diff --git a/conformance/fixtures/stream_aggregation.json b/conformance/fixtures/stream_aggregation.json index c3364a4a..71a5111a 100644 --- a/conformance/fixtures/stream_aggregation.json +++ b/conformance/fixtures/stream_aggregation.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Stream chunk aggregation conformance \u2014 all SDKs MUST use recursive deep merge with max depth 32. Objects merge recursively; non-objects use last-value-wins.", "test_cases": [ { diff --git a/conformance/fixtures/stream_completion.json b/conformance/fixtures/stream_completion.json index 2cb12565..fc5bec7b 100644 --- a/conformance/fixtures/stream_completion.json +++ b/conformance/fixtures/stream_completion.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "The opt-in completion handle reports one invocation's canonical JSON output, individual post-processing outcomes, and terminal reason, including on close or failure.", "driver_contract": "Drive the public stream-with-completion API. `mode` chooses native streaming or single-call fallback. The fixture module emits the objects in `chunks`, or `chunks[0]` for fallback. Validation `invalid`, `ignored`, `recovered`, and `no_match` use a schema requiring an integer value. `ignored` configures ignore_errors and `recovered` uses step middleware recovery. Validation `removed` and `no_match` remove or scope that step. After `mutate` changes `value` to 2 in place; `fail` raises MODULE_EXECUTE_ERROR; `cancel` raises EXECUTION_CANCELLED. `execution_count` counts module body entry, not an iterator pull. For early close, cancellation or timeout, settle and observe completion independently of producer cleanup. For `timeout_after_first` hold the producer's next item past the deadline. For `timeout_during_after` or `cancel_during_after`, start the final pull, wait until after has entered its blocked callback, then allow the caller deadline or cancellation to settle completion before releasing the callback. For `recover_after_first`, outer module on_error returns {\"recovered\":true}. Project idiomatic field names to snake_case in assertions.", "test_cases": [ diff --git a/conformance/fixtures/stream_post_processing.json b/conformance/fixtures/stream_post_processing.json index 7c9954fa..219d3114 100644 --- a/conformance/fixtures/stream_post_processing.json +++ b/conformance/fixtures/stream_post_processing.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Cancellation from stream post-processing reaches the consumer after the last data chunk (D-20). Ordinary post-processing failures still end the iterator and emit a diagnostic.", "test_cases": [ { diff --git a/conformance/fixtures/system_modules_hardening.json b/conformance/fixtures/system_modules_hardening.json index 3dee4a15..9f47ef4d 100644 --- a/conformance/fixtures/system_modules_hardening.json +++ b/conformance/fixtures/system_modules_hardening.json @@ -1,4 +1,5 @@ { + "profile": "system-modules", "description": "System modules hardening: config persistence, contextual audit trail, Prometheus UsageCollector metrics, path-filter reload, and startup failure handling. Closes Issue #45.", "test_cases": [ { diff --git a/conformance/fixtures/timeout_cancellation.json b/conformance/fixtures/timeout_cancellation.json index 10ce82ec..9483483f 100644 --- a/conformance/fixtures/timeout_cancellation.json +++ b/conformance/fixtures/timeout_cancellation.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "A timeout cancels the timed-out call's own cancel token and raises MODULE_TIMEOUT at once; every call receives a child token of its caller's (PROTOCOL_SPEC 12.7.5, Algorithm A22, decision D-133). Before D-133 no SDK cancelled any token on a timeout, and each nested call SHARED its caller's token object, so the two obvious fixes are both wrong: cancelling the shared token on a nested timeout also cancels the caller, which is then unable to catch the error and continue. The cases below pin both directions: a timeout MUST cancel the timed-out call's token (fails the status quo), and MUST NOT reach the caller's token or the token the application supplied (fails the shared-token fix). There is no grace period and no forced termination.", "spec_sections": [ "PROTOCOL_SPEC 12.7.5", diff --git a/conformance/fixtures/toggle_state_isolation.json b/conformance/fixtures/toggle_state_isolation.json index 34c2f0be..41a2417b 100644 --- a/conformance/fixtures/toggle_state_isolation.json +++ b/conformance/fixtures/toggle_state_isolation.json @@ -1,4 +1,5 @@ { + "profile": "system-modules", "description": "Per-APCore-instance ToggleState isolation (issue #71). Each APCore instance owns one ToggleState, injected into BOTH the toggle module (write path) and the pipeline lookup step (read path). Disabling a module on one instance MUST NOT affect another instance in the same process, and toggle state survives reload of its own instance (A-D-12, re-scoped from process-global to instance-scoped). Runner: construct the named instances in a single process; apply each operation in order through the owning instance's toggle write path; then assert each instance's disabled-set as observed through that instance's read path (the pipeline lookup / is_module_disabled), NOT the process-global fallback. The `reload` action re-registers modules on the instance but MUST preserve its ToggleState. `module_id` values are opaque identifiers the runner may register as no-op modules.", "test_cases": [ { diff --git a/conformance/fixtures/trace_context.json b/conformance/fixtures/trace_context.json index 071dd2a0..47891680 100644 --- a/conformance/fixtures/trace_context.json +++ b/conformance/fixtures/trace_context.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "TraceContext W3C alignment (Issue #35): tracestate ordered propagation with 32-entry cap and malformed-entry tolerance, case-insensitive header lookup, dynamic trace_flags honoring on extract→inject roundtrip, and optional `parent_id` override on inject() validated against ^[0-9a-f]{16}$. See docs/features/observability.md §W3C Alignment Rules.", "test_cases": [ { diff --git a/conformance/fixtures/tracing_from_config.json b/conformance/fixtures/tracing_from_config.json index 4b4d162d..bb33e98f 100644 --- a/conformance/fixtures/tracing_from_config.json +++ b/conformance/fixtures/tracing_from_config.json @@ -1,4 +1,5 @@ { + "profile": "observability", "description": "PROTOCOL_SPEC §10.1.1 (spec v1.44.0, apcore#118 decision D-68 C'): `observability.tracing.*` in the LOADED CONFIGURATION reaches the middleware the client runs. Five keys, one unit — and treating them as five independent keys is what kept all five inert. Two of them, `strategy` and `otlp_endpoint`, were declared by §9.15.2's namespace registration and by NO schema, so `_config.strict` rejected them as unknown while the specification documented their defaults; the other three were deprecated in v1.39.0 on the finding that nothing read them. Every case here MUST be driven through the SDK's own client construction from `input.config`: a driver that calls the SDK's tracing-middleware builder directly proves the builder works, which was never in doubt, and passes on the implementation this fixture exists to rule out. `expected.tracing_middleware_count` is the observable the whole section turns on — before v1.44.0 it was 0 for every configuration in this file.", "test_cases": [ { diff --git a/conformance/fixtures/usage_contract.json b/conformance/fixtures/usage_contract.json index 476ce44a..889208bc 100644 --- a/conformance/fixtures/usage_contract.json +++ b/conformance/fixtures/usage_contract.json @@ -1,4 +1,5 @@ { + "profile": "system-modules", "description": "system.usage.* value semantics that no JSON Schema can assert (PROTOCOL_SPEC 6.7.1). The two schemas sys-usage-summary/sys-usage-module lock the SHAPE; a full-history call_count and an off-by-one p99_latency_ms are both well-typed numbers in the right field, so they need fixed inputs and expected outputs instead. Cases 1-3 pin the p99 disagreement (apcore-python returned sorted[rank] where apcore-typescript and apcore-rust returned sorted[rank-1]); cases 4-6 pin that `period` filters rather than being echoed (apcore-rust echoed it and computed over the full retained history); cases 7-9 pin the period grammar at the input-validation boundary; case 10 pins the hour-key format and the 24-entry invariant; case 11 pins the unattributed caller_id.", "driver_contract": { "path": "MUST drive the real UsageCollector and the real system.usage.* modules through Executor.call() \u2014 not the collector's internal accessors directly. Every divergence this fixture pins lives in the sys-module layer's choice of accessor (apcore-rust called get_all_summaries() where a period-aware variant existed), so a driver that calls get_summary_for_period() itself asserts the layer that was never wrong.", diff --git a/conformance/fixtures/usage_exporter.json b/conformance/fixtures/usage_exporter.json index 561b5e48..2a1aa145 100644 --- a/conformance/fixtures/usage_exporter.json +++ b/conformance/fixtures/usage_exporter.json @@ -1,4 +1,5 @@ { + "profile": "observability", "description": "UsageExporter push interface (#45 §3, D-55). All 3 SDKs MUST ship a UsageExporter Protocol/interface/trait, NoopUsageExporter (default, drops summaries), and PeriodicUsageExporter (bundled timer wrapper, default interval_seconds=3600). PeriodicUsageExporter.start() spawns a background task that polls UsageCollector.summary() at the configured interval and calls exporter.export(summary). PeriodicUsageExporter.stop() halts the loop and awaits exporter.shutdown(). stop() MUST be idempotent. See docs/features/metrics-and-usage.md#usageexporter-push-style.", "test_cases": [ { diff --git a/conformance/fixtures/version_negotiation.json b/conformance/fixtures/version_negotiation.json index 894f3598..287bf788 100644 --- a/conformance/fixtures/version_negotiation.json +++ b/conformance/fixtures/version_negotiation.json @@ -1,4 +1,5 @@ { + "profile": "core", "description": "Version negotiation (Algorithm A14)", "test_cases": [ { diff --git a/python/src/apcore/_sync_bridge.py b/python/src/apcore/_sync_bridge.py index 13b2d802..c62e643b 100644 --- a/python/src/apcore/_sync_bridge.py +++ b/python/src/apcore/_sync_bridge.py @@ -53,7 +53,7 @@ def run(self, coro: Coroutine[Any, Any, Any], module_id: str, wait: float | None try: with self._lock: owner: _ThreadLoop | None = getattr(self._local, "owner", None) - if owner is None or owner.retired: + if owner is None or owner.retired or owner.loop.is_closed(): owner = _ThreadLoop() self._local.owner = owner self._loops.add(owner) @@ -70,6 +70,15 @@ def run(self, coro: Coroutine[Any, Any, Any], module_id: str, wait: float | None if owner.retired: owner.close() + @staticmethod + def retain_invocation(task: asyncio.Future[Any] | None) -> None: + """Let a timed-out pipeline invocation drain on its bridge worker.""" + if task is not None and not task.done(): + invocations = getattr(_worker_thread, "invocations", None) + if invocations is not None: + invocations.add(task) + task.add_done_callback(invocations.discard) + def _run_on_worker(self, coro: Coroutine[Any, Any, Any], module_id: str, wait: float | None) -> Any: deadline = None if wait is None else time.monotonic() + wait reentrant = getattr(_worker_thread, "active", False) @@ -94,6 +103,8 @@ def _run_on_worker(self, coro: Coroutine[Any, Any, Any], module_id: str, wait: f def run() -> None: nonlocal worker _worker_thread.active = True + invocations: set[asyncio.Future[Any]] = set() + _worker_thread.invocations = invocations try: if expired.is_set() or (deadline is not None and time.monotonic() >= deadline): coro.close() @@ -110,8 +121,15 @@ def run() -> None: finally: # Publish before draining so D-133 timeout/cancellation # never waits for cooperative cleanup on the caller. - pending = asyncio.all_tasks(loop) try: + # Late dispatches may still need tasks they spawned. + # Let the invocation drain before cancelling leftovers. + while invocations: + loop.run_until_complete(asyncio.gather(*invocations, return_exceptions=True)) + pending = asyncio.all_tasks(loop) + for remaining_task in pending: + if not remaining_task.cancelling(): + remaining_task.cancel() if pending: loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True)) finally: @@ -124,6 +142,7 @@ def run() -> None: _logger.warning("Sync bridge cleanup failed", exc_info=True) finally: _worker_thread.active = False + del _worker_thread.invocations self._slots.release() try: diff --git a/python/src/apcore/async_task.py b/python/src/apcore/async_task.py index 2c8abb35..7303301f 100644 --- a/python/src/apcore/async_task.py +++ b/python/src/apcore/async_task.py @@ -964,7 +964,13 @@ async def _run( if await self._store_reached_terminal(task_id): return - if retry_policy is None or info.retry_count >= max_retries: + if ( + retry_policy is None + or info.retry_count >= max_retries + or ( + isinstance(attempt_error, ModuleError) and attempt_error.code == ErrorCodes.CALL_BUDGET_EXCEEDED + ) + ): await self._persist_terminal( dataclasses.replace( info, status=TaskStatus.FAILED, completed_at=time.time(), error=str(attempt_error) diff --git a/python/src/apcore/bound_module.py b/python/src/apcore/bound_module.py index 1f614fb4..d5cfeede 100644 --- a/python/src/apcore/bound_module.py +++ b/python/src/apcore/bound_module.py @@ -5,13 +5,13 @@ import inspect from collections.abc import Callable, Coroutine from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, Self, TypeVar, get_origin, get_type_hints, overload +from typing import TYPE_CHECKING, Any, ParamSpec, Protocol, Self, TypeVar, get_type_hints, overload -from pydantic import BaseModel, TypeAdapter +from pydantic import TypeAdapter from pydantic_core import PydanticSerializationError, to_json from apcore.context import Context, _APPROVAL_TOKEN_KEY -from apcore.decorator import FunctionModule, _context_param_name, _forward_function +from apcore.decorator import FunctionModule, _context_param_name, _forward_function, _has_object_output from apcore.module import PreflightResult, PreviewResult if TYPE_CHECKING: @@ -150,9 +150,7 @@ def bind(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> inspect.BoundAr def result(self, output: dict[str, Any]) -> Any: if self.return_type is type(None): return None - object_result = self.return_type is dict or get_origin(self.return_type) is dict - model_result = isinstance(self.return_type, type) and issubclass(self.return_type, BaseModel) - payload = output if object_result or model_result else output["result"] + payload = output if _has_object_output(self.return_type) else output["result"] try: encoded = to_json(payload) except PydanticSerializationError: diff --git a/python/src/apcore/context.py b/python/src/apcore/context.py index 29c5444d..6f089e0a 100644 --- a/python/src/apcore/context.py +++ b/python/src/apcore/context.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import math import time import uuid from collections.abc import Awaitable, Callable, Sequence @@ -348,6 +349,15 @@ def __post_init__(self) -> None: raise InvalidInputError("Declined or cancelled elicitation must have no content") +def _finite_progress_value(value: object) -> bool: + if not isinstance(value, (int, float)) or isinstance(value, bool): + return False + try: + return math.isfinite(value) + except OverflowError: + return False + + ProgressReporter = Callable[[float, float | None, str | None], Awaitable[None]] ElicitationHandler = Callable[[str, dict[str, Any] | None], Awaitable[ElicitationResult]] @@ -495,14 +505,21 @@ def _with_local_binding(self) -> Context[T]: async def report_progress(self, progress: float, total: float | None = None, message: str | None = None) -> None: """Report progress to the attached host callback when one is available.""" callback = self._progress_reporter - if callback is not None: - await self._wait_for_interaction(lambda: callback(progress, total, message)) + if callback is None: + return + if not _finite_progress_value(progress) or (total is not None and not _finite_progress_value(total)): + raise InvalidInputError("Progress and total must be finite numbers") + await self._wait_for_interaction(lambda: callback(progress, total, message)) async def elicit(self, message: str, requested_schema: dict[str, Any] | None = None) -> ElicitationResult | None: """Ask the host for optional structured input.""" callback = self._elicitation_handler if callback is None: return None + if requested_schema is not None and ( + not isinstance(requested_schema, dict) or not all(isinstance(key, str) for key in requested_schema) + ): + raise InvalidInputError("Requested elicitation schema must be an object") result = await self._wait_for_interaction(lambda: callback(message, requested_schema)) if not isinstance(result, ElicitationResult): raise InvalidInputError("Expected an ElicitationResult from the handler") diff --git a/python/src/apcore/decorator.py b/python/src/apcore/decorator.py index a04e430e..90bd6c36 100644 --- a/python/src/apcore/decorator.py +++ b/python/src/apcore/decorator.py @@ -8,11 +8,14 @@ import logging import re import typing -from collections.abc import Awaitable +from collections.abc import Awaitable, Mapping +from types import UnionType from typing import Annotated, Any, Callable, get_args, get_origin -from pydantic import BaseModel, ConfigDict, Field, create_model +from pydantic import BaseModel, ConfigDict, Field, GetJsonSchemaHandler, RootModel, create_model from pydantic.fields import FieldInfo +from pydantic_core import CoreSchema +from typing_extensions import is_typeddict from apcore._docstrings import parse_docstring from apcore.context import Context @@ -101,39 +104,57 @@ def generate_input_model( return create_model("InputModel", **field_dict) -def generate_output_model(func: Any) -> type[BaseModel]: - """Convert a function's return type annotation into a Pydantic BaseModel. - - - dict / dict[str, T] -> permissive model (extra="allow") - - BaseModel subclass -> returned directly - - None -> empty permissive model - - Other types -> model with single "result" field - """ +def _output_annotation(func: Callable) -> Any: try: hints = typing.get_type_hints(func, include_extras=True) except NameError: hints = {} - - return_type = hints.get("return") - if return_type is None and "return" not in hints: + if "return" not in hints: raise FuncMissingReturnTypeError(function_name=func.__name__) + return hints["return"] - # Handle None return type - if return_type is None or return_type is type(None): - return create_model("OutputModel", __config__=ConfigDict(extra="allow")) - # Handle BaseModel subclass - if isinstance(return_type, type) and issubclass(return_type, BaseModel): - return return_type +def _has_object_output(annotation: Any, *, root: bool = False) -> bool: + """Determine whether a return type has an object-shaped wire payload.""" + origin = get_origin(annotation) + if root and origin is Annotated: + return _has_object_output(get_args(annotation)[0], root=True) + if root and origin in (UnionType, typing.Union): + return all(_has_object_output(item, root=True) for item in get_args(annotation)) + + cls = origin or annotation + if is_typeddict(cls): + return True + if not isinstance(cls, type): + return False + if issubclass(cls, RootModel): + return _has_object_output(cls.model_fields["root"].annotation, root=True) + return issubclass(cls, BaseModel) or (issubclass(cls, Mapping) if root else cls is dict) - # Handle dict (bare or parameterized) - if return_type is dict or get_origin(return_type) is dict: - return create_model("OutputModel", __config__=ConfigDict(extra="allow")) - # All other types: wrap in a model with a "result" field +class _TypedDictOutput(RootModel): + @classmethod + def __get_pydantic_json_schema__(cls, schema: CoreSchema, handler: GetJsonSchemaHandler) -> dict[str, Any]: + # Protocol adapters consume an explicit object-shaped root schema. + return handler.resolve_ref_schema(super().__get_pydantic_json_schema__(schema, handler)) + + +def _output_model(return_type: Any) -> type[BaseModel]: + origin = get_origin(return_type) or return_type + if return_type is type(None) or origin is dict: + return create_model("OutputModel", __config__=ConfigDict(extra="allow")) + if is_typeddict(origin): + return typing.cast(type[BaseModel], _TypedDictOutput.__class_getitem__(return_type)) + if isinstance(return_type, type) and issubclass(return_type, BaseModel) and _has_object_output(return_type): + return return_type return create_model("OutputModel", result=(return_type, ...)) +def generate_output_model(func: Callable) -> type[BaseModel]: + """Generate an object schema for a function's declared return type.""" + return _output_model(_output_annotation(func)) + + def _context_param_name(func: Any) -> str | None: """Return the name of the parameter typed as ``Context``, or None. @@ -155,12 +176,12 @@ def _context_param_name(func: Any) -> str | None: return None -def _normalize_result(result: Any) -> dict[str, Any]: - """Normalize a function's return value to a dict for the executor pipeline.""" - if result is None: +def _normalize_result(result: Any, *, wrap_result: bool) -> dict[str, Any]: + """Normalize a function's return value to the declared wire shape.""" + if result is None and not wrap_result: return {} result = normalize_module_output(result) - if isinstance(result, dict): + if isinstance(result, dict) and not wrap_result: return result return {"result": result} @@ -198,7 +219,12 @@ def __init__( doc_desc, doc_body, param_descs = parse_docstring(func) self.input_schema = input_schema if input_schema is not None else generate_input_model(func, param_descs) - self.output_schema = output_schema if output_schema is not None else generate_output_model(func) + wrap_result = False + if output_schema is None: + return_type = _output_annotation(func) + output_schema = _output_model(return_type) + wrap_result = return_type is not type(None) and not _has_object_output(return_type) + self.output_schema = output_schema context_param_name = _context_param_name(func) positional_only = [ @@ -261,7 +287,7 @@ def call_arguments(inputs: dict[str, Any], context: Context) -> tuple[list[Any], async def _async_execute(inputs: dict[str, Any], context: Context) -> dict[str, Any]: args, kwargs = call_arguments(inputs, context) result = await func(*args, **kwargs) - return _normalize_result(result) + return _normalize_result(result, wrap_result=wrap_result) self.execute = _async_execute else: @@ -269,7 +295,7 @@ async def _async_execute(inputs: dict[str, Any], context: Context) -> dict[str, def _sync_execute(inputs: dict[str, Any], context: Context) -> dict[str, Any]: args, kwargs = call_arguments(inputs, context) result = func(*args, **kwargs) - return _normalize_result(result) + return _normalize_result(result, wrap_result=wrap_result) self.execute = _sync_execute diff --git a/python/src/apcore/executor.py b/python/src/apcore/executor.py index 0ba3649c..362181c4 100644 --- a/python/src/apcore/executor.py +++ b/python/src/apcore/executor.py @@ -1156,6 +1156,8 @@ async def _run_call( continue output = recovery trace = pipe_ctx.trace or PipelineTrace(module_id=module_id, strategy_name=effective_strategy.name) + finally: + self._sync_bridge.retain_invocation(pipe_ctx.module_task) if attempted_steps: trace.steps[:0] = attempted_steps trace.total_duration_ms = (time.monotonic() - started) * 1000 @@ -1907,13 +1909,14 @@ def governance_state(self) -> GovernanceState: # only when no built-in gate is wired ("configured and not wired"). acl_gates = [step for step in steps if isinstance(step, BuiltinACLCheck)] approval_gates = [step for step in steps if isinstance(step, BuiltinApprovalGate)] + # Mixed providers are not reported as a fully configured stage. if acl_gates: - acl_configured = any(gate.acl is not None for gate in acl_gates) + acl_configured = all(gate.acl is not None for gate in acl_gates) else: acl_configured = self._acl is not None if approval_gates: - handler_configured = any(gate.handler is not None for gate in approval_gates) - policy_strict = any(gate.policy.strict for gate in approval_gates) + handler_configured = all(gate.handler is not None for gate in approval_gates) + policy_strict = all(gate.policy.strict for gate in approval_gates) else: handler_configured = self._approval_handler is not None policy_strict = self._policy is not None and bool(getattr(self._policy, "strict", False)) diff --git a/python/tests/test_async_task.py b/python/tests/test_async_task.py index 9fa10a07..c3b8ab1d 100644 --- a/python/tests/test_async_task.py +++ b/python/tests/test_async_task.py @@ -174,11 +174,9 @@ async def test_cancel_nonexistent_task(self, manager: AsyncTaskManager) -> None: @pytest.mark.asyncio async def test_cancel_completed_task(self, manager: AsyncTaskManager) -> None: task_id = await manager.submit("test.simple", {"x": 1}) - await asyncio.sleep(0.1) - - info = manager.get_status(task_id) - assert info is not None - assert info.status == TaskStatus.COMPLETED + async with asyncio.timeout(3): + while (info := manager.get_status(task_id)) is None or info.status is not TaskStatus.COMPLETED: + await asyncio.sleep(0.01) result = await manager.cancel(task_id) assert result is False @@ -639,6 +637,22 @@ async def test_retry_exhausted_then_failed(self, failing_executor: Executor) -> assert info.attempt_number == 2 assert info.max_retries == 2 + async def test_exhausted_call_budget_does_not_retry(self, executor: Executor) -> None: + from apcore import CallBudget, Context + from apcore.async_task import RetryConfig + + policy = RetryConfig(max_retries=2, retry_delay_ms=0) + context = Context.create().with_budget(CallBudget(max_calls=0)) + spy = _SpyStore() + manager = AsyncTaskManager(executor, store=spy) + task_id = await manager.submit("test.simple", {"x": 1}, context=context, retry_policy=policy) + async with asyncio.timeout(3): + while (info := await manager.get_status_async(task_id)) is None or info.status is not TaskStatus.FAILED: + await asyncio.sleep(0.01) + assert "CALL_BUDGET_EXCEEDED" in (info.error or "") + assert info.retry_count == 0 + assert spy.put_statuses == [TaskStatus.PENDING, TaskStatus.RUNNING, TaskStatus.FAILED] + @pytest.mark.asyncio async def test_status_sequence_includes_pending_during_backoff(self, failing_executor: Executor) -> None: """TC-015 (post-D-12): backoff state is PENDING (was RETRYING). diff --git a/python/tests/test_bound_module.py b/python/tests/test_bound_module.py index 7e1b423c..432d388c 100644 --- a/python/tests/test_bound_module.py +++ b/python/tests/test_bound_module.py @@ -7,7 +7,8 @@ from uuid import UUID import pytest -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, RootModel +from typing_extensions import TypedDict from apcore import ( ACL, @@ -80,6 +81,42 @@ def save(order: Order, /, quantity: int = 1, *, multiplier: int = 2) -> Receipt: bound.invoke(order, quantity="2") # type: ignore[arg-type] +class Coordinates(TypedDict): + x: int + y: int + + +async def test_bound_module_typed_dict_has_direct_validated_wire_shape() -> None: + client = APCore() + + @client.module("shape.coordinates") + async def coordinates() -> Coordinates: + return {"x": 2, "y": 3} + + assert await coordinates.invoke_async() == {"x": 2, "y": 3} + assert await client.call_async("shape.coordinates", {}) == {"x": 2, "y": 3} + schema = coordinates.apcore_module.output_schema.model_json_schema() + assert schema["type"] == "object" + assert schema["required"] == ["x", "y"] + + +def test_bound_module_root_models_preserve_native_and_wire_shapes() -> None: + client = APCore() + + @client.module("shape.list") + def list_root() -> RootModel[list[int]]: + return RootModel[list[int]]([2, 3]) + + @client.module("shape.mapping") + def object_root() -> RootModel[dict[str, int]]: + return RootModel[dict[str, int]]({"count": 2}) + + assert list_root.invoke().root == [2, 3] + assert client.call("shape.list", {}) == {"result": [2, 3]} + assert object_root.invoke().root == {"count": 2} + assert client.call("shape.mapping", {}) == {"count": 2} + + def test_bound_module_keeps_the_native_union_branch() -> None: client = APCore() diff --git a/python/tests/test_executor_async.py b/python/tests/test_executor_async.py index 8d0b6b01..948682bc 100644 --- a/python/tests/test_executor_async.py +++ b/python/tests/test_executor_async.py @@ -370,6 +370,63 @@ async def test_unbounded_constructor_bridge_wait_preserves_pipeline_timeout(self ex.call("test.module", {}) assert raised.value.details["timeout_ms"] == 10 + @pytest.mark.parametrize("times_out", [False, True]) + async def test_bridge_cancels_background_tasks_after_draining_invocation(self, times_out: bool) -> None: + from threading import Event + + started = Event() + stopped = Event() + completed = Event() + loops: list[asyncio.AbstractEventLoop] = [] + tasks: list[asyncio.Task[None]] = [] + + async def background() -> None: + started.set() + try: + await asyncio.Future() + finally: + stopped.set() + + class BackgroundModule(AsyncModule): + resources = {"timeout": 20} if times_out else {} + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + loops.append(asyncio.get_running_loop()) + tasks.append(asyncio.create_task(background())) + await asyncio.sleep(0.05 if times_out else 0) + completed.set() + return await super().execute(inputs, context) + + with _make_executor(module=BackgroundModule()) as executor: + if times_out: + with pytest.raises(ModuleTimeoutError): + executor.call("test.module", {}) + else: + assert executor.call("test.module", {}) == {"greeting": "Hello, World"} + assert started.is_set() + try: + assert stopped.wait(2) + assert completed.is_set() + finally: + if not stopped.is_set(): + loops[0].call_soon_threadsafe(tasks[0].cancel) + stopped.wait(1) + + def test_bridge_replaces_closed_thread_loop(self) -> None: + loops: list[asyncio.AbstractEventLoop] = [] + + class LoopModule(AsyncModule): + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + loops.append(asyncio.get_running_loop()) + return await super().execute(inputs, context) + + with _make_executor(module=LoopModule()) as executor: + assert executor.call("test.module", {}) == {"greeting": "Hello, World"} + loops[0].close() + + assert executor.call("test.module", {}) == {"greeting": "Hello, World"} + assert loops[1] is not loops[0] + # === Async middleware === diff --git a/python/tests/test_governance_state.py b/python/tests/test_governance_state.py index 7e25cc7a..d41328df 100644 --- a/python/tests/test_governance_state.py +++ b/python/tests/test_governance_state.py @@ -82,6 +82,29 @@ def test_acl_configured_but_internal_strategy_has_no_acl_step(self) -> None: # `acl is not None` would report this as protected. It is not. assert state.unprotected_control_surface is True + def test_mixed_builtin_gates_report_incomplete_configuration(self) -> None: + from apcore.builtin_steps import BuiltinACLCheck, BuiltinApprovalGate + + client = _client(SYS_ON) + acl = BuiltinACLCheck(acl=ACL(default_effect="deny")) + secondary_acl = BuiltinACLCheck() + secondary_acl.name = "secondary_acl" + approval = BuiltinApprovalGate(handler=_AlwaysApprove()) + secondary_approval = BuiltinApprovalGate(policy=ExecutionPolicy(strict=False)) + secondary_approval.name = "secondary_approval" + strategy = ExecutionStrategy( + "mixed", [acl, secondary_acl, approval, secondary_approval], validate_dependencies=False + ) + + state = _executor(client, strategy).governance_state() + + assert state.builtin_acl_gate_wired + assert state.builtin_approval_gate_wired + assert not state.acl_configured + assert not state.approval_handler_configured + assert not state.policy_strict + assert state.unprotected_control_surface + class TestGateDetectionIsByType: def test_custom_step_named_acl_check_is_not_the_builtin(self) -> None: diff --git a/python/tests/test_realtime_context.py b/python/tests/test_realtime_context.py index 0212a7c5..337787b6 100644 --- a/python/tests/test_realtime_context.py +++ b/python/tests/test_realtime_context.py @@ -8,7 +8,7 @@ from apcore import APCore, CancelToken, Context, ElicitationResult from apcore.cancel import ExecutionCancelledError -from apcore.errors import ModuleTimeoutError +from apcore.errors import InvalidInputError, ModuleTimeoutError async def test_callbacks_are_inherited_and_excluded_from_wire_context() -> None: @@ -42,6 +42,32 @@ async def confirm(ctx: Context[Any]) -> bool: assert observed == [(1, 2, "Preparing")] +async def test_optional_interaction_without_callbacks_does_not_dispatch() -> None: + context: Context[Any] = Context.create() + await context.report_progress(float("nan")) + assert await context.elicit("Optional", []) is None # type: ignore[arg-type] + + +@pytest.mark.parametrize("progress,total", [(float("nan"), None), (1, float("inf")), (True, None), (10**400, None)]) +async def test_report_progress_rejects_invalid_numbers(progress: float, total: float | None) -> None: + async def reporter(*_: Any) -> None: + pytest.fail("Invalid progress reached the host callback") + + context: Context[Any] = Context.create() + with pytest.raises(InvalidInputError): + await context.with_progress_reporter(reporter).report_progress(progress, total) + + +@pytest.mark.parametrize("schema", [[], True, {1: "not a JSON object key"}]) +async def test_elicit_rejects_non_object_requested_schema(schema: Any) -> None: + async def handler(*_: Any) -> ElicitationResult: + pytest.fail("Invalid schema reached the host callback") + + context: Context[Any] = Context.create() + with pytest.raises(InvalidInputError): + await context.with_elicitation_handler(handler).elicit("Enter a value", schema) + + async def test_realtime_wait_stops_on_parent_cancellation_and_expired_deadline() -> None: token = CancelToken() started = asyncio.Event() diff --git a/rust/src/async_task.rs b/rust/src/async_task.rs index 0be6b5f8..03068a88 100644 --- a/rust/src/async_task.rs +++ b/rust/src/async_task.rs @@ -1130,7 +1130,7 @@ async fn run_task( } Err(err) => { if let Some(cfg) = retry.as_ref() { - if info.retry_count < max_retries { + if info.retry_count < max_retries && err.code != ErrorCode::CallBudgetExceeded { let delay_ms = cfg.compute_delay_ms(info.retry_count); match queue_retry(store.as_ref(), &info, &transition).await { Ok(true) => { diff --git a/rust/src/builtin_steps.rs b/rust/src/builtin_steps.rs index be270a87..3dc0bcce 100644 --- a/rust/src/builtin_steps.rs +++ b/rust/src/builtin_steps.rs @@ -1038,9 +1038,6 @@ impl BuiltinPostValidationPolicy { .take() .ok_or_else(|| missing_pipeline_input("policy_approval_annotations"))?; let required = annotations.requires_approval || effect == PolicyEffect::RequireApproval; - if !required { - ctx.reject_unconsumed_scoped_approval()?; - } if required || ctx.has_approval_credential() { let Some(handler) = ctx.approval_handler.clone() else { return Err(BuiltinApprovalGate::reject_unavailable_handler( @@ -1077,8 +1074,18 @@ impl BuiltinPostValidationPolicy { let Some(emitter) = ctx.event_emitter.as_ref() else { return; }; + let rule_id = verdict.rule_id.as_deref().filter(|id| { + let Some((first, tail)) = id.as_bytes().split_first() else { + return false; + }; + id.len() <= 64 + && first.is_ascii_alphanumeric() + && tail + .iter() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b'-')) + }); let mut data = serde_json::json!({ - "rule_id": verdict.rule_id, + "rule_id": rule_id, "decision": verdict.decision, "sensitive_fields": request.sensitive_fields, }); diff --git a/rust/src/sys_modules/mod.rs b/rust/src/sys_modules/mod.rs index 1aa0af1b..1fab9b83 100644 --- a/rust/src/sys_modules/mod.rs +++ b/rust/src/sys_modules/mod.rs @@ -345,7 +345,17 @@ fn audit_identity(identity: &crate::Identity) -> serde_json::Value { } if let Some(fields) = snapshot.as_object_mut() { for (key, value) in identity.attrs() { - if !matches!(key.as_str(), "id" | "type" | "roles") { + if !matches!( + key.as_str(), + "id" | "type" + | "roles" + | "actor_id" + | "subject_id" + | "delegation_depth" + | "issuer" + | "scopes" + | "on_behalf_of" + ) { fields.insert(key.clone(), redact_identity_attr(key, value)); } } @@ -416,6 +426,44 @@ mod identity_audit_tests { use super::augment_with_context_identity; use crate::context::{Context, Identity}; use serde_json::{json, Value}; + use std::collections::HashMap; + + #[test] + fn atlas_audit_identity_attrs_cannot_supply_authority_fields() { + let root = Identity::new( + "subject".into(), + "user".into(), + vec![], + [ + ("issuer".into(), json!("untrusted-issuer")), + ("scopes".into(), json!(["untrusted-scope"])), + ("on_behalf_of".into(), json!({"id": "untrusted-parent"})), + ("actor_id".into(), json!("untrusted-actor")), + ("subject_id".into(), json!("untrusted-subject")), + ("delegation_depth".into(), json!(7)), + ("department".into(), json!("support")), + ] + .into_iter() + .collect(), + ); + let event = augment_with_context_identity(json!({}), &Context::::new(root.clone())); + assert_eq!( + event["identity"], + json!({"id":"subject", "type":"user", "department":"support"}) + ); + + let actor = Identity::new("agent".into(), "agent".into(), vec![], HashMap::new()); + let delegated = root + .with_authority(Some(vec!["read".into()]), None) + .unwrap() + .delegate(actor, vec!["read".into()]) + .unwrap(); + let event = augment_with_context_identity(json!({}), &Context::::new(delegated)); + assert_eq!( + event["identity"]["on_behalf_of"], + json!({"id":"subject", "type":"user", "department":"support", "scopes":["read"]}) + ); + } #[test] fn scoped_audit_redacts_nested_attributes_at_every_hop() { diff --git a/rust/tests/call_budget.rs b/rust/tests/call_budget.rs index ebea9634..68c95c0e 100644 --- a/rust/tests/call_budget.rs +++ b/rust/tests/call_budget.rs @@ -393,3 +393,35 @@ async fn custom_strategy_without_a_stock_call_chain_guard_cannot_spend_budget() .unwrap(); assert_eq!(approved["started"], 1); } + +#[tokio::test] +async fn atlas_audit_exhausted_background_budget_is_terminal_without_retry() { + use apcore::{AsyncRetryConfig, AsyncTaskManager, TaskStatus}; + use std::time::Duration; + + let client = APCore::new(); + register(&client, false, false); + let manager = AsyncTaskManager::new(client.executor_arc(), 1, 10); + let context = Context::::anonymous().with_budget(Some(budget(Some(0), None))); + let mut retry = AsyncRetryConfig::default(); + retry.max_retries = 1; + retry.retry_delay_ms = 5; + let task = manager + .submit_with_retry("test.cost", json!({}), Some(context), Some(retry)) + .await + .unwrap(); + let info = tokio::time::timeout(Duration::from_secs(2), async { + loop { + let info = manager.get_status_async(&task).await.unwrap().unwrap(); + if info.status == TaskStatus::Failed { + break info; + } + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); + assert_eq!(info.retry_count, 0); + assert!(info.error.unwrap().starts_with("[CallBudgetExceeded]")); + manager.shutdown().await.unwrap(); +} diff --git a/rust/tests/post_validation_policy.rs b/rust/tests/post_validation_policy.rs index 504b5a46..2dedc164 100644 --- a/rust/tests/post_validation_policy.rs +++ b/rust/tests/post_validation_policy.rs @@ -72,6 +72,7 @@ impl Probe { struct Evaluator { decision: String, + rule_id: String, observed: Mutex>, } @@ -96,7 +97,7 @@ impl PolicyEvaluator for Evaluator { }; Ok(PolicyVerdict { decision, - rule_id: Some("fixture-rule".to_string()), + rule_id: Some(self.rule_id.clone()), }) } } @@ -413,6 +414,7 @@ fn register_probe(registry: &Registry, version: &str, probe: Probe) { fn spy_evaluator(verdict: &str) -> Arc { Arc::new(Evaluator { decision: verdict.to_string(), + rule_id: "fixture-rule".into(), observed: Mutex::new(Vec::new()), }) } @@ -719,11 +721,75 @@ async fn scoped_approval_cannot_resume_under_a_different_subject_or_ceiling() { ); assert!(handler.scope.lock().unwrap().is_some()); } + executor + .set_policy_evaluator(Some(spy_evaluator("allow"))) + .unwrap(); assert!(executor - .call(target, credential, Some(&original), None) + .call(target, credential.clone(), Some(&original), None) .await .is_ok()); assert!(handler.scope.lock().unwrap().is_none()); + assert_eq!( + executor + .call(target, credential, Some(&original), None) + .await + .unwrap_err() + .code, + ErrorCode::ApprovalDenied + ); + assert_eq!(handler.checks.load(Ordering::Relaxed), 4); + assert_eq!(handler.requested.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn atlas_audit_policy_event_only_includes_safe_rule_ids() { + use apcore::events::{ApCoreEvent, EventEmitter, EventSubscriber}; + + #[derive(Debug, Default)] + struct Events(Arc>>); + + #[async_trait] + impl EventSubscriber for Events { + async fn on_event(&self, event: &ApCoreEvent) -> Result<(), ModuleError> { + if event.event_type == "apcore.policy.decision" { + self.0.lock().unwrap().push(event.data["rule_id"].clone()); + } + Ok(()) + } + } + + let events = Events::default(); + let captured = Arc::clone(&events.0); + let emitter = EventEmitter::new(); + emitter.subscribe(Box::new(events)); + let mut executor = Executor::new(probe_registry("1.0.0"), Config::in_memory()); + executor.set_event_emitter(Some(Arc::new(emitter))); + for label in [ + "fixture.rule-1", + "invalid label", + "_prefixed", + &"x".repeat(65), + ] { + let evaluator = Arc::new(Evaluator { + decision: "allow".into(), + rule_id: label.into(), + observed: Mutex::new(Vec::new()), + }); + executor.set_policy_evaluator(Some(evaluator)).unwrap(); + executor + .call("demo.policy", json!({}), None, None) + .await + .unwrap(); + } + assert_eq!( + *captured.lock().unwrap(), + vec![ + json!("fixture.rule-1"), + Value::Null, + Value::Null, + Value::Null + ] + ); } #[tokio::test] diff --git a/typescript/src/builtin-steps.ts b/typescript/src/builtin-steps.ts index b2477606..fc6a0808 100644 --- a/typescript/src/builtin-steps.ts +++ b/typescript/src/builtin-steps.ts @@ -20,7 +20,7 @@ import { CancelToken, awaitExecution } from './cancel.js'; import { bindBudgetContext, commitBudgetCall, recordBudgetProducer, reserveBudgetCall } from './call-budget.js'; import { Context } from './context.js'; import { assertDeclarationInvocation, recordDeclarationDispatch } from './declaration-invocation.js'; -import { authorityKeyOf, hasScopeCeiling } from './identity.js'; +import { authorityKeyOf, delegationDepthOf, hasScopeCeiling, isTrustedIdentity, rootSubjectOf } from './identity.js'; import { assertScopedInvocation, isStockScopeAcl, recordScopedGrant, recordScopedLookup } from './scoped-invocation.js'; import { ACLDeniedError, @@ -892,12 +892,21 @@ class BuiltinPostValidationPolicy implements Step { assertPolicyBinding(ctx, invocation); const verdict = await evaluatePolicy(this.evaluator, ctx, invocation, invocation.validated); assertPolicyBinding(ctx, invocation); - if (!invocation.preflight && this.emitter) { - this.emitter.emit(createEvent('apcore.policy.decision', ctx.moduleId, verdict.decision === 'deny' ? 'warn' : 'info', { + if (!invocation.preflight) { + const identity = ctx.context.identity; + const data = { decision: verdict.decision, ...(verdict.ruleId === undefined ? {} : { rule_id: verdict.ruleId }), sensitive_fields: [...invocation.validated.sensitiveFields], - })); + ...(isTrustedIdentity(identity) && identity.scopes !== undefined ? { + actor_id: identity.id, + subject_id: rootSubjectOf(identity).id, + delegation_depth: delegationDepthOf(identity), + } : {}), + }; + const eventType = 'apcore.policy.decision'; + auditSpan(ctx.context)?.events.push({ name: eventType, ...data }); + this.emitter?.emit(createEvent(eventType, ctx.moduleId, verdict.decision === 'deny' ? 'warn' : 'info', data)); } if (verdict.decision === 'deny') throw new PolicyDeniedError(ctx.moduleId); diff --git a/typescript/src/context.ts b/typescript/src/context.ts index e94dd35a..ccd775e9 100644 --- a/typescript/src/context.ts +++ b/typescript/src/context.ts @@ -258,15 +258,24 @@ export class Context { /** Report progress if the invocation has a reporter. */ async reportProgress(progress: number, total?: number, message?: string): Promise { const reporter = this._progressReporter; - if (reporter !== null) await this._runInteraction(async () => reporter(progress, total, message)); + if (reporter === null) return; + if (!Number.isFinite(progress) || (total !== undefined && !Number.isFinite(total))) { + throw new InvalidInputError('Progress and total must be finite'); + } + await this._runInteraction(async () => reporter(progress, total, message)); } /** Request structured input if the invocation has an elicitation handler. */ async elicit(message: string, requestedSchema?: Record): Promise { const handler = this._elicitationHandler; if (handler === null) return null; + if (requestedSchema !== undefined && !isRecord(requestedSchema)) { + throw new InvalidInputError('Elicitation requires a schema object'); + } const result = await this._runInteraction(async () => handler(message, requestedSchema)); - if (result?.action === 'decline' || result?.action === 'cancel') return { action: result.action }; + if ((result?.action === 'decline' || result?.action === 'cancel') && !('content' in result)) { + return { action: result.action }; + } if (result?.action === 'accept' && isRecord(result.content)) return { action: 'accept', content: result.content }; throw new InvalidInputError('Elicitation handler returned an invalid result'); } diff --git a/typescript/src/durable-input.ts b/typescript/src/durable-input.ts index 5163f7ba..6a904336 100644 --- a/typescript/src/durable-input.ts +++ b/typescript/src/durable-input.ts @@ -89,15 +89,16 @@ export function prepareInputResume( nowMs: number, ): InputResume { if (!validClock(nowMs)) throw new InvalidInputError('Invalid input resume clock'); - const { requestId, expiresAtMs, moduleId, moduleVersion, callerId: expectedCaller, owner, businessArgs } = parseRecord(record); - if (nowMs >= expiresAtMs || callerId !== expectedCaller || !matchesOwner(identity, owner)) throw unavailable(); - - let snapshot: ReturnType; + let submittedAnswer: unknown; try { - snapshot = snapshotJsonObject({ ...businessArgs, input_request_id: requestId, answer }); + submittedAnswer = snapshotJsonObject({ answer }).arguments['answer']; } catch { throw new InvalidInputError('The submitted answer is not a canonical JSON value'); } + const { requestId, expiresAtMs, moduleId, moduleVersion, callerId: expectedCaller, owner, businessArgs } = parseRecord(record); + if (nowMs >= expiresAtMs || callerId !== expectedCaller || !matchesOwner(identity, owner)) throw unavailable(); + + const snapshot = snapshotJsonObject({ ...businessArgs, input_request_id: requestId, answer: submittedAnswer }); const canonical = snapshot.canonical.join(''); const argumentsSnapshot = snapshot.arguments; const resume: InputResume = { diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index 13649895..ccbf3645 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -804,7 +804,7 @@ export class Executor { const parent = (context ?? Context.create()).withExecutor(this); const provider = this._capabilitySearchProvider; const position = options.cursor == null - ? { candidates: this._capabilityCandidates(parent, provider, filters.query), offset: 0 } + ? { candidates: this._capabilityCandidates(parent, provider, filters), offset: 0 } : this._capabilityCursors.read(options.cursor, context, filters); const items: ModuleSummary[] = []; let nextCursor: string | null = null; @@ -855,12 +855,15 @@ export class Executor { } private _capabilityCandidates( - parent: Context, provider: CapabilitySearchProvider | null, query: string, + parent: Context, provider: CapabilitySearchProvider | null, filters: ReturnType, ): string[] { const ids = this._registry.list(); if (provider === null) return ids; - const eligible = new Set(ids.filter(id => this._discoverCapability(id, parent) !== null)); - const ranked = provider.search(query || undefined, [...eligible]); + const eligible = new Set(ids.filter(id => { + const summary = this._capabilitySummary(id, parent); + return summary !== null && matchesCapability(summary, filters, false); + })); + const ranked = provider.search(filters.query || undefined, [...eligible]); if (!Array.isArray(ranked)) throw new InvalidInputError('Capability search must return a list of module IDs'); return [...new Set(ranked)].filter(id => eligible.has(id)); } diff --git a/typescript/src/identity.ts b/typescript/src/identity.ts index 0e8612c7..67a592be 100644 --- a/typescript/src/identity.ts +++ b/typescript/src/identity.ts @@ -1,5 +1,6 @@ /** Trusted caller identity and its active local delegation chain. */ +import { InvalidInputError } from './errors.js'; import { compareCodePoints } from './utils/compare-code-points.js'; export const MAX_DELEGATION_DEPTH = 8; @@ -26,23 +27,23 @@ export class Identity { ) { const { scopes, onBehalfOf, issuer } = options; if (scopes !== undefined && (!Array.isArray(scopes) || ![...scopes].every(isScopeLiteral))) { - throw new TypeError('Identity scopes must be a list of nonempty strings without whitespace'); + throw new InvalidInputError('Identity scopes must be a list of nonempty strings without whitespace'); } if (issuer !== undefined && !isNonemptyString(issuer)) { - throw new TypeError('Identity issuer must be a nonempty string'); + throw new InvalidInputError('Identity issuer must be a nonempty string'); } if ((scopes !== undefined || issuer !== undefined || onBehalfOf !== undefined) && (!isNonemptyString(id) || !isNonemptyString(type) || !Array.isArray(roles) || ![...roles].every(role => typeof role === 'string') || !isRecord(attrs))) { - throw new TypeError('Invalid scoped identity'); + throw new InvalidInputError('Invalid scoped identity'); } if (onBehalfOf !== undefined) { if (!isTrustedIdentity(onBehalfOf) || delegationDepthOf(onBehalfOf) >= MAX_DELEGATION_DEPTH) { - throw new TypeError('Invalid identity delegation chain'); + throw new InvalidInputError('Invalid identity delegation chain'); } const ceiling = onBehalfOf.scopes; if (scopes === undefined || ceiling === undefined || !scopes.every(scope => ceiling.includes(scope))) { - throw new TypeError('Delegated scopes must be a subset of the parent scopes'); + throw new InvalidInputError('Delegated scopes must be a subset of the parent scopes'); } } this.id = id; @@ -72,11 +73,11 @@ export class Identity { /** Issue explicitly attenuated authority to the supplied actor. */ delegate(actor: Identity, scopes: readonly string[]): Identity { if (!isTrustedIdentity(actor) || actor.onBehalfOf !== undefined) { - throw new TypeError('A trusted direct actor is required'); + throw new InvalidInputError('A trusted direct actor is required'); } const ceiling = actor.scopes; if (ceiling !== undefined && (!Array.isArray(scopes) || !scopes.every(scope => ceiling.includes(scope)))) { - throw new TypeError('Delegated scopes must be a subset of the actor scopes'); + throw new InvalidInputError('Delegated scopes must be a subset of the actor scopes'); } return new Identity(actor.id, actor.type, actor.roles, actor.attrs, { scopes, onBehalfOf: this, issuer: actor.issuer }); } @@ -142,7 +143,7 @@ export function authorityKeyOf(identity: Identity | null | undefined): string | } function requireTrustedIdentity(identity: Identity): Identity { - if (!isTrustedIdentity(identity)) throw new TypeError('A trusted identity is required'); + if (!isTrustedIdentity(identity)) throw new InvalidInputError('A trusted identity is required'); return identity; } @@ -183,7 +184,7 @@ export function identityFromWire(data: Record, depth: number = (Object.hasOwn(data, 'scopes') && !Array.isArray(scopes)) || (Object.hasOwn(data, 'issuer') && !isNonemptyString(issuer)) || (Object.hasOwn(data, 'on_behalf_of') && !isRecord(parent))) { - throw new TypeError('Invalid wire identity'); + throw new InvalidInputError('Invalid wire identity'); } return new Identity( typeof id === 'string' ? id : String(id ?? ''), diff --git a/typescript/tests/conformance-durable-input.test.ts b/typescript/tests/conformance-durable-input.test.ts index c4b1e84c..b2423bd2 100644 --- a/typescript/tests/conformance-durable-input.test.ts +++ b/typescript/tests/conformance-durable-input.test.ts @@ -73,6 +73,15 @@ describe('durable input bindings', () => { expect(() => new InputRequiredError(requestId, 0)).toThrow(expect.objectContaining({ code: 'GENERAL_INVALID_INPUT' })); }); + it('rejects an invalid answer before inspecting an unavailable record', () => { + const unread = vi.fn(() => undefined); + const record = Object.defineProperty({}, 'request_id', { get: unread, enumerable: true }); + expect(() => prepareInputResume(record, BigInt(10), principal(), null, now)).toThrow( + expect.objectContaining({ code: 'GENERAL_INVALID_INPUT', details: {} }), + ); + expect(unread).not.toHaveBeenCalled(); + }); + it('keeps detached arguments bound by exact canonical equality', () => { const record = durableRecord(); const answer = { values: ['north', false] }; diff --git a/typescript/tests/conformance-identity-delegation.test.ts b/typescript/tests/conformance-identity-delegation.test.ts index f19a010a..13def901 100644 --- a/typescript/tests/conformance-identity-delegation.test.ts +++ b/typescript/tests/conformance-identity-delegation.test.ts @@ -27,7 +27,7 @@ describe('identity_delegation.json', () => { it.each(fixture.test_cases)('$id', async ({ input, expected }) => { const restore = (): Context => Context.fromJSON({ identity: input.identity }); if (!expected.valid) { - expect(restore).toThrow(TypeError); + expect(restore).toThrow(expect.objectContaining({ code: 'GENERAL_INVALID_INPUT' })); return; } const context = restore(); diff --git a/typescript/tests/test-capability-discovery.test.ts b/typescript/tests/test-capability-discovery.test.ts index 46cb0f5c..1490e542 100644 --- a/typescript/tests/test-capability-discovery.test.ts +++ b/typescript/tests/test-capability-discovery.test.ts @@ -6,6 +6,7 @@ import { type ACLRule, type CapabilitySearchOptions, } from '../src/index.js'; import { Config, ExtensionManager, registerSysModules } from '../src/full.js'; +import { ToggleState } from '../src/sys-modules/toggle.js'; import { findFixturesRoot } from './spec-repo.js'; interface DiscoveryCase { @@ -266,6 +267,21 @@ describe('capability discovery lifecycle and identity', () => { expect(executor.getCallableDefinition('demo.review', requester())).toBeNull(); }); + it.each([ + { prefix: 'demo.echo' }, + { tags: ['review'] }, + { readonly: true }, + { includeApprovalRequired: false }, + ] as CapabilitySearchOptions[])('applies structured filters before ranking: %j', async (options) => { + const { registry } = await fixtureRegistry(); + const search = vi.fn(() => ['demo.echo', 'demo.review']); + const executor = new Executor({ registry, toggleState: new ToggleState(), capabilitySearchProvider: { search } }); + const expected = options.tags ? 'demo.review' : 'demo.echo'; + const page = executor.listCallable(requester(), { ...options, query: ' Semantic Query ' }); + expect(search).toHaveBeenCalledExactlyOnceWith('semantic query', [expected]); + expect(page.items.map(({ moduleId }) => moduleId)).toEqual([expected]); + }); + it('does not invoke custom conditions or disclose a candidate after the provider revokes ACL access', async () => { const { registry } = await fixtureRegistry(); const evaluate = vi.fn(async () => false); diff --git a/typescript/tests/test-context-interactions.test.ts b/typescript/tests/test-context-interactions.test.ts index ca9df592..6806aa5a 100644 --- a/typescript/tests/test-context-interactions.test.ts +++ b/typescript/tests/test-context-interactions.test.ts @@ -25,6 +25,28 @@ describe('Context interaction callbacks', () => { await expect(Context.fromJSON(derived.toJSON()).elicit('Name?')).resolves.toBeNull(); }); + it('rejects non-finite progress before invoking the reporter', async () => { + const progress = vi.fn(); + const context = Context.create().withProgressReporter(progress); + await expect(context.reportProgress(NaN)).rejects.toMatchObject({ code: 'GENERAL_INVALID_INPUT' }); + await expect(context.reportProgress(1, Infinity)).rejects.toMatchObject({ code: 'GENERAL_INVALID_INPUT' }); + expect(progress).not.toHaveBeenCalled(); + }); + + it('rejects a non-object elicitation schema before invoking the handler', async () => { + const elicit = vi.fn(() => ({ action: 'cancel' as const })); + const context = Context.create().withElicitationHandler(elicit); + for (const schema of [null, 'answer', [], new Date()] as unknown as Record[]) { + await expect(context.elicit('Answer?', schema)).rejects.toMatchObject({ code: 'GENERAL_INVALID_INPUT' }); + } + expect(elicit).not.toHaveBeenCalled(); + }); + + it.each(['decline', 'cancel'] as const)('rejects content on a %s reply', async (action) => { + const context = Context.create().withElicitationHandler(() => ({ action, content: { answer: 'unexpected' } })); + await expect(context.elicit('Answer?')).rejects.toMatchObject({ code: 'GENERAL_INVALID_INPUT' }); + }); + it('carries callbacks through unary and stream execution contexts', async () => { const client = new APCore(); const progress = vi.fn(async () => {}); diff --git a/typescript/tests/test-identity-delegation.test.ts b/typescript/tests/test-identity-delegation.test.ts index 003bd498..aaa764d2 100644 --- a/typescript/tests/test-identity-delegation.test.ts +++ b/typescript/tests/test-identity-delegation.test.ts @@ -59,10 +59,14 @@ describe('scoped identity delegation', () => { expect(Object.isFrozen(leaf.scopes)).toBe(true); expect(Context.fromJSON(Context.create(leaf).toJSON()).identity?.authorityKey()).toBe(leaf.authorityKey()); expect(Context.create(legacy).toJSON().identity).not.toHaveProperty('scopes'); - expect(() => root.delegate(actor, ['admin'])).toThrow(); + expect(() => root.delegate(actor, ['admin'])).toThrow( + expect.objectContaining({ code: 'GENERAL_INVALID_INPUT' }), + ); expect(() => root.delegate(leaf, ['read'])).toThrow(); const restricted = createIdentity('worker', 'agent', [], {}, { scopes: [] }); - expect(() => root.delegate(restricted, ['read'])).toThrow(); + expect(() => root.delegate(restricted, ['read'])).toThrow( + expect.objectContaining({ code: 'GENERAL_INVALID_INPUT' }), + ); expect(() => root.delegate(actor, ['not\u00a0a.scope'])).toThrow(); expect(() => legacy.delegate(actor, [])).toThrow(); diff --git a/typescript/tests/test-post-validation-policy.test.ts b/typescript/tests/test-post-validation-policy.test.ts index 9953a5f8..78aeb564 100644 --- a/typescript/tests/test-post-validation-policy.test.ts +++ b/typescript/tests/test-post-validation-policy.test.ts @@ -9,6 +9,7 @@ import { Context, createAnnotations, createApprovalResult, + createIdentity, Executor, ModuleError, Registry, @@ -18,6 +19,8 @@ import { type PolicyEvaluationRequest, } from '../src/index.js'; import { ExtensionManager } from '../src/full.js'; +import { EventEmitter } from '../src/events/emitter.js'; +import { InMemoryExporter, TracingMiddleware } from '../src/observability/tracing.js'; import { Middleware } from '../src/middleware/index.js'; import { findFixturesRoot } from './spec-repo.js'; @@ -156,6 +159,44 @@ describe('post_validation_policy.json', () => { }); describe('post-validation policy executor integration', () => { + it.each([true, false])('records scoped policy audit data with event emitter enabled: %s', async (enableEvents) => { + const { registry } = await makeRegistry(); + const exporter = new InMemoryExporter(); + const emitter = enableEvents ? new EventEmitter() : null; + const onEvent = vi.fn(); + emitter?.subscribe({ onEvent, eventPattern: 'apcore.policy.decision' }); + const acl = new ACL([{ + callers: ['@external'], targets: [moduleId], effect: 'allow', description: '', conditions: { scopes: ['execute'] }, + }]); + const executor = new Executor({ + registry, acl, eventEmitter: emitter, middlewares: [new TracingMiddleware(exporter)], + policyEvaluator: { async evaluate() { return { decision: 'allow', ruleId: 'orders.rule-1' }; } }, + }); + const subject = createIdentity('subject', 'user', [], { hidden: 'subject-attribute' }, { scopes: ['execute'] }); + const actor = createIdentity('actor', 'agent', [], { hidden: 'actor-attribute' }); + const context = Context.create(subject.delegate(actor, ['execute'])); + const expected = { + decision: 'allow', rule_id: 'orders.rule-1', sensitive_fields: ['/secret'], + actor_id: 'actor', subject_id: 'subject', delegation_depth: 1, + }; + + await executor.validate(moduleId, input, context); + expect(onEvent).not.toHaveBeenCalled(); + expect(exporter.getSpans().flatMap(span => span.events)).not.toContainEqual( + expect.objectContaining({ name: 'apcore.policy.decision' }), + ); + + await executor.call(moduleId, input, context); + await emitter?.flush(); + if (enableEvents) { + expect(onEvent).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + eventType: 'apcore.policy.decision', data: expected, + })); + } + expect(exporter.getSpans().flatMap(span => span.events)) + .toContainEqual({ name: 'apcore.policy.decision', ...expected }); + }); + it('does not expose an ACL-rejected preflight to the evaluator or preview', async () => { const { registry, preview } = await makeRegistry(); const evaluate = vi.fn(async () => ({ decision: 'allow' as const }));