From b3a6a13024b8ac13f46861fc12e736459be40a90 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 22:42:35 +0800 Subject: [PATCH 1/5] docs(planning): prepare ACL-aware capability discovery Signed-off-by: tercel --- planning/capability-discovery/overview.md | 22 +++++++++ planning/capability-discovery/plan.md | 24 ++++++++++ planning/capability-discovery/state.json | 45 +++++++++++++++++++ .../capability-discovery/tasks/core-sdks.md | 8 ++++ .../tasks/shared-contract.md | 7 +++ .../capability-discovery/tasks/surfaces.md | 18 ++++++++ .../tasks/verification.md | 7 +++ 7 files changed, 131 insertions(+) create mode 100644 planning/capability-discovery/overview.md create mode 100644 planning/capability-discovery/plan.md create mode 100644 planning/capability-discovery/state.json create mode 100644 planning/capability-discovery/tasks/core-sdks.md create mode 100644 planning/capability-discovery/tasks/shared-contract.md create mode 100644 planning/capability-discovery/tasks/surfaces.md create mode 100644 planning/capability-discovery/tasks/verification.md diff --git a/planning/capability-discovery/overview.md b/planning/capability-discovery/overview.md new file mode 100644 index 00000000..4d93dd69 --- /dev/null +++ b/planning/capability-discovery/overview.md @@ -0,0 +1,22 @@ +# ACL-aware Capability Discovery + +Gap 3 follows the merged post-validation policy milestone. The Core base is `0daf50a3`; the Surfaces base is `04e1c698`. The local candidate branches are `core-alpha4` and `surfaces-alpha4`. + +The milestone lets a trusted caller discover public modules that it is authorized to know about. Core owns the visibility decision, summaries, expansion, and pagination. MCP applies the same visibility decision to the modules it already exports and preserves complete `inputSchema` values on standard `tools/list`. + +The [implementation plan](./plan.md) records the proposed contract. The maintainers review and approve changes to the normative protocol specification before it is edited. The target is draft revision 3 on the current protocol version line. + +The merged baseline passed targeted ACL and system manifest checks in all three SDKs. Python passed 349 tests with 3 skips, TypeScript passed 71 tests, and Rust passed 326 tests with 1 ignored test. These runs verify the existing invocation and manifest behavior that discovery must preserve. + +## Acceptance + +- The same shared cases run through Python, TypeScript, and Rust. They cover hidden and inactive modules, caller-sensitive ACL, deferred decisions, approval hints, and cursor isolation. +- MCP client tests compare listing and execution for different authenticated identities and verify that listed tools retain the existing full input schema. +- Core Profile and full SDK checks pass. Surfaces verify against the candidate wheel, npm tarball, and Rust crate and preserve declared stable minimum compatibility where applicable. + +## Tasks + +1. [Shared contract and conformance](./tasks/shared-contract.md) +2. [Core SDKs](./tasks/core-sdks.md) +3. [MCP surfaces](./tasks/surfaces.md) +4. [Dual-repository verification](./tasks/verification.md) diff --git a/planning/capability-discovery/plan.md b/planning/capability-discovery/plan.md new file mode 100644 index 00000000..08cd8234 --- /dev/null +++ b/planning/capability-discovery/plan.md @@ -0,0 +1,24 @@ +# ACL-aware Capability Discovery Implementation Plan + +## Visibility and execution + +`ACL.evaluate_visibility` evaluates the exact caller and target from the same trusted invocation context used by the executor's active built-in ACL gate. Derive the same prospective caller frame and depth as Step 1 without mutating the original context. Reuse pattern matching, structural prechecks, first-match evaluation, and built-in identity, role, and call-depth predicates. Keep the invocation path and its audit behavior intact. + +Discovery has no submitted arguments. Treat argument predicates and custom conditions, including replacements for built-in handlers, as undetermined. Resolve logical compounds with known and undetermined outcomes, then disclose only when all remaining first-match outcomes grant access. A possible deny or an argument-dependent grant with no independent allow stays hidden. Apply the existing fail-closed rules for malformed conditions and keep their diagnostics internal. An installed custom ACL must provide a silent visibility contract before the executor can disclose entries it governs. No ACL installed retains public discovery in the default assembly. + +Visibility runs without module validation, input policy evaluation, approval handling, normal ACL audit logging, denied events, or error-history records. It excludes registrations that are hidden or ineligible for new execution. Use the current registration generation and selected version for both authorization and the returned view. A provider result is a candidate selector and cannot authorize metadata, including forgotten candidates, stale versions, or hidden IDs. + +## Public APIs + +- `Executor` and `APCore` expose `list_callable` and `get_callable_definitions`, with idiomatic SDK naming. `list_callable` returns a `CapabilityPage` of `ModuleSummary` records containing the module ID, resolved version, short description, tags, read-only flag, and an advisory `access_hint`. It returns no schemas, source paths, or arbitrary metadata. +- Match the optional query, prefix, tags, and read-only filters against current public candidates. Default to 20 items with an explicit maximum of 100. Default search needs only deterministic lexical and tag matching. The optional `CapabilitySearchProvider` can supply ranked IDs. The executor filters every returned ID before it reads or returns metadata. +- `get_callable_definitions` returns detached copies of the complete input and output schemas for eligible requested IDs. Missing, denied, and hidden IDs yield omissions with the same response shape. Validate trust and visibility for each request even when an ID came from a previous page. +- Use `requires_approval` when the ACL and normal Step 5 policy guarantee human approval for the invocation. Use `conditional` when an eligible ACL decision can vary in approval outcome or a configured post-validation evaluator can add requirements. Use `allowed` for the remaining eligible entries. Apply `include_approval_required=false` to definite approval entries. Every invocation still runs the usual governance pipeline. +- Cursors are opaque, integrity-protected or server-side, and scoped to the executor, requester identity and roles, relevant trusted context, and normalized filters. Reject invalid, expired, foreign-scope, or incompatible cursors without exposing their bindings. Use stable ordering with a module-ID tie breaker and reauthorize every item at emission. A disappearance or replacement during lookup must not expose a stale definition. +- Add `system.manifest.search` as a separate read-only facade gated by its own ACL. Run discovery with the originating trusted request context and apply target visibility in addition to the facade's ACL. Derive each target frame from the original caller so the search module cannot contribute its own identity, ACL grants, or extra call depth. Preserve `system.manifest.full` and `system.manifest.module` wire contracts and existing access checks. + +## Surfaces + +MCP bridges use the same authenticated identity and caller context as actual invocation. Apply Core visibility per request to the adapter's existing exported-tool candidates. Keep standard schemas, aliases, versions, and capability negotiation. Preserve transport meta-tools on their existing authorization paths. Project module documentation through the same visibility check where discoverable MCP resources expose it. Management manifest resources continue through their own ACL and keep their existing output shapes. + +Build minimal and full Core distributions before checking the installed Surfaces providers. Only MCP changes its protocol projection for this milestone. Test other Surfaces consumers against the built Core artifacts. Delegation, new budgets, and general SDK ergonomics have separate milestones. diff --git a/planning/capability-discovery/state.json b/planning/capability-discovery/state.json new file mode 100644 index 00000000..f78eb00b --- /dev/null +++ b/planning/capability-discovery/state.json @@ -0,0 +1,45 @@ +{ + "feature": "capability-discovery", + "created": "2026-11-27", + "updated": "2026-11-27", + "status": "in_progress", + "execution_order": ["shared-contract", "core-sdks", "surfaces", "verification"], + "progress": { + "total_tasks": 4, + "completed": 0, + "in_progress": 0, + "pending": 3, + "skipped": 0, + "blocked": 1 + }, + "tasks": [ + { + "id": "shared-contract", + "file": "tasks/shared-contract.md", + "title": "Shared contract and conformance", + "status": "blocked", + "blocker": "Maintainer approval for the proposed draft revision" + }, + { + "id": "core-sdks", + "file": "tasks/core-sdks.md", + "title": "Python, TypeScript, and Rust discovery APIs", + "status": "pending", + "dependencies": ["shared-contract"] + }, + { + "id": "surfaces", + "file": "tasks/surfaces.md", + "title": "MCP discovery projection", + "status": "pending", + "dependencies": ["core-sdks"] + }, + { + "id": "verification", + "file": "tasks/verification.md", + "title": "Dual-repository verification", + "status": "pending", + "dependencies": ["core-sdks", "surfaces"] + } + ] +} diff --git a/planning/capability-discovery/tasks/core-sdks.md b/planning/capability-discovery/tasks/core-sdks.md new file mode 100644 index 00000000..69e2adc1 --- /dev/null +++ b/planning/capability-discovery/tasks/core-sdks.md @@ -0,0 +1,8 @@ +# Core SDK Implementation + +The Python, TypeScript, and Rust implementations can proceed in parallel after the shared contract is approved. Each owns its SDK and conformance driver. Use the active built-in pipeline gate lookup and existing effective annotation and approval policy logic. Reuse the registry's registration generation and version resolution to guard the metadata view across asynchronous boundaries. + +1. Add failing public-entry tests from the shared cases. Show that hidden entries stay hidden and single-ID expansion is equally protected. Assert that discovery leaves audit, error history, approval, evaluator, and module callback counters untouched. +2. Add the silent visibility branch at the ACL decision layer. Preserve existing call-path auditing and first-match semantics. Exercise policies with argument-dependent and custom rules without synthesizing request arguments. +3. Build the filtered L1 and L2 projections in the executor, forward the same trusted context from `APCore`, and reuse the same service in the read-only manifest search module. Keep registry factories and application adapters free of authorization logic. +4. Check candidate generation changes, provider output with mixed eligibility, and invalid, expired, tampered, or cross-identity cursors. Run the language-specific checks and fixtures through the normal runtime API. diff --git a/planning/capability-discovery/tasks/shared-contract.md b/planning/capability-discovery/tasks/shared-contract.md new file mode 100644 index 00000000..65560f66 --- /dev/null +++ b/planning/capability-discovery/tasks/shared-contract.md @@ -0,0 +1,7 @@ +# Shared Contract and Conformance + +Approval is pending for the Gap 3 protocol changes. Amend the draft protocol only after maintainer approval. Keep version 2.0.0 and update the draft revision, revision history, changelog, and decision register together. Retain existing anchors and the source of truth for manifest schemas. + +Use the existing root conformance format and inventory checks. Define cases for an authenticated role grant and denial, an unavailable argument or custom condition, compound conditions, an uncertain deny overriding a later grant, a definite human approval requirement, a conditional approval, and a configured final-input evaluator. Include names that are hidden, inactive, absent, moved to a new generation, and injected by a search provider. + +Specify observable behavior for scope-bound cursors, deterministic ordering and normalized filters, zero disclosure for invalid cursors and unapproved IDs, and absence of normal execution effects. Cover both L1 omission of schemas and L2 return of the complete versioned schemas. Exercise the separate manifest search module and compatibility of the existing management manifest calls. diff --git a/planning/capability-discovery/tasks/surfaces.md b/planning/capability-discovery/tasks/surfaces.md new file mode 100644 index 00000000..7be11a82 --- /dev/null +++ b/planning/capability-discovery/tasks/surfaces.md @@ -0,0 +1,18 @@ +# MCP discovery projection + +Pending maintainer approval of the [shared discovery contract](./shared-contract.md). The Core SDK discovery APIs are a prerequisite for this task. + +## Implementation + +- Apply the Core visibility decision to the existing MCP tool candidates on each request. Use the backend that handles calls and the same trusted initiating context. The authenticated principal belongs in `Context.identity`. An external request leaves `caller_id` unset, including over stdio. Let Core derive the prospective caller frame and call depth. +- In Python, use `_request_identity()` in `mcp/python/src/apcore_mcp/server/factory.py` and the context and executor wiring in `server/router.py`. In TypeScript, use the request's `getCurrentIdentity()` and `createBridgeContext` in `mcp/typescript/src/server`, including the standalone and embedded assembly paths in `index.ts`. In Rust, use the `AUTH_IDENTITY` scope already installed by the HTTP auth middleware. Resolve visibility through `ExecutionRouter` and the typed `ApcoreExecutorAdapter`. Preserve existing synchronous server helpers if the wire path needs an async handler. +- Apply the adapter's existing export selection before returning visible tools. Preserve each selected registration's complete MCP `inputSchema`, aliases, version checks and negotiated `outputSchema`. Prevent a replacement registration from authorizing metadata cached for an older registration. Standard `tools/list` keeps its existing result shape and enumerates all eligible exports. Use the separate Core query for paginated summaries and schema expansion. +- Keep approval and async task meta-tools on their current bridge-owned authorization paths. Known-ID calls continue through the normal execution pipeline and retain actual ACL, validation and approval checks. +- Apply the same visibility policy to `docs://` resources during enumeration and direct reads. Treat an ineligible documentation resource like an absent resource. Preserve existing `apcore://system.*` management resources, including their ACL-protected router calls and manifest wire contracts. The optional Explorer has a separate public browsing audience and remains outside this task. + +## Verification + +- Drive an initialized MCP client through `tools/list` and `tools/call` with the real Core executor. Check two authenticated principals with different roles on the same server and an anonymous stdio client. Include an argument-conditional rule, a mandatory approval, and a hidden module. Check that changing the subject or its roles changes the list on the next request and that list requests execute no module or approval callbacks. +- Assert that a visible tool retains its named schema properties and local references. Check older negotiated protocol versions and the default tool version, and verify that a denied known-ID call still fails through the execution pipeline. Reuse the Python versioned-wire session fixture, the TypeScript SDK client with the existing transport fixtures, and the Rust HTTP JSON-RPC test path with the real auth middleware. +- Verify `resources/list` omits denied documentation and `resources/read` rejects a direct denied URI. Confirm an authorized administrator can still invoke the existing manifest resources with their prior response shapes. Keep the approval resumption and async task meta-tool regressions green. +- Test against the installed Core wheel, npm tarball and crate for the exact candidate commits. Re-run the established downstream compatibility matrix and Golden Path without publishing packages. See the [verification task](./verification.md). diff --git a/planning/capability-discovery/tasks/verification.md b/planning/capability-discovery/tasks/verification.md new file mode 100644 index 00000000..0e8d5a2b --- /dev/null +++ b/planning/capability-discovery/tasks/verification.md @@ -0,0 +1,7 @@ +# Dual-repository Verification + +Run shared conformance inventory, minimal and full Core tests, language-specific checks, and strict documentation builds. Build the wheel, npm tarball, and Rust crate from one fixed Core candidate commit. Verify their digests before installing them into Surfaces. + +Run the installed-candidate Toolkit, MCP, A2A, and CLI test matrix, including Toolkit with its declared stable minimum. Run the real MCP discovery and invocation tests, plus the existing direct and MCP Golden Path. Verify that the active candidate and expected Core implementation are actually installed in every matrix job. + +Record Core and Surfaces revisions, per-language results, and artifact digests. This milestone ends at reviewed candidates and verification. Release and merge authorization are separate. From de0c797760796daeefc1ba70d1e44263ea6519f1 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 02:20:46 +0800 Subject: [PATCH 2/5] feat(core): add caller-aware capability discovery Signed-off-by: tercel --- CHANGELOG.md | 1 + conformance/README.md | 1 + conformance/check_config_key_consumers.py | 2 +- conformance/decision_coverage.json | 11 + .../fixtures/capability_discovery.json | 495 +++++++++++++++++ docs/features/capability-discovery.md | 58 ++ docs/features/extension-system.md | 15 +- docs/features/index.md | 1 + docs/features/system-modules.md | 13 +- docs/index.md | 8 +- docs/spec/conformance.md | 5 +- docs/spec/decision-register.md | 1 + docs/spec/protocol-spec.md | 46 +- mkdocs.yml | 1 + python/apcore-conformance.yaml | 2 +- python/pyproject.toml | 2 +- python/src/apcore/__init__.py | 8 + python/src/apcore/acl.py | 116 +++- python/src/apcore/capabilities.py | 372 +++++++++++++ python/src/apcore/client.py | 48 ++ python/src/apcore/executor.py | 74 ++- python/src/apcore/extensions.py | 12 + python/src/apcore/registry/registry.py | 30 +- python/src/apcore/sys_modules/manifest.py | 66 ++- python/src/apcore/sys_modules/registration.py | 5 +- .../conformance/test_capability_discovery.py | 76 +++ python/tests/test_capability_discovery.py | 228 ++++++++ python/tests/test_extensions.py | 5 +- python/tests/test_public_api.py | 6 + python/uv.lock | 2 +- rust/Cargo.lock | 2 +- rust/Cargo.toml | 2 +- rust/apcore-conformance.yaml | 2 +- rust/src/acl.rs | 86 +++ rust/src/acl_handlers.rs | 80 ++- rust/src/builtin_steps.rs | 4 + rust/src/capability.rs | 515 ++++++++++++++++++ rust/src/client.rs | 39 ++ rust/src/executor.rs | 5 + rust/src/extensions.rs | 32 +- rust/src/lib.rs | 5 + rust/src/pipeline.rs | 6 + rust/src/pipeline_config.rs | 12 + rust/src/registry/registry.rs | 19 + rust/src/sys_modules/manifest.rs | 103 ++++ rust/src/sys_modules/mod.rs | 5 + rust/tests/capability_discovery.rs | 355 ++++++++++++ rust/tests/core_profile.rs | 1 + rust/tests/test_extensions.rs | 4 +- schemas/sys-manifest-search.schema.json | 38 ++ schemas/sys-modules.schema.json | 2 +- typescript/apcore-conformance.yaml | 2 +- typescript/package.json | 2 +- typescript/src/acl.ts | 101 +++- typescript/src/browser/index.ts | 4 + typescript/src/builtin-steps.ts | 5 + typescript/src/capability-discovery.ts | 143 +++++ typescript/src/client.ts | 25 + typescript/src/executor.ts | 176 +++++- typescript/src/extensions.ts | 12 + typescript/src/node-api.ts | 4 + typescript/src/registry/registry.ts | 25 +- typescript/src/sys-modules/manifest.ts | 84 ++- typescript/src/sys-modules/registration.ts | 3 +- .../tests/test-capability-discovery.test.ts | 216 ++++++++ typescript/tests/test-extensions.test.ts | 9 +- typescript/tests/test-registration.test.ts | 7 +- 67 files changed, 3770 insertions(+), 75 deletions(-) create mode 100644 conformance/fixtures/capability_discovery.json create mode 100644 docs/features/capability-discovery.md create mode 100644 python/src/apcore/capabilities.py create mode 100644 python/tests/conformance/test_capability_discovery.py create mode 100644 python/tests/test_capability_discovery.py create mode 100644 rust/src/capability.rs create mode 100644 rust/tests/capability_discovery.rs create mode 100644 schemas/sys-manifest-search.schema.json create mode 100644 typescript/src/capability-discovery.ts create mode 100644 typescript/tests/test-capability-discovery.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c650266..16fca12a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Provide explicit configuration, discovery, and full runtime assemblies. The default profile supports in-memory execution from installed Python, TypeScript, and Rust packages. - Add the pure TypeScript Prometheus text renderer and host-owned subscriber factories for configured event delivery. - **Protocol 2.0.0 draft revision 2.** Add opt-in policy evaluation after input validation. The enabled pipeline combines approval requirements at one gate, binds approval to the selected module version and effective arguments, and enforces the gate before ordinary and streaming execution. Final-scope pending approvals require an explicitly compatible scoped handler. +- **Protocol 2.0.0 draft revision 3.** Add caller-scoped capability summaries and full-schema lookup using silent ACL visibility. Add the read-only `system.manifest.search` module with opaque cursors bound to the original requester. ### Changed diff --git a/conformance/README.md b/conformance/README.md index 1ecb5d9b..98d89d6c 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -70,6 +70,7 @@ declared extension. Adapter wire projections are verified in Surfaces. | `approval_gate.json` | A05 | Approval gate Step 5: explicit compatibility policy, result-status outcomes, and scoped resumption | | `core_profile_governance.json` | §7.4, §7.9 | Core Profile defaults and explicit overrides through public preflight and execution, including an injected Executor | | `post_validation_policy.json` | §7.4.1 | Opt-in policy evaluation, validated input approval binding, preflight, scoped resumption and zero stream starts on rejection | +| `capability_discovery.json` | §6.10 | Silent ACL decisions, hidden and conditional capabilities, approval hints, and caller-scoped schema projection | | `approval_request_fields.json` | D-03 | `ApprovalRequest` carries `caller_id` (null for a top-level call) and `action` (= `module_id`) — fields the Contract text already required and no SDK's `ApprovalRequest` carried | | `preflight_disclosure.json` | §12.8.5.1 | `Executor.validate()` withholds module-level introspection from a caller the ACL denied: no `module_preflight` / `module_preview` check, empty `predicted_changes`, and the hooks themselves not invoked. Module lookup is Step 3 and the ACL check is Step 4, so all three SDKs gated these hooks on "lookup succeeded" alone and ran module-authored code for a denied caller. Scoped to AUTHORIZATION: a failed `schema` check does **not** suppress introspection. Drivers MUST run the real `validate()` against a real Registry and ACL, and MUST observe hook invocation from inside the hook bodies — see `driver_contract` | | `middleware_on_error_recovery.json` | A11 | After-middleware error recovery: first-dict-wins, null passthrough, success non-override | diff --git a/conformance/check_config_key_consumers.py b/conformance/check_config_key_consumers.py index 4992313d..5172d7ec 100644 --- a/conformance/check_config_key_consumers.py +++ b/conformance/check_config_key_consumers.py @@ -147,7 +147,7 @@ def _health_enabled() -> str | None: @probe("sys_modules.manifest.enabled") def _manifest_enabled() -> str | None: - return _group_probe("manifest", {"system.manifest.module", "system.manifest.full"}) + return _group_probe("manifest", {"system.manifest.module", "system.manifest.full", "system.manifest.search"}) @probe("sys_modules.usage.enabled") diff --git a/conformance/decision_coverage.json b/conformance/decision_coverage.json index 046b25fd..c9e4e74a 100644 --- a/conformance/decision_coverage.json +++ b/conformance/decision_coverage.json @@ -1065,6 +1065,17 @@ "module_lifecycle.json#module_lifecycle.phase_b.approval_denied_preserves_generation" ], "discriminates": "Requires a drain signal and native stream completion before state capture, bars calls during recovery and replacement, distinguishes retention from compensation and an empty selector match, limits forced cancellation to the retiring invocation, correlates the shutdown event with its operation, and preserves callable state without lifecycle events on approval denial." + }, + "D-154": { + "title": "capability discovery proves ACL visibility", + "kind": "behavioural", + "cases": [ + "capability_discovery.json#possible_deny_prevents_disclosure", + "capability_discovery.json#possible_approval_does_not_prevent_proven_visibility", + "capability_discovery.json#authenticated_role_grant", + "capability_discovery.json#prospective_nested_context_depth" + ], + "discriminates": "Rejects disclosure through an unresolved deny or missing role, preserves a valid conditional approval hint without execution, and checks the prospective target caller frame." } } } diff --git a/conformance/fixtures/capability_discovery.json b/conformance/fixtures/capability_discovery.json new file mode 100644 index 00000000..3493bbb9 --- /dev/null +++ b/conformance/fixtures/capability_discovery.json @@ -0,0 +1,495 @@ +{ + "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": [ + { + "module_id": "demo.echo", + "description": "Echo message", + "tags": [ + "message" + ], + "readonly": true + }, + { + "module_id": "demo.hidden", + "description": "Hidden utility", + "discoverable": false + }, + { + "module_id": "demo.review", + "description": "Review message", + "tags": [ + "message", + "review" + ], + "requires_approval": true + } + ], + "notes": "Register all modules at version 1.0.0 with an object input schema containing a message property and a complete output schema. Create a real Executor with the ordered ACL rules and default_effect deny for each case. Context has a user Identity with the supplied roles (empty when omitted) and is external unless caller_id is given; represent a non-external caller as the tail of the parent call chain. list_callable receives options if present. For the same context independently request definitions for demo.hidden, demo.echo, demo.review, and demo.unknown, plus a duplicate demo.echo. Every listed item must have the expected hint and no schema. Definitions must contain complete input and output schemas; when omitted from expected, expect the set of listed IDs, disregarding order. Audit entries, handler invocations and executions must stay zero. A configured policy_evaluator must never be invoked." + }, + "test_cases": [ + { + "id": "authenticated_role_grant", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow", + "conditions": { + "roles": [ + "reader" + ] + } + }, + { + "callers": [ + "@external" + ], + "targets": [ + "demo.hidden" + ], + "effect": "allow" + } + ], + "roles": [ + "reader" + ] + }, + "expected": { + "items": [ + { + "module_id": "demo.echo", + "access_hint": "allowed" + } + ], + "audit_entries": 0 + } + }, + { + "id": "unauthorized_role_omits_both_levels", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow", + "conditions": { + "roles": [ + "reader" + ] + } + } + ], + "roles": [ + "observer" + ] + }, + "expected": { + "items": [], + "audit_entries": 0 + } + }, + { + "id": "possible_deny_prevents_disclosure", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "deny", + "conditions": { + "arguments": { + "has_key": [ + "mode" + ] + } + } + }, + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow" + } + ] + }, + "expected": { + "items": [], + "audit_entries": 0 + } + }, + { + "id": "definite_first_grant_shadows_later_deny", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow" + }, + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "deny", + "conditions": { + "arguments": { + "has_key": [ + "mode" + ] + } + } + } + ] + }, + "expected": { + "items": [ + { + "module_id": "demo.echo", + "access_hint": "allowed" + } + ], + "audit_entries": 0 + } + }, + { + "id": "argument_only_grant_has_no_authorized_fallback", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow", + "conditions": { + "arguments": { + "has_key": [ + "mode" + ] + } + } + } + ] + }, + "expected": { + "items": [], + "audit_entries": 0 + } + }, + { + "id": "possible_approval_does_not_prevent_proven_visibility", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow", + "conditions": { + "arguments": { + "has_key": [ + "mode" + ] + } + }, + "approval": "required" + }, + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow" + } + ] + }, + "expected": { + "items": [ + { + "module_id": "demo.echo", + "access_hint": "conditional" + } + ], + "audit_entries": 0 + } + }, + { + "id": "module_requires_approval", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.review" + ], + "effect": "allow" + } + ] + }, + "expected": { + "items": [ + { + "module_id": "demo.review", + "access_hint": "requires_approval" + } + ], + "audit_entries": 0 + } + }, + { + "id": "hide_definite_approval_from_summaries", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.*" + ], + "effect": "allow" + } + ], + "options": { + "include_approval_required": false + } + }, + "expected": { + "items": [ + { + "module_id": "demo.echo", + "access_hint": "allowed" + } + ], + "definitions": [ + "demo.echo", + "demo.review" + ], + "audit_entries": 0 + } + }, + { + "id": "policy_is_reported_as_conditional_without_evaluation", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow" + } + ], + "policy_evaluator": true + }, + "expected": { + "items": [ + { + "module_id": "demo.echo", + "access_hint": "conditional" + } + ], + "audit_entries": 0 + } + }, + { + "id": "prospective_nested_context_depth", + "input": { + "rules": [ + { + "callers": [ + "worker.reader" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow", + "conditions": { + "max_call_depth": 2 + } + } + ], + "caller_id": "worker.reader" + }, + "expected": { + "items": [ + { + "module_id": "demo.echo", + "access_hint": "allowed" + } + ], + "audit_entries": 0 + } + }, + { + "id": "compound_known_false_denial_does_not_block", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "deny", + "conditions": { + "roles": [ + "operator" + ], + "arguments": { + "has_key": [ + "mode" + ] + } + } + }, + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow" + } + ], + "roles": [ + "reader" + ] + }, + "expected": { + "items": [ + { + "module_id": "demo.echo", + "access_hint": "allowed" + } + ], + "audit_entries": 0 + } + }, + { + "id": "lexical_tag_filter_only_changes_summary", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.*" + ], + "effect": "allow" + } + ], + "options": { + "query": "review", + "tags": [ + "review" + ], + "prefix": "demo." + } + }, + "expected": { + "items": [ + { + "module_id": "demo.review", + "access_hint": "requires_approval" + } + ], + "definitions": [ + "demo.echo", + "demo.review" + ], + "audit_entries": 0 + } + }, + { + "id": "lexical_query_is_one_substring", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow" + } + ], + "options": { + "query": "echo demo" + } + }, + "expected": { + "items": [], + "definitions": [ + "demo.echo" + ], + "audit_entries": 0 + } + }, + { + "id": "module_prefix_is_literal", + "input": { + "rules": [ + { + "callers": [ + "@external" + ], + "targets": [ + "demo.echo" + ], + "effect": "allow" + } + ], + "options": { + "prefix": " demo." + } + }, + "expected": { + "items": [], + "definitions": [ + "demo.echo" + ], + "audit_entries": 0 + } + } + ] +} diff --git a/docs/features/capability-discovery.md b/docs/features/capability-discovery.md new file mode 100644 index 00000000..82427618 --- /dev/null +++ b/docs/features/capability-discovery.md @@ -0,0 +1,58 @@ +# ACL-aware Capability Discovery + +Use capability discovery to find public modules for the current caller before requesting their schemas. The executor evaluates the active ACL with the prospective caller frame, including the trusted identity and call depth. It returns only active, discoverable registrations that the ACL can prove visible without invocation arguments. A deny dependent on an unknown argument or custom condition can hide a module until the caller makes an actual invocation. + +`list_callable` returns lightweight summaries. Use the query, prefix, tags, and read-only filters to narrow the set. Follow `next_cursor` under the same trusted identity and filters. A cursor belongs to the issuing executor. Role changes, invalid cursors, and expiry can require starting again. Each page is checked against current policy and module availability. + +The `access_hint` field reports `requires_approval` for a definite human requirement, `conditional` when the approval requirement depends on the invocation, and `allowed` otherwise. Discovery does not invoke a module, the policy evaluator, or the approval handler. Every real call still runs the normal gates. + +Use `get_callable_definitions` for selected module IDs to obtain complete input and output schemas. Each requested module is checked again. Missing and hidden IDs are omitted. + +=== "Python" + + ```python + from apcore import APCore + + client = APCore() + page = client.list_callable(limit=10, readonly=True) + definitions = client.get_callable_definitions([item.module_id for item in page.items]) + for definition in definitions: + print(definition.module_id, definition.input_schema) + ``` + +=== "TypeScript" + + ```typescript + import { APCore } from "apcore-js"; + + const client = new APCore(); + const page = client.listCallable(undefined, { limit: 10, readonly: true }); + const definitions = client.getCallableDefinitions(page.items.map(item => item.moduleId)); + for (const definition of definitions) { + console.log(definition.moduleId, definition.inputSchema); + } + ``` + +=== "Rust" + + ```rust + use apcore::{APCore, CapabilityQuery, ModuleError}; + + fn main() -> Result<(), ModuleError> { + let client = APCore::new(); + let page = client.list_callable(None, CapabilityQuery { + limit: 10, + readonly: Some(true), + ..CapabilityQuery::default() + })?; + let ids: Vec<&str> = page.items.iter().map(|item| item.module_id.as_str()).collect(); + for definition in client.get_callable_definitions(&ids, None) { + println!("{} {}", definition.module_id, definition.input_schema); + } + Ok(()) + } + ``` + +Hosts can supply a `CapabilitySearchProvider` to rank eligible IDs. The executor checks any ID returned by the provider against visibility and the current registration. + +When system manifests are enabled, [`system.manifest.search`](./system-modules.md#systemmanifestsearch) exposes the summary query to authorized callers. MCP lists eligible tools using their full `inputSchema` and applies the same visibility to module documentation resources. Existing administrative manifest endpoints have their own ACLs. diff --git a/docs/features/extension-system.md b/docs/features/extension-system.md index dedaa70f..4ae7b52e 100644 --- a/docs/features/extension-system.md +++ b/docs/features/extension-system.md @@ -42,6 +42,7 @@ The Extension System provides a pluggable architecture for customizing and exten | `module_validator` | No | ModuleValidator protocol | Custom module validation | | `approval_handler` | No | ApprovalHandler protocol | Approval gate handler | | `policy_evaluator` | No | PolicyEvaluator protocol | Optional policy over validated execution arguments | +| `capability_search_provider` | No | CapabilitySearchProvider protocol | Optional ranking of ACL-visible capability IDs | ### ExtensionPoint @@ -173,8 +174,9 @@ When `apply(registry, executor)` is called, the manager performs the following i 3. **ACL** → `executor.set_acl(ext)` — replaces the executor's ACL provider. 4. **Approval Handler** → `executor.set_approval_handler(ext)` — replaces the executor's approval handler. 5. **Policy Evaluator** → `executor.set_policy_evaluator(ext)` — enables [policy on validated arguments](../spec/protocol-spec.md#741-post-validation-policy). -6. **Middleware** → `executor.use(mw)` for each registered middleware — appends to the middleware chain. -7. **Span Exporters** → Locates the `TracingMiddleware` already in the executor's middleware chain and sets its exporter: +6. **Capability Search Provider** sets the optional ranking provider on the executor. +7. **Middleware** → `executor.use(mw)` for each registered middleware — appends to the middleware chain. +8. **Span Exporters** → Locates the `TracingMiddleware` already in the executor's middleware chain and sets its exporter: - If a single exporter is registered, it is set directly. - If multiple exporters are registered, they are wrapped in a composite exporter that delegates to all of them. A failure in one exporter is logged and does not affect the others. - If the chain has no `TracingMiddleware`, a warning is logged and the exporters are not applied — `apply` does not add one. @@ -274,13 +276,13 @@ Rust, where the manager owns its extensions, that path is ### Inputs - `registry` (Registry, required) — registry to wire extensions into (discoverer, module_validator) -- `executor` (Executor, required) — executor to wire extensions into (acl, approval_handler, policy_evaluator, middleware, span_exporter) +- `executor` (Executor, required) receives acl, approval_handler, policy_evaluator, capability_search_provider, middleware, and span_exporter. ### Errors - Errors raised by the Registry / Executor setters propagate (Rust: `Err(ModuleError)`, e.g. a rejected middleware). A registered span exporter with no `TracingMiddleware` in the chain is **not** an error: it is logged as a warning and skipped. ### Returns -- On success: void/None/() — all registered extensions wired in the documented order (discoverer → module_validator → acl → approval_handler → policy_evaluator → middleware chain → span exporters) +- On success, returns void/None/() after wiring each extension in the order below. ### Side Effects (ordered) 1. `registry.set_discoverer(ext)` if discoverer registered @@ -288,8 +290,9 @@ Rust, where the manager owns its extensions, that path is 3. `executor.set_acl(ext)` if acl registered 4. `executor.set_approval_handler(ext)` if approval_handler registered 5. `executor.set_policy_evaluator(ext)` if policy_evaluator registered -6. `executor.use(mw)` for each middleware in registration order -7. Locate `TracingMiddleware` in the executor chain; set a single exporter directly or wrap several in a composite exporter; warn and skip if there is none +6. `executor.set_capability_search_provider(ext)` if capability_search_provider registered +7. `executor.use(mw)` for each middleware in registration order +8. Locate `TracingMiddleware` in the executor chain and install the single exporter or a composite. Warn and skip exporter wiring when tracing middleware is absent. ### Postconditions diff --git a/docs/features/index.md b/docs/features/index.md index 9ad95729..971880cc 100644 --- a/docs/features/index.md +++ b/docs/features/index.md @@ -29,6 +29,7 @@ One page per apcore subsystem: what it does, the contract the SDKs implement, an ### Security & Governance *Guardrails, identity, and access control.* - [ACL System](./acl-system.md) — Pattern-based permission rules. +- [ACL-aware Capability Discovery](./capability-discovery.md) — Caller-scoped summaries and full-schema lookup. - [Identity System](./identity-system.md) — Caller representation and roles. - [Approval System](./approval-system.md) — Human-in-the-loop gates. - [Call Chain Guard](./call-chain-guard.md) — Recursion and depth protection. diff --git a/docs/features/system-modules.md b/docs/features/system-modules.md index fc70736c..ba16c94b 100644 --- a/docs/features/system-modules.md +++ b/docs/features/system-modules.md @@ -20,6 +20,7 @@ The built-in `system.*` modules let AI agents and operators query and control a | [`system.health.module`](#systemhealthmodule) | Health detail for one module: latency and recent errors | readonly, idempotent | | [`system.manifest.module`](#systemmanifestmodule) | One module's schema, annotations, tags, source path | readonly, idempotent | | [`system.manifest.full`](#systemmanifestfull) | Full registry manifest, filterable by tags and prefix | readonly, idempotent | +| [`system.manifest.search`](#systemmanifestsearch) | Lightweight capability summaries visible to the caller | readonly, idempotent | | [`system.usage.summary`](#systemusagesummary) | Usage statistics for every module, with trends | readonly, idempotent | | [`system.usage.module`](#systemusagemodule) | One module's usage, per-caller breakdown, hourly distribution | readonly, idempotent | | [`system.control.update_config`](#systemcontrolupdate_config) | Change a runtime configuration value | requires_approval | @@ -45,10 +46,10 @@ With the defaults this gives three states (§6.6.3): | Config | Modules registered | |---|---| | `sys_modules.enabled: false` | **0** | -| `sys_modules.enabled: true`, `events.enabled: false` | **6** — `system.health.*`, `system.usage.*`, `system.manifest.*` | -| `sys_modules.enabled: true`, `events.enabled: true` | **9** — the six plus the three `system.control.*` write modules | +| `sys_modules.enabled: true`, `events.enabled: false` | **7** — `system.health.*`, `system.usage.*`, `system.manifest.*` | +| `sys_modules.enabled: true`, `events.enabled: true` | **10** — the seven read modules plus three `system.control.*` write modules | -A registry holding only the six read modules has no write surface; anything reasoning about exposure should distinguish the two enabled states. +A registry holding only the read modules has no write surface. The control modules declare `requires_approval: true`, so the approval gate applies to them. Approval, like ACL, is inactive by absence ([§6.6.3.1](../spec/protocol-spec.md#6631-layers-2-and-3-are-inactive-by-absence)): with no `ApprovalHandler` the gate is skipped with a warning unless `ExecutionPolicy(strict=true)` is set, and a missing ACL file attaches no ACL. To see what actually gates a registry, read [`executor.governance_state()`](./core-executor.md#governance-state-api) (§6.6.5). @@ -311,6 +312,12 @@ Each `modules[]` entry has the shape of `system.manifest.module`'s output. `proj --- +## system.manifest.search + +Returns the public module summaries visible to the original trusted caller. The module has its own ACL, and every returned target must also pass the discovery check. Existing administrative manifests retain their independent ACLs. + +Pass optional filters `query`, `prefix`, `tags`, `readonly`, `limit`, and `include_approval_required`. To continue, pass `cursor` with the same filters and authenticated context. The result contains `items` and `next_cursor`, which is null on the last page. See [ACL-aware capability discovery](./capability-discovery.md) for the approval hints and schema lookup APIs. + ## system.usage.summary Usage overview with trend detection across all modules. diff --git a/docs/index.md b/docs/index.md index 2640994c..89a62129 100644 --- a/docs/index.md +++ b/docs/index.md @@ -24,10 +24,10 @@ A schema makes a capability contract machine-readable and validatable. It does n | Component | Package | Stable | In development | |---|---|---|---| -| Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `2.0.0` (draft revision 2) | -| Python SDK | `apcore` | `0.33.0` | `1.0.0a3` | -| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.3` | -| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.3` | +| Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `2.0.0` (draft revision 3) | +| Python SDK | `apcore` | `0.33.0` | `1.0.0a4` | +| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.4` | +| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.4` | The protocol `2.0.0` draft defines the contract for the SDK `1.0.0` release line. The three core SDKs share that release line. Surface adapters (`apcore-mcp`, `apcore-a2a`, `apcore-cli`, `apcore-toolkit`) are versioned independently and declare the core range they support in their package metadata. diff --git a/docs/spec/conformance.md b/docs/spec/conformance.md index 0bf1f9c1..63891bff 100644 --- a/docs/spec/conformance.md +++ b/docs/spec/conformance.md @@ -326,7 +326,7 @@ The following requirements are not met by the SDK implementations in this reposi ## 8. Conformance Test Fixtures -The repository ships **99 cross-language fixture files** under `conformance/fixtures/` covering **1238 test cases**. `conformance-integrity` checks these two numbers, §8.1's per-fixture counts and its Total row against the fixtures themselves. Each fixture is consumed by all three SDK test runners (§5.2). An SDK declaring a conformance level **MUST** pass every fixture whose tested feature is required at that level (§5.3). +The repository ships **100 cross-language fixture files** under `conformance/fixtures/` covering **1252 test cases**. `conformance-integrity` checks these two numbers, §8.1's per-fixture counts and its Total row against the fixtures themselves. Each fixture is consumed by all three SDK test runners (§5.2). An SDK declaring a conformance level **MUST** pass every fixture whose tested feature is required at that level (§5.3). ### 8.1 Fixture Inventory @@ -370,6 +370,7 @@ The repository ships **99 cross-language fixture files** under `conformance/fixt | [`error_details_shape`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/error_details_shape.json) | 5 | `SCHEMA_VALIDATION_ERROR` details items are `{path, keyword, message}` with a JSON Pointer path; `details` keys are snake_case (spec §8.1, D-149) | | [`core_profile_governance`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/core_profile_governance.json) | 8 | Core Profile governance defaults and explicit overrides through public preflight and execution, including an injected Executor (spec §7.4 and §7.9) | | [`post_validation_policy`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/post_validation_policy.json) | 9 | Final argument policy, combined approval requirements, scoped resumption and stream producer gating (spec §7.4.1) | +| [`capability_discovery`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/capability_discovery.json) | 14 | Caller-scoped visibility, conditional approval hints and schema lookup (spec §6.10) | | [`ephemeral_modules`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/ephemeral_modules.json) | 7 | `ephemeral.*`: one audit event per register / unregister under the standard bootstrap, the bare ID `ephemeral`, `INVALID_MODULE_ID` rejections (spec §2.5.1, D-148) | | [`error_fingerprinting`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/error_fingerprinting.json) | 6 | Error fingerprint = SHA-256 of `code:module_id:normalized_message` for ErrorHistory dedup | | [`error_recovery_metadata`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/error_recovery_metadata.json) | 22 | `retryable` / `ai_guidance` / `user_fixable` / `suggestion` recovery metadata (spec §8) | @@ -431,7 +432,7 @@ The repository ships **99 cross-language fixture files** under `conformance/fixt | [`usage_contract`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/usage_contract.json) | 11 | `system.usage.*` value semantics no schema can assert (spec §6.7.1) | | [`usage_exporter`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/usage_exporter.json) | 3 | `UsageExporter` push interface (D-55) | | [`version_negotiation`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/version_negotiation.json) | 12 | Version negotiation (Algorithm A14) | -| **Total** | **1238** | **99 fixtures** | +| **Total** | **1252** | **100 fixtures** | ### 8.2 Loading Fixtures from a Test Runner diff --git a/docs/spec/decision-register.md b/docs/spec/decision-register.md index 707c7e96..fdc1f6a0 100644 --- a/docs/spec/decision-register.md +++ b/docs/spec/decision-register.md @@ -165,6 +165,7 @@ them. | D-131 | Built-in logging middleware logs the captured values | In force | v1.61.0 | [divergence log](./2026-09-divergence-decisions.md#d-131-built-in-logging-middleware-logs-the-captured-values) | | D-132 | The specification follows three agreeing, correct implementations | In force | v1.62.0 | [divergence log](./2026-09-divergence-decisions.md#d-132-the-specification-follows-three-agreeing-correct-implementations) | | D-153 | Managed lifecycle binds admission, cancellation, and recovery to a generation | Draft | — | [Managed Module Lifecycle](./protocol-spec.md#1279-managed-module-lifecycle) | +| D-154 | Capability discovery proves visibility before projecting metadata and rechecks access on every request | Draft | — | [ACL-aware capability discovery](./protocol-spec.md#acl-aware-capability-discovery) | | E-01 | `start_reaper` starts synchronously; only `stop()` is awaited | In force | — | [2026-09 audit log](./2026-09-decision-log.md#e-01-asynctaskmanagerstart_reaper-does-the-call-itself-need-to-be-awaited) | | E-02 | `APCore.discover` is sync in Python, async in TypeScript and Rust | In force | — | [2026-09 audit log](./2026-09-decision-log.md#e-02-apcorediscover-synchronous-in-all-languages-contradicted-two-of-three-implementations) | | E-03 | `ACL(rules=[…])` validates every rule it is handed | In force | v1.33.0 | [2026-09 audit log](./2026-09-decision-log.md#e-03-aclrules-did-not-re-validate-a-rule-mutated-before-its-first-construction) | diff --git a/docs/spec/protocol-spec.md b/docs/spec/protocol-spec.md index 12215263..d6575bca 100644 --- a/docs/spec/protocol-spec.md +++ b/docs/spec/protocol-spec.md @@ -8,7 +8,7 @@ description: "The canonical apcore protocol specification (RFC 2119): module, sc > Version: 2.0.0 > Status: Draft -> Draft Revision: 2 +> Draft Revision: 3 > Last Updated: 2026-11-27 --- @@ -4705,12 +4705,12 @@ Layer 1: Activation (Config) — two stages, not one sys_modules.enabled = false (default) → 0 modules registered. Nothing to call, nothing to list. sys_modules.enabled = true, sys_modules.events.enabled = false (default) - → 6 read modules: system.health.*, system.usage.*, system.manifest.* + → 7 read modules: system.health.*, system.usage.*, system.manifest.* → NO system.control.* — the write modules require the EventEmitter that carries their audit events (§6.7 cross-cutting requirement 3), so they are registered inside the events branch and not otherwise. both = true - → 9 modules: the 6 above plus the 3 system.control.* write modules. + → 10 modules: the 7 above plus the 3 system.control.* write modules. Layer 2: Authorization (ACL) When system modules ARE registered, ACL rules control who can call them. @@ -4727,7 +4727,7 @@ Layer 3: Approval (requires_approval annotation) SHOULD set requires_approval = true for human-in-the-loop enforcement. ``` -The 0 / 6 / 9 distinction matters to anything that reasons about exposure: a registry holding six read-only modules and no ACL is an **information-disclosure** question, not a control-plane one. Treating "system modules are registered" as one state produces a warning that fires on a configuration with no write surface at all. +The 0 / 7 / 10 distinction matters to anything that reasons about exposure: a registry holding seven read-only modules and no ACL is an **information-disclosure** question, not a control-plane one. Treating "system modules are registered" as one state produces a warning that fires on a configuration with no write surface at all. Adapters and UI layers **SHOULD NOT** introduce additional independent permission switches. The three layers above are sufficient — adding adapter-level switches creates shadow permission systems that can diverge from the actual ACL state. @@ -4814,7 +4814,7 @@ Two things it **does not** claim, and implementations **MUST NOT** document it a 1. **That protection exists when it is `false`.** A configured, wired ACL may permit every call. The flag reports the **absence of a gate**, never the presence of protection. Implementations **MUST NOT** name it `is_secure`, expose an inverse spelled as safety, or otherwise present it as a security verdict. 2. **That nothing will stop the call when it is `true`.** A deployment may enforce through a custom pipeline step, custom middleware, or an upstream gateway. Those are invisible to this accessor by construction and are not negated by the flag. -The read modules are reported separately for the reason given in §6.6.3: six read-only modules with no ACL is an information-disclosure question, and folding them into the control-surface flag makes it fire on a configuration with no write surface at all. +The read modules are reported separately for the reason given in §6.6.3: seven read-only modules with no ACL is an information-disclosure question, and folding them into the control-surface flag makes it fire on a configuration with no write surface at all. ###### 6.6.5.1.1 Why the two gates are not symmetric @@ -4887,6 +4887,7 @@ This section documents the canonical `system.*` module catalogue. Conformant SDK | `system.health.module` | Observability | Read | Level 1 | Detailed health for a single module (latency p50/p99, error count, error rate) | | `system.manifest.module` | Introspection | Read | Level 1 | Full manifest for one module (input_schema, output_schema, annotations, tags, dependencies, source path) | | `system.manifest.full` | Introspection | Read | Level 1 | Full manifest for all registered modules | +| `system.manifest.search` | Introspection | Read | Level 1 | Paginated summaries visible to the requesting caller (§6.10) | | `system.usage.summary` | Observability | Read | Level 1 | Aggregated usage statistics (calls, errors, latency) | | `system.usage.module` | Observability | Read | Level 1 | Per-module usage statistics | | `system.control.update_config` | Administration | Write | Level 2 | Update a runtime configuration value by dot-path key (audit-logged) | @@ -4902,7 +4903,7 @@ This section documents the canonical `system.*` module catalogue. Conformant SDK 5. **`system.control.update_config`** **MUST** redact sensitive keys (per §10.6.1 `obs.redaction.sensitive_keys`) in both `old_value` and `new_value` fields of its output and audit event. 6. **`system.control.toggle_feature`** state **MUST** persist via the configured `OverridesStore` so toggle state survives process restart; without persistence, toggle decisions revert to the registered defaults on reload. -**Conformance note:** SDKs declaring Level 1 conformance ([Conformance](./conformance.md) §3) MUST register the 6 read modules. SDKs declaring Level 2 MUST additionally register the 3 control modules. Implementations MAY register additional modules under `system..*` namespaces — these are NOT covered by this canonical catalogue and MUST NOT collide with the names above. +**Conformance note:** SDKs declaring Level 1 conformance ([Conformance](./conformance.md) §3) MUST register the 7 read modules. SDKs declaring Level 2 MUST additionally register the 3 control modules. Implementations MAY register additional modules under `system..*` namespaces — these are NOT covered by this canonical catalogue and MUST NOT collide with the names above. #### 6.7.1 Usage Module Output Contract @@ -5040,6 +5041,33 @@ Approval requirements have more than one source. The composition is normative, n **Rule 7 is a compatibility constraint, not a modelling preference.** `AuditEntry.decision` is a string that downstream consumers parse. A third value breaks every existing parser; a new field beside it does not. +### 6.10 ACL-aware capability discovery {#acl-aware-capability-discovery} + +Capability discovery answers whether a trusted caller may see metadata for an active, public module. Every invocation **MUST** still satisfy the execution pipeline's ACL, validation, policy, approval, and lifecycle checks. + +#### 6.10.1 Silent visibility + +- The Executor **MUST** use the prospective target invocation's caller frame, depth, and trusted identity, with the ACL that governs its pipeline. It **MUST NOT** derive identity or caller from query data. When no ACL governs the default assembly, public active modules are eligible. +- `ACL.evaluate_visibility` **MUST** preserve §6.1–§6.2 rule ordering, structural prechecks, and fail-closed resolution. It **MUST** evaluate known built-in identity, role, and depth predicates. Argument predicates and custom handlers, including replacements for built-ins, are unknown to discovery. The probe **MUST NOT** supply fabricated arguments or run these handlers. After structural precheck, false in an AND and true in an OR settle the corresponding expression. Negating unknown remains unknown. +- The probe **MUST** grant visibility only if every reachable first-match result is an allow. A reachable unknown deny hides the target. An unknown allow may change the approval requirement, but the fallthrough path still requires a grant. Malformed conditions retain §6.1.1 deny and pending-approval semantics. A custom ACL **MUST** provide an equivalent silent decision for its governed targets to be eligible. +- Discovery **MUST NOT** emit the ordinary ACL audit entry or denied event, write to execution error history, validate inputs, call the policy evaluator or approval handler, or run module hooks or execution. It **MUST NOT** return hidden, disabled, draining, missing, or otherwise ineligible registrations. Metadata **MUST** correspond to the authorized registration generation, even when the same version is registered again. + +#### 6.10.2 Summaries, definition lookup, and paging + +The Executor and APCore **MUST** expose idiomatic equivalents of `list_callable(context, options)` and `get_callable_definitions(module_ids, context)`. SDKs **MAY** provide a version-aware single-definition lookup for adapters. A version selector **MUST** use the invocation resolver and **MUST NOT** disclose stale or unresolvable metadata. + +- `list_callable` **MUST** produce a `CapabilityPage` containing `items` and an opaque, nullable `next_cursor`. Each `ModuleSummary` **MUST** contain `module_id`, resolved `version`, `description`, `tags`, `readonly`, and `access_hint`. Summaries **MUST NOT** include schemas, source paths, or arbitrary metadata. +- `access_hint` **MUST** be `requires_approval` when every eligible path requires approval under ACL and Step 5, `conditional` when the requirement can vary or the final-input policy can add a requirement, and `allowed` otherwise. `include_approval_required: false` **MUST** omit entries with `requires_approval`. +- Filters are `query`, `prefix`, `tags`, and `readonly`. Omitted filters are unconstrained. The default lexical search **MUST** trim and lowercase the query and match it as one substring within the lowercased module ID, description, or a single tag. Prefixes and requested tags match literally, and every requested tag **MUST** be present. Results **MUST** have deterministic order with a module ID tie breaker. Page size defaults to 20 and the allowed range is 1–100. +- A cursor **MUST** be bound to the issuing Executor, trusted principal and caller frame, and normalized request filters, including page size. Invalid, expired, or foreign cursors **MUST** fail without returning entries or cursor binding details. Every emitted entry **MUST** pass current visibility, including after ACL or registry changes. +- Definition lookup **MUST** return the full detached input and output JSON Schemas with the resolved module ID and version. It **MUST** check visibility again. Missing, hidden, and unauthorized IDs **MUST** be omitted indistinguishably; duplicate IDs **MUST** appear at most once in first-request order. +- A configured `CapabilitySearchProvider` (§11.3) **MAY** rank candidate IDs. The Executor **MUST** run the same visibility and active-registration checks on those IDs before returning metadata. + +#### 6.10.3 Manifest search and adapter projection + +`system.manifest.search` is a read-only module using the filters and pagination in §6.10.2. Clients **MUST** omit unset input fields. Its result uses the `CapabilityPage` shape in snake_case with a nullable `next_cursor`. The call **MUST** pass its own ACL. Target visibility **MUST** then use the original trusted caller frame, excluding the search module's own frame. The existing `system.manifest.full` and `system.manifest.module` retain their own ACL checks and wire contracts. + +A caller-aware adapter **MUST** use the same trusted context as its invocation path when applying discovery to its published modules. Standard MCP `tools/list` **MUST** retain the complete `inputSchema` of each eligible tool. Lightweight summaries and definition lookup **MUST** use the separate discovery API. MCP exposes `system.manifest.search` as a read-only query tool when the module is available to the requester. When the adapter publishes module documentation resources, listing and direct access **MUST** apply the same visibility. Transport control tools and ACL-gated management manifests retain their own authorization contracts. --- @@ -8184,7 +8212,7 @@ Config.register_namespace( !!! warning "These defaults are off, and §6.6.3 is the reason" `enabled` and `events.enabled` are the two flags §6.6.3 describes as the - 0 / 6 / 9 activation ladder, and both default to **false**. Registering + 0 / 7 / 10 activation ladder, and both default to **false**. Registering this namespace with `enabled: True` would stand the system modules up in every project that never asked for them, and `events.enabled: True` would additionally stand up the three `system.control.*` **write** modules — @@ -8845,6 +8873,7 @@ implementations registered for one point are not chained (§11.7) (D-143). > | *(no equivalent)* | `span_exporter` | Observability export as a dedicated extension point | > | *(no equivalent)* | `approval_handler` | The approval gate's handler (§7) as an extension point | > | *(no equivalent)* | `policy_evaluator` | Opt-in evaluation of validated execution arguments (§7.4.1) | +> | *(no equivalent)* | `capability_search_provider` | Optional ranking of capability candidates (§6.10) | > | `id_converter` | *(not an extension point)* | Not a common runtime customization need | > | `executor` | *(not an extension point)* | Local execution covers the supported use cases | > @@ -8939,7 +8968,7 @@ Extension Point: Executor Extensions are registered in code with `ExtensionManager.register(point_name, extension)` and wired with `apply(registry, executor)` (§11.3): -1. A single-valued point (`discoverer`, `acl`, `module_validator`, `approval_handler`, `policy_evaluator`) holds one +1. A single-valued point (`discoverer`, `acl`, `module_validator`, `approval_handler`, `policy_evaluator`, `capability_search_provider`) holds one implementation; registering another replaces it. 2. A multi-valued point (`middleware`, `span_exporter`) holds every registered implementation in registration order. @@ -10343,6 +10372,7 @@ The specification and the SDK have independent version numbers. `CHANGELOG.md` r | Version | Date | Summary | Records | |---|---|---|---| +| 2.0.0 (draft revision 3) | Unreleased | Add silent ACL visibility, caller-scoped summaries and schema lookup, and `system.manifest.search` (§6.10, §11.3). | D-154, [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | | 2.0.0 (draft revision 2) | Unreleased | Add the opt-in post-validation policy evaluator, final-input approval binding, and preflight semantics (§7.2–§7.4.1, §11.3, §12.8). | [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | | 2.0.0 (draft revision 1) | Unreleased | Define an in-memory Core Profile and opt-in extensions (§1.8, §12). Deny calls requiring approval when the handler is absent, and require approval for destructive modules by default (§6.6.3.1, §7.4, §7.9). Require invocation-scoped approval resumption and use a non-secret correlation ID in telemetry (§7, §9.16.2). Specify managed drain, recovery, scoped forced removal, reload reports and lifecycle events (§6.7, §9.16.2, §12.7.9). Assign provider projections to Surfaces (§4.17 and Appendix D). Resolve path-typed configuration against one project root (§9.2.2). Clarify pipeline configuration, preflight and approval argument scope (§5.16.1, §7.3–7.4, §12.8), configured redaction (§6.1.8, §10.6.1) and trace IDs (§10.5). Align schema examples with Draft 2020-12 and the validation error format (§4.2, §4.14, §8.1). | D-153, [#113](https://github.com/aiperceivable/apcore/issues/113), [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | | 1.66.0 | 2026-10-19 | A23 preserves optional enum, const, reference and applicator constraints inside an anyOf-null wrapper; required fields remain unchanged. | [#124](https://github.com/aiperceivable/apcore/issues/124) | diff --git a/mkdocs.yml b/mkdocs.yml index 4494436f..726885b3 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -113,6 +113,7 @@ nav: - Cancellation: features/cancellation.md - Security & Governance: - ACL System: features/acl-system.md + - ACL-aware Capability Discovery: features/capability-discovery.md - Identity System: features/identity-system.md - Approval System: features/approval-system.md - Call Chain Guard: features/call-chain-guard.md diff --git a/python/apcore-conformance.yaml b/python/apcore-conformance.yaml index 13a734e6..d8fbb247 100644 --- a/python/apcore-conformance.yaml +++ b/python/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-python - version: 1.0.0a3 + version: 1.0.0a4 language: python spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/python/pyproject.toml b/python/pyproject.toml index d8943482..c62faef0 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "apcore" -version = "1.0.0a3" +version = "1.0.0a4" description = "Build once, invoke by code or AI — with schema, ACL, approval, and audit enforced at every call" readme = "README.md" requires-python = ">=3.11" diff --git a/python/src/apcore/__init__.py b/python/src/apcore/__init__.py index ff88d91e..9f150bf7 100644 --- a/python/src/apcore/__init__.py +++ b/python/src/apcore/__init__.py @@ -22,6 +22,7 @@ ScopedApprovalHandler, ) from apcore.cancel import CancelToken, ExecutionCancelledError +from apcore.capabilities import AccessHint, CallableDefinition, CapabilityPage, CapabilitySearchProvider, ModuleSummary from apcore.context import Context, ContextFactory, GovernanceProjection, Identity from apcore.context_key import ContextKey from apcore.context_keys import ( @@ -168,6 +169,7 @@ AuditEntry, ConditionOutcome, RuleValidationFinding, + VisibilityDecision, ) # Execution-time governance policy (apcore#76 RFC pilot) @@ -602,6 +604,12 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st "ApprovalResult", "AutoApproveHandler", "CancelToken", + "AccessHint", + "CallableDefinition", + "CapabilityPage", + "CapabilitySearchProvider", + "ModuleSummary", + "VisibilityDecision", "Context", "ErrorCodes", "ExecutionPolicy", diff --git a/python/src/apcore/acl.py b/python/src/apcore/acl.py index fd028dff..76a1c3a5 100644 --- a/python/src/apcore/acl.py +++ b/python/src/apcore/acl.py @@ -45,6 +45,7 @@ "ACL", "ConditionOutcome", "RuleValidationFinding", + "VisibilityDecision", ] _logger = logging.getLogger(__name__) @@ -520,6 +521,36 @@ class AccessDecision: reason: str = "default_effect" +@dataclass(frozen=True) +class VisibilityDecision: + """Eligibility for discovery and the reachable ACL approval outcomes.""" + + visible: bool + approval_required: bool = False + approval_conditional: bool = False + + +_VISIBILITY_HANDLERS = { + "identity_types": _IdentityTypesHandler(), + "roles": _RolesHandler(), + "max_call_depth": _MaxCallDepthHandler(), +} +_MATCH = ConditionOutcome.SATISFIED +_NO_MATCH = ConditionOutcome.UNSATISFIED +_FAULT = ConditionOutcome.UNEVALUABLE +_DYNAMIC_VISIBILITY_OUTCOMES = frozenset(ConditionOutcome) + + +def _combine_visibility( + left: frozenset[ConditionOutcome], right: frozenset[ConditionOutcome], decisive: ConditionOutcome +) -> frozenset[ConditionOutcome]: + return frozenset( + decisive if decisive in (first, second) else _FAULT if _FAULT in (first, second) else first + for first in left + for second in right + ) + + @dataclass(frozen=True) class RuleValidationFinding: """One structural or registry fault found by the §6.1.4 precheck. @@ -747,9 +778,7 @@ class ACL: """ _condition_handlers: ClassVar[dict[str, ACLConditionHandler]] = { - "identity_types": _IdentityTypesHandler(), - "roles": _RolesHandler(), - "max_call_depth": _MaxCallDepthHandler(), + **_VISIBILITY_HANDLERS, # PROTOCOL_SPEC §6.1.7: `arguments` is built-in, and registered here # beside the other built-ins rather than through a new registration # point — `register_condition` writes runtime code into a process-wide @@ -1799,6 +1828,81 @@ async def async_check_access( _projection_var.reset(projection_token) _handler_error_var.reset(token) + def evaluate_visibility( + self, caller_id: str | None, target_id: str, context: Context | None = None + ) -> VisibilityDecision: + """Prove visibility across reachable ACL outcomes without call arguments or audit effects.""" + effective_caller, rules, default_effect, _ = self._snapshot(caller_id) + pending_approvals = {False} + possible_approvals: set[bool] = set() + for rule in rules: + outcomes = self._visibility_rule(rule, effective_caller, target_id, context) + if rule.effect != "allow" and outcomes != {_NO_MATCH}: + return VisibilityDecision(False) + if _MATCH in outcomes: + possible_approvals.update( + pending or rule.approval == APPROVAL_REQUIRED for pending in pending_approvals + ) + if outcomes == {_MATCH}: + break + if _FAULT in outcomes and self._raises_pending_approval(rule): + pending_approvals = (pending_approvals | {True}) if _NO_MATCH in outcomes else {True} + else: + if default_effect != "allow": + return VisibilityDecision(False) + possible_approvals.update(pending_approvals) + + return VisibilityDecision( + True, approval_required=possible_approvals == {True}, approval_conditional=len(possible_approvals) > 1 + ) + + def _visibility_rule( + self, rule: ACLRule, caller: str, target: str, context: Context | None + ) -> frozenset[ConditionOutcome]: + if self._precheck_patterns(rule): + return frozenset({_FAULT}) + if not self._match_patterns(rule.callers, caller, context) or not self._match_patterns( + rule.targets, target, context + ): + return frozenset({_NO_MATCH}) + if rule.conditions is None: + return frozenset({_MATCH}) + if self._precheck_conditions(rule.conditions, async_path=True): + return frozenset({_FAULT}) + if context is None: + return frozenset({_NO_MATCH}) + return self._visibility_matches(rule.conditions, context) + + @classmethod + def _visibility_matches(cls, conditions: dict[str, Any], context: Context) -> frozenset[ConditionOutcome]: + outcomes = frozenset({_MATCH}) + for key, value in conditions.items(): + outcomes = _combine_visibility(outcomes, cls._visibility_condition(key, value, context), _NO_MATCH) + if outcomes == {_NO_MATCH}: + break + return outcomes + + @classmethod + def _visibility_condition(cls, key: str, value: Any, context: Context) -> frozenset[ConditionOutcome]: + registered = cls._async_condition_handlers.get(key, cls._condition_handlers.get(key)) + if key == "$or" and registered is _BUILTIN_ASYNC_OR: + outcomes = frozenset({_NO_MATCH}) + for operand in value: + outcomes = _combine_visibility(outcomes, cls._visibility_matches(operand, context), _MATCH) + if outcomes == {_MATCH}: + break + return outcomes + if key == "$not" and registered is _BUILTIN_ASYNC_NOT: + negations = {_MATCH: _NO_MATCH, _NO_MATCH: _MATCH, _FAULT: _FAULT} + return frozenset(negations[outcome] for outcome in cls._visibility_matches(value, context)) + handler = _VISIBILITY_HANDLERS.get(key) + if handler is None or registered is not handler: + return _DYNAMIC_VISIBILITY_OUTCOMES + try: + return frozenset({_as_outcome(handler.evaluate(value, context))}) + except (TypeError, ValueError): + return frozenset({_FAULT}) + def _snapshot(self, caller_id: str | None) -> tuple[str, list[ACLRule], str, "_AuditSink"]: """Atomically snapshot mutable state for a check call. @@ -2420,5 +2524,7 @@ def reload(self) -> None: # Async-aware variants: used by async_check() so $or/$not properly await # async sub-condition handlers (mirrors TypeScript registerAsyncCondition). -ACL.register_async_condition("$or", _OrHandlerAsync(ACL._evaluate_conditions_async)) -ACL.register_async_condition("$not", _NotHandlerAsync(ACL._evaluate_conditions_async)) +_BUILTIN_ASYNC_OR = _OrHandlerAsync(ACL._evaluate_conditions_async) +_BUILTIN_ASYNC_NOT = _NotHandlerAsync(ACL._evaluate_conditions_async) +ACL.register_async_condition("$or", _BUILTIN_ASYNC_OR) +ACL.register_async_condition("$not", _BUILTIN_ASYNC_NOT) diff --git a/python/src/apcore/capabilities.py b/python/src/apcore/capabilities.py new file mode 100644 index 00000000..49a6ac27 --- /dev/null +++ b/python/src/apcore/capabilities.py @@ -0,0 +1,372 @@ +"""ACL-aware projections of the live module catalogue.""" + +from __future__ import annotations + +from collections import OrderedDict +from collections.abc import Iterable +from copy import copy, deepcopy +from dataclasses import dataclass +from secrets import token_urlsafe +from threading import Lock +from time import monotonic +from typing import TYPE_CHECKING, Any, Literal, Protocol, runtime_checkable + +from apcore._post_validation_policy import _argument_digest +from apcore.acl import ACL, VisibilityDecision +from apcore.builtin_steps import BuiltinACLCheck, BuiltinApprovalGate, BuiltinModuleLookup +from apcore.context import Context, Identity +from apcore.errors import InvalidInputError, PolicyEvaluationError +from apcore.policy import ExecutionPolicy +from apcore.schema.annotations import governance_union + +if TYPE_CHECKING: + from apcore.executor import Executor + from apcore.registry.registry import _ModuleRegistration + from apcore.registry.types import ModuleDescriptor + +__all__ = ["AccessHint", "CallableDefinition", "CapabilityPage", "CapabilitySearchProvider", "ModuleSummary"] + +AccessHint = Literal["allowed", "requires_approval", "conditional"] +_CURSOR_TTL_SECONDS = 300 +_MAX_CURSORS = 128 + + +@dataclass(frozen=True) +class ModuleSummary: + """Lightweight discovery information for one visible module.""" + + module_id: str + version: str + description: str + tags: tuple[str, ...] + readonly: bool + access_hint: AccessHint + + +@dataclass(frozen=True) +class CapabilityPage: + """A page of summaries and an opaque continuation for the requesting frame.""" + + items: tuple[ModuleSummary, ...] + next_cursor: str | None = None + + +@dataclass(frozen=True) +class CallableDefinition: + """Detached schemas for a single authorized module registration.""" + + module_id: str + version: str + input_schema: dict[str, Any] + output_schema: dict[str, Any] + + +@runtime_checkable +class CapabilitySearchProvider(Protocol): + """Rank authorized candidate IDs for the normalized query.""" + + def search(self, query: str | None, candidates: tuple[str, ...]) -> Iterable[str]: ... + + +@dataclass(frozen=True) +class _Filters: + query: str | None + prefix: str | None + tags: tuple[str, ...] + readonly: bool | None + limit: int + include_approval_required: bool + + @classmethod + def create( + cls, + query: str | None, + prefix: str | None, + tags: Iterable[str] | None, + readonly: bool | None, + limit: int, + include_approval_required: bool, + ) -> _Filters: + if query is not None and not isinstance(query, str) or prefix is not None and not isinstance(prefix, str): + raise InvalidInputError("Discovery query and prefix must be strings") + if isinstance(tags, (str, bytes)): + raise InvalidInputError("Discovery tags must be a collection of strings") + try: + tag_items = tuple(() if tags is None else tags) + except TypeError as exc: + raise InvalidInputError("Discovery tags must be a collection of strings") from exc + if any(not isinstance(tag, str) for tag in tag_items): + raise InvalidInputError("Discovery tags must be a collection of strings") + if readonly is not None and not isinstance(readonly, bool) or not isinstance(include_approval_required, bool): + raise InvalidInputError("Discovery flags must be booleans") + if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 100: + raise InvalidInputError("Discovery limit must be an integer from 1 through 100") + normalized_query = query.strip().lower() if query is not None else "" + return cls( + normalized_query or None, prefix, tuple(sorted(set(tag_items))), readonly, limit, include_approval_required + ) + + def matches(self, item: ModuleSummary) -> bool: + return ( + (self.readonly is None or self.readonly == item.readonly) + and all(tag in item.tags for tag in self.tags) + and (self.include_approval_required or item.access_hint != "requires_approval") + ) + + +@dataclass(frozen=True) +class _Caller: + identity: Identity | None + caller_id: str | None + call_chain: tuple[str, ...] + + @classmethod + def capture(cls, context: Context) -> _Caller: + return cls(deepcopy(context.identity), context.caller_id, tuple(context.call_chain)) + + def snapshot_context(self, context: Context) -> Context: + snapshot = copy(context) + snapshot.identity = self.identity + snapshot.caller_id = self.caller_id + snapshot.call_chain = list(self.call_chain) + return snapshot + + def digest(self) -> str: + identity = self.identity + scope = { + "caller_id": self.caller_id, + "call_chain": list(self.call_chain), + "identity": None + if identity is None + else { + "id": identity.id, + "type": identity.type, + "roles": list(identity.roles), + "attrs": identity.attrs, + }, + } + try: + return _argument_digest(scope) + except PolicyEvaluationError: + raise InvalidInputError("Invalid discovery cursor") from None + + +@dataclass(frozen=True) +class _Cursor: + expires_at: float + caller_digest: str + filters: _Filters + after: str + provider: CapabilitySearchProvider | None + remaining_ranked_ids: tuple[str, ...] | None + + +_Registration = tuple["_ModuleRegistration", object | None] + + +@dataclass(frozen=True) +class _SummaryCandidate: + index: int + summary: ModuleSummary + registration: _Registration + access: VisibilityDecision + + +class _CapabilityDiscovery: + def __init__(self) -> None: + self.provider: CapabilitySearchProvider | None = None + self._cursors: OrderedDict[str, _Cursor] = OrderedDict() + self._cursor_lock = Lock() + + def _cursor( + self, token: str | None, caller: _Caller, filters: _Filters, provider: CapabilitySearchProvider | None + ) -> _Cursor | None: + if token is None: + return None + if not isinstance(token, str) or len(token) != 32: + raise InvalidInputError("Invalid discovery cursor") + with self._cursor_lock: + entry = self._cursors.get(token) + if ( + entry is None + or entry.expires_at <= monotonic() + or entry.caller_digest != caller.digest() + or entry.filters != filters + or entry.provider is not provider + ): + raise InvalidInputError("Invalid discovery cursor") + return entry + + def _next_cursor(self, entry: _Cursor) -> str: + token = token_urlsafe(24) + with self._cursor_lock: + self._cursors[token] = entry + if len(self._cursors) > _MAX_CURSORS: + self._cursors.popitem(last=False) + return token + + def list(self, executor: Executor, context: Context, filters: _Filters, cursor: str | None) -> CapabilityPage: + caller = _Caller.capture(context) + context = caller.snapshot_context(context) + provider = self.provider + entry = self._cursor(cursor, caller, filters, provider) + if entry is not None and entry.remaining_ranked_ids is not None: + candidates = entry.remaining_ranked_ids + else: + candidates = tuple(executor.registry.list(prefix=filters.prefix)) + if entry is not None: + candidates = tuple(module_id for module_id in candidates if module_id > entry.after) + elif provider is not None: + eligible = tuple(self._summaries(executor, context, filters, candidates, lexical=False)) + allowed_ids = tuple( + candidate.summary.module_id + for candidate in eligible + if self._summary_is_current(executor, context, candidate) + ) + allowed = set(allowed_ids) + candidates = tuple( + dict.fromkeys( + candidate + for candidate in provider.search(filters.query, allowed_ids) + if isinstance(candidate, str) and candidate in allowed + ) + ) + + items: list[_SummaryCandidate] = [] + next_cursor = None + for candidate in self._summaries(executor, context, filters, candidates, lexical=provider is None): + if len(items) == filters.limit: + next_cursor = self._next_cursor( + _Cursor( + monotonic() + _CURSOR_TTL_SECONDS, + caller.digest(), + filters, + items[-1].summary.module_id, + provider, + candidates[candidate.index :] if provider is not None else None, + ) + ) + break + items.append(candidate) + emitted = tuple(item.summary for item in items if self._summary_is_current(executor, context, item)) + return CapabilityPage(emitted, next_cursor) + + def _summary_is_current(self, executor: Executor, context: Context, item: _SummaryCandidate) -> bool: + current = self._visible(executor, item.summary.module_id, context, None) + return current is not None and _same_registration(item.registration, current[0]) and item.access == current[1] + + def _summaries( + self, executor: Executor, context: Context, filters: _Filters, candidates: tuple[str, ...], *, lexical: bool + ) -> Iterable[_SummaryCandidate]: + for index, module_id in enumerate(candidates): + selected = self._visible(executor, module_id, context, None) + if selected is None: + continue + (registration, _), access = selected + metadata = registration.metadata + declared = metadata.get("annotations") + annotations = governance_union(getattr(registration.module, "annotations", None), declared) + hint = _access_hint(executor, module_id, annotations, access) + readonly = annotations.readonly if annotations is not None else False + if declared is not None: + readonly = declared.get("readonly", readonly) if isinstance(declared, dict) else declared.readonly + description = metadata.get("description") or "" + tags = tuple(metadata.get("tags") or ()) + if ( + lexical + and filters.query + and not any(filters.query in value.lower() for value in (module_id, description, *tags)) + ): + continue + item = ModuleSummary( + module_id, + executor.registry._effective_version(registration.module, metadata), + description, + tags, + readonly, + hint, + ) + if filters.matches(item) and _still_current(executor, module_id, None, selected[0]): + yield _SummaryCandidate(index, item, selected[0], access) + + def descriptor( + self, executor: Executor, module_id: str, context: Context, version_hint: str | None + ) -> ModuleDescriptor | None: + if not isinstance(module_id, str) or not module_id: + return None + context = _Caller.capture(context).snapshot_context(context) + selected = self._visible(executor, module_id, context, version_hint) + if selected is None: + return None + descriptor = deepcopy( + executor.registry._describe_registration(module_id, selected[0][0], warn_deprecation=False) + ) + current = self._visible(executor, module_id, context, version_hint) + if current is None or not _same_registration(selected[0], current[0]): + return None + return descriptor + + @staticmethod + def _visible( + executor: Executor, module_id: str, context: Context, version_hint: str | None + ) -> tuple[_Registration, VisibilityDecision] | None: + steps = executor.current_strategy.steps + lookup = next((step for step in steps if type(step) is BuiltinModuleLookup), None) + if lookup is None or lookup._registry is not executor.registry or lookup.toggle_state.is_disabled(module_id): + return None + selected = executor.registry._discovery_registration(module_id, version_hint) + if selected is None: + return None + gate = next((step for step in steps if type(step) is BuiltinACLCheck), None) + if gate is None: + return None + access = _visibility_decision(gate.acl, module_id, context) + if access.visible and _still_current(executor, module_id, version_hint, selected): + return selected, access + return None + + +def _same_registration(selected: _Registration, current: _Registration | None) -> bool: + return ( + current is not None + and selected[1] is current[1] + and selected[0].module is current[0].module + and selected[0].metadata is current[0].metadata + and selected[0].descriptor_metadata == current[0].descriptor_metadata + ) + + +def _still_current(executor: Executor, module_id: str, version_hint: str | None, selected: _Registration) -> bool: + current = executor.registry._discovery_registration(module_id, version_hint) + return _same_registration(selected, current) and not executor.toggle_state.is_disabled(module_id) + + +def _visibility_decision(acl: ACL | None, module_id: str, context: Context) -> VisibilityDecision: + if acl is None: + return VisibilityDecision(True) + evaluator = getattr(acl, "evaluate_visibility", None) + if not callable(evaluator) or ( + type(acl) is not ACL and getattr(type(acl), "evaluate_visibility", None) is ACL.evaluate_visibility + ): + return VisibilityDecision(False) + child = context.child(module_id) + child.identity = deepcopy(child.identity) + try: + decision = evaluator(child.caller_id, module_id, child) + except Exception: + return VisibilityDecision(False) + return decision if isinstance(decision, VisibilityDecision) else VisibilityDecision(False) + + +def _access_hint(executor: Executor, module_id: str, annotations: Any, access: VisibilityDecision) -> AccessHint: + gate = next((step for step in executor.current_strategy.steps if type(step) is BuiltinApprovalGate), None) + if gate is not None: + enforces = gate.policy.strict or gate.handler is not None or executor._policy_evaluator is not None + policy_requires_approval = ( + type(gate.policy) is ExecutionPolicy and gate.policy.resolve(module_id, annotations).needs_approval + ) + if enforces and (access.approval_required or policy_requires_approval): + return "requires_approval" + if type(gate.policy) is not ExecutionPolicy or enforces and access.approval_conditional: + return "conditional" + return "conditional" if executor._policy_evaluator is not None else "allowed" diff --git a/python/src/apcore/client.py b/python/src/apcore/client.py index 7ab3a26f..3b8c40af 100644 --- a/python/src/apcore/client.py +++ b/python/src/apcore/client.py @@ -22,6 +22,7 @@ from contextlib import aclosing from typing import Any, Callable +from apcore.capabilities import CallableDefinition, CapabilityPage, CapabilitySearchProvider from apcore.config import Config from apcore.context import Context from apcore.errors import InvalidInputError, SysModulesDisabledError @@ -43,6 +44,7 @@ from apcore.policy import ExecutionPolicy from apcore.observability.metrics import MetricsCollector from apcore.registry import Registry +from apcore.registry.types import ModuleDescriptor from apcore.streaming import StreamExecution from apcore.sys_modules.control import ToggleState @@ -67,6 +69,7 @@ def __init__( *, fail_on_error: bool = False, subscriber_registry: SubscriberRegistry | None = None, + capability_search_provider: CapabilitySearchProvider | None = None, ) -> None: """Initialize the APCore client. @@ -86,6 +89,8 @@ def __init__( ``sys_modules_errors``. subscriber_registry: Factories for this client's configured event subscribers. Omitting this uses the built-in factories. + capability_search_provider: Optional ranker for discoverable module IDs. + Configure it on the supplied Executor when one is provided. """ self.config = config self._shutdown_lock = threading.Lock() @@ -126,6 +131,7 @@ def __init__( config=config, policy=policy, toggle_state=self.toggle_state, + capability_search_provider=capability_search_provider, ) # Config-driven ACL discovery (D-64, Recommendation A). Resolve @@ -416,6 +422,48 @@ def describe(self, module_id: str) -> str: """ return self.registry.describe(module_id) + def list_callable( + self, + context: Context | None = None, + *, + query: str | None = None, + prefix: str | None = None, + tags: Iterable[str] | None = None, + readonly: bool | None = None, + limit: int = 20, + cursor: str | None = None, + include_approval_required: bool = True, + ) -> CapabilityPage: + """List public modules whose ACL proves visibility for this caller frame.""" + return self.executor.list_callable( + context, + query=query, + prefix=prefix, + tags=tags, + readonly=readonly, + limit=limit, + cursor=cursor, + include_approval_required=include_approval_required, + ) + + def get_callable_definition( + self, module_id: str, context: Context | None = None, *, version_hint: str | None = None + ) -> CallableDefinition | None: + """Expand one visible module to its complete schemas.""" + return self.executor.get_callable_definition(module_id, context, version_hint=version_hint) + + def get_callable_definitions( + self, module_ids: Iterable[str], context: Context | None = None + ) -> list[CallableDefinition]: + """Expand visible module IDs in request order.""" + return self.executor.get_callable_definitions(module_ids, context) + + def get_callable_descriptor( + self, module_id: str, context: Context | None = None, *, version_hint: str | None = None + ) -> ModuleDescriptor | None: + """Return a detached, authorized descriptor for trusted host projections.""" + return self.executor.get_callable_descriptor(module_id, context, version_hint=version_hint) + def use(self, middleware: Any) -> APCore: """Add class-based middleware. Returns self for chaining.""" self.executor.use(middleware) diff --git a/python/src/apcore/executor.py b/python/src/apcore/executor.py index d9bfa773..9b76b2da 100644 --- a/python/src/apcore/executor.py +++ b/python/src/apcore/executor.py @@ -11,7 +11,7 @@ import logging import threading import time -from collections.abc import AsyncGenerator, AsyncIterator +from collections.abc import AsyncGenerator, AsyncIterator, Iterable from contextlib import AsyncExitStack, aclosing from copy import copy, deepcopy from typing import TYPE_CHECKING, Any, Callable @@ -26,6 +26,13 @@ _is_idempotent, ) from apcore.cancel import CancelToken, ExecutionCancelledError +from apcore.capabilities import ( + CallableDefinition, + CapabilityPage, + CapabilitySearchProvider, + _CapabilityDiscovery, + _Filters, +) from apcore.config import Config from apcore.context import Context from apcore.context_keys import _current_trace_span @@ -75,6 +82,7 @@ _any_match, ) from apcore.registry import MAX_MODULE_ID_LENGTH, MODULE_ID_PATTERN, Registry +from apcore.registry.types import ModuleDescriptor from apcore.streaming import StreamExecution, _StreamObservation if TYPE_CHECKING: @@ -303,6 +311,7 @@ def __init__( approval_handler: ApprovalHandler | None = None, policy: ExecutionPolicy | None = None, policy_evaluator: PolicyEvaluator | None = None, + capability_search_provider: CapabilitySearchProvider | None = None, event_emitter: Any = None, toggle_state: Any = None, sync_bridge_timeout_ms: int | None = None, @@ -322,6 +331,7 @@ def __init__( policy: Optional ExecutionPolicy with execution-time governance overrides for the Step 5 gate (apcore#76 RFC pilot). policy_evaluator: Optional evaluator for the validated invocation. + capability_search_provider: Optional ranker for discoverable module IDs. event_emitter: Optional EventEmitter. When provided, the executor emits apcore.stream.post_validation_failed events so post-stream failures (which cannot un-send already-yielded @@ -398,6 +408,8 @@ def __init__( # while governance_state() reported the gate as configured and wired. self._strategy = self._bind_providers(self._strategy) self.set_policy_evaluator(policy_evaluator) + self._capability_discovery = _CapabilityDiscovery() + self.set_capability_search_provider(capability_search_provider) self._pipeline_engine = PipelineEngine() @@ -435,6 +447,7 @@ def from_registry( approval_handler: ApprovalHandler | None = None, policy: ExecutionPolicy | None = None, policy_evaluator: PolicyEvaluator | None = None, + capability_search_provider: CapabilitySearchProvider | None = None, sync_bridge_timeout_ms: int | None = None, ) -> Executor: """Convenience factory for creating an Executor from a Registry. @@ -448,6 +461,7 @@ def from_registry( approval_handler: Optional approval handler. policy: Optional execution-time governance policy (apcore#76). policy_evaluator: Optional evaluator for the validated invocation. + capability_search_provider: Optional ranker for discoverable module IDs. sync_bridge_timeout_ms: Optional wait limit for the sync thread bridge. Returns: @@ -462,6 +476,7 @@ def from_registry( approval_handler=approval_handler, policy=policy, policy_evaluator=policy_evaluator, + capability_search_provider=capability_search_provider, sync_bridge_timeout_ms=sync_bridge_timeout_ms, ) @@ -612,6 +627,12 @@ def set_policy_evaluator(self, evaluator: PolicyEvaluator | None) -> None: _bind_post_validation_policy(self._strategy, evaluator) self._policy_evaluator = evaluator + def set_capability_search_provider(self, provider: CapabilitySearchProvider | None) -> None: + """Install a ranker for new discovery queries, or restore lexical matching.""" + if provider is not None and not callable(getattr(provider, "search", None)): + raise InvalidInputError("Capability search provider must implement search()") + self._capability_discovery.provider = provider + def use(self, middleware: Middleware) -> Executor: """Add class-based middleware with duplicate detection and return self for chaining.""" self._middleware_manager.use(middleware) @@ -1681,6 +1702,57 @@ def _effective_strategy( # Introspection # ------------------------------------------------------------------------- + def list_callable( + self, + context: Context | None = None, + *, + query: str | None = None, + prefix: str | None = None, + tags: Iterable[str] | None = None, + readonly: bool | None = None, + limit: int = 20, + cursor: str | None = None, + include_approval_required: bool = True, + ) -> CapabilityPage: + """List public modules whose ACL proves visibility for this caller frame.""" + filters = _Filters.create(query, prefix, tags, readonly, limit, include_approval_required) + return self._capability_discovery.list( + self, context if context is not None else Context.create(), filters, cursor + ) + + def get_callable_descriptor( + self, module_id: str, context: Context | None = None, *, version_hint: str | None = None + ) -> ModuleDescriptor | None: + """Return a detached, authorized descriptor for trusted host projections.""" + return self._capability_discovery.descriptor( + self, module_id, context if context is not None else Context.create(), version_hint + ) + + def get_callable_definition( + self, module_id: str, context: Context | None = None, *, version_hint: str | None = None + ) -> CallableDefinition | None: + """Expand one ACL-visible module to its complete input and output schemas.""" + descriptor = self.get_callable_descriptor(module_id, context, version_hint=version_hint) + if descriptor is None: + return None + return CallableDefinition( + descriptor.module_id, descriptor.version, descriptor.input_schema, descriptor.output_schema + ) + + def get_callable_definitions( + self, module_ids: Iterable[str], context: Context | None = None + ) -> list[CallableDefinition]: + """Expand visible IDs in request order, suppressing absent and ineligible IDs.""" + if isinstance(module_ids, (str, bytes)): + raise InvalidInputError("Discovery module IDs must be a collection of strings") + parent = context if context is not None else Context.create() + definitions = [] + for module_id in dict.fromkeys(module_ids): + definition = self.get_callable_definition(module_id, parent) + if definition is not None: + definitions.append(definition) + return definitions + @classmethod def register_strategy(cls, name: str, strategy: ExecutionStrategy) -> None: """Register a named strategy for resolution by string name. diff --git a/python/src/apcore/extensions.py b/python/src/apcore/extensions.py index df58f811..8d546bda 100644 --- a/python/src/apcore/extensions.py +++ b/python/src/apcore/extensions.py @@ -13,6 +13,7 @@ from apcore.acl import ACL from apcore.approval import ApprovalHandler +from apcore.capabilities import CapabilitySearchProvider from apcore.errors import InvalidInputError from apcore.middleware import Middleware from apcore.observability.tracing import Span, SpanExporter, TracingMiddleware @@ -95,6 +96,12 @@ def _built_in_points() -> dict[str, ExtensionPoint]: description="Policy evaluator for validated invocations", multiple=False, ), + "capability_search_provider": ExtensionPoint( + name="capability_search_provider", + extension_type=CapabilitySearchProvider, + description="Rank eligible module IDs for capability discovery", + multiple=False, + ), } @@ -218,6 +225,7 @@ def apply(self, registry: Registry, executor: Executor) -> None: - acl -> executor.set_acl() - approval_handler -> executor.set_approval_handler() - policy_evaluator -> executor.set_policy_evaluator() + - capability_search_provider -> executor.set_capability_search_provider() - middleware -> executor.use() for each - span_exporter -> find TracingMiddleware, set exporter (composite if multiple) @@ -249,6 +257,10 @@ def apply(self, registry: Registry, executor: Executor) -> None: if evaluator is not None: executor.set_policy_evaluator(evaluator) + search_provider = self.get("capability_search_provider") + if search_provider is not None: + executor.set_capability_search_provider(search_provider) + # Middleware for mw in self.get_all("middleware"): executor.use(mw) diff --git a/python/src/apcore/registry/registry.py b/python/src/apcore/registry/registry.py index b80c01e4..70d80486 100644 --- a/python/src/apcore/registry/registry.py +++ b/python/src/apcore/registry/registry.py @@ -1897,7 +1897,10 @@ def _is_discoverable( Anything other than an explicit ``False`` keeps the module visible — the default ``True`` preserves backward compatibility. """ - meta = module_meta.get(module_id) + return Registry._registration_is_discoverable(modules.get(module_id), module_meta.get(module_id)) + + @staticmethod + def _registration_is_discoverable(module: Any, meta: dict[str, Any] | None) -> bool: if meta is not None: ann = meta.get("annotations") if ann is not None: @@ -1908,7 +1911,6 @@ def _is_discoverable( return False if discoverable is not None: return True - module = modules.get(module_id) if module is None: return True ann = getattr(module, "annotations", None) @@ -1918,6 +1920,23 @@ def _is_discoverable( return ann.get("discoverable", True) is not False return getattr(ann, "discoverable", True) is not False + def _discovery_registration( + self, module_id: str, version_hint: str | None + ) -> tuple[_ModuleRegistration, object | None] | None: + """Snapshot a public registration that can accept new calls, without holding a lease.""" + with self._lock: + if self._closed or module_id in self._draining or module_id in self._unavailable: + return None + try: + registration = self._resolve_registration(module_id, version_hint) + except ModuleNotFoundError: + return None + if registration is None or not self._registration_is_discoverable( + registration.module, registration.metadata + ): + return None + return registration, self._lease_generations.get(module_id) + def get_definition(self, module_id: str, version_hint: str | None = None) -> ModuleDescriptor | None: """Get a ModuleDescriptor for a registered module. Returns None if not found. @@ -1928,6 +1947,11 @@ def get_definition(self, module_id: str, version_hint: str | None = None) -> Mod registration = self._resolve_registration(module_id, version_hint) if registration is None: return None + return self._describe_registration(module_id, registration) + + def _describe_registration( + self, module_id: str, registration: _ModuleRegistration, *, warn_deprecation: bool = True + ) -> ModuleDescriptor: module = registration.module meta = registration.metadata version_str = meta.get("version") or getattr(module, "version", None) or DEFAULT_MODULE_VERSION @@ -1963,7 +1987,7 @@ def get_definition(self, module_id: str, version_hint: str | None = None) -> Mod # Log deprecation warning if x-deprecation is present deprecation = effective_metadata.get("x-deprecation") - if deprecation: + if deprecation and warn_deprecation: self._log_deprecation_warning(module_id, version_str, deprecation) sunset_date: str | None = None diff --git a/python/src/apcore/sys_modules/manifest.py b/python/src/apcore/sys_modules/manifest.py index a5a735cd..8ae24b90 100644 --- a/python/src/apcore/sys_modules/manifest.py +++ b/python/src/apcore/sys_modules/manifest.py @@ -1,18 +1,19 @@ -"""system.manifest.module and system.manifest.full sys modules.""" +"""System modules for manifests and capability discovery.""" from __future__ import annotations -from dataclasses import asdict +from dataclasses import asdict, replace from typing import Any from apcore.config import Config +from apcore.context import Context from apcore.errors import InvalidInputError, ModuleNotFoundError from apcore.module import ModuleAnnotations from apcore.registry.registry import Registry from apcore.registry.types import DependencyInfo from apcore.schema.annotations import governance_union -__all__ = ["ManifestFullModule", "ManifestModule", "ManifestModuleModule"] +__all__ = ["ManifestFullModule", "ManifestModule", "ManifestModuleModule", "ManifestSearchModule"] def _compute_source_path(config: Config | None, module_id: str) -> str | None: @@ -332,3 +333,62 @@ def _get_project_name(self) -> str: if self._config is None: return self.DEFAULT_PROJECT_NAME return self._config.get("project.name", "") or self.DEFAULT_PROJECT_NAME + + +class ManifestSearchModule: + """Return ACL-authorized summaries using the original caller's context.""" + + description = "Search public modules visible to the requesting caller" + annotations = ModuleAnnotations(readonly=True, idempotent=True, open_world=False) + input_schema: dict[str, Any] = { + "type": "object", + "additionalProperties": False, + "properties": { + "query": {"type": "string"}, + "prefix": {"type": "string"}, + "tags": {"type": "array", "items": {"type": "string"}}, + "readonly": {"type": "boolean"}, + "limit": {"type": "integer", "minimum": 1, "maximum": 100}, + "cursor": {"type": "string"}, + "include_approval_required": {"type": "boolean"}, + }, + } + output_schema: dict[str, Any] = { + "type": "object", + "additionalProperties": False, + "required": ["items", "next_cursor"], + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": False, + "required": ["module_id", "version", "description", "tags", "readonly", "access_hint"], + "properties": { + "module_id": {"type": "string"}, + "version": {"type": "string"}, + "description": {"type": "string"}, + "tags": {"type": "array", "items": {"type": "string"}}, + "readonly": {"type": "boolean"}, + "access_hint": {"enum": ["allowed", "requires_approval", "conditional"]}, + }, + }, + }, + "next_cursor": {"type": ["string", "null"]}, + }, + } + + def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + from apcore.executor import Executor + + if not isinstance(context.executor, Executor) or context.call_chain[-1:] != ["system.manifest.search"]: + raise InvalidInputError("Manifest search requires a bound invocation context") + if any(value is None for value in inputs.values()): + raise InvalidInputError("Manifest search filters must not be null") + callers = context.call_chain[:-1] + original = replace(context, call_chain=callers, caller_id=callers[-2] if len(callers) > 1 else None) + page = context.executor.list_callable(original, **inputs) + return { + "items": [{**asdict(item), "tags": list(item.tags)} for item in page.items], + "next_cursor": page.next_cursor, + } diff --git a/python/src/apcore/sys_modules/registration.py b/python/src/apcore/sys_modules/registration.py index ad7dde3f..492194fa 100644 --- a/python/src/apcore/sys_modules/registration.py +++ b/python/src/apcore/sys_modules/registration.py @@ -32,7 +32,7 @@ ) from apcore.sys_modules.health import HealthModule, HealthSummaryModule from apcore.sys_modules.overrides import FileOverridesStore, OverridesStore -from apcore.sys_modules.manifest import ManifestFullModule, ManifestModule +from apcore.sys_modules.manifest import ManifestFullModule, ManifestModule, ManifestSearchModule from apcore.sys_modules.usage import UsageModule, UsageSummaryModule from apcore.observability.usage import UsageCollector, UsageMiddleware @@ -348,7 +348,7 @@ def _register_sys_modules( and the one ``schemas/sys-modules.schema.json`` declares, key by key: - ``health.enabled`` — "Whether system.health.summary and system.health.module are registered" - - ``manifest.enabled`` — "Whether system.manifest.module and system.manifest.full are registered" + - ``manifest.enabled`` — whether the manifest modules are registered - ``usage.enabled`` — "Whether system.usage.summary and system.usage.module are registered" All three default to ``True``, so the flags narrow and never widen. @@ -382,6 +382,7 @@ def _register_sys_modules( if _cfg_get(sys_cfg, config, "manifest.enabled", True): register_module("system.manifest.module", ManifestModule(registry=registry, config=config)) register_module("system.manifest.full", ManifestFullModule(registry=registry, config=config)) + register_module("system.manifest.search", ManifestSearchModule()) if _cfg_get(sys_cfg, config, "usage.enabled", True): register_module("system.usage.summary", UsageSummaryModule(collector=usage_collector)) diff --git a/python/tests/conformance/test_capability_discovery.py b/python/tests/conformance/test_capability_discovery.py new file mode 100644 index 00000000..535e8bc1 --- /dev/null +++ b/python/tests/conformance/test_capability_discovery.py @@ -0,0 +1,76 @@ +"""Exercise the public discovery APIs against the shared cases.""" + +from dataclasses import asdict +from typing import Any + +import pytest + +from apcore import Context, Executor, Identity, ModuleAnnotations, Registry +from apcore.acl import ACL, ACLRule +from conformance.canonical_fixtures import case_ids, load_fixture + +FIXTURE = "capability_discovery.json" +INPUT_SCHEMA = {"type": "object", "properties": {"message": {"type": "string"}}} +OUTPUT_SCHEMA = {"type": "object", "properties": {"ok": {"type": "boolean"}}} + + +class Operation: + input_schema = INPUT_SCHEMA + output_schema = OUTPUT_SCHEMA + version = "1.0.0" + + def __init__(self, row: dict[str, Any]) -> None: + self.description = row["description"] + self.tags = row.get("tags", []) + self.annotations = ModuleAnnotations( + discoverable=row.get("discoverable", True), + readonly=row.get("readonly", False), + requires_approval=row.get("requires_approval", False), + ) + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + pytest.fail("Discovery must not execute the module") + + +class Evaluator: + async def evaluate(self, request: Any) -> Any: + pytest.fail("Discovery must not evaluate final-input policy") + + +class Approval: + async def request_approval(self, request: Any) -> Any: + pytest.fail("Discovery must not request approval") + + +@pytest.mark.parametrize("case", load_fixture(FIXTURE)["test_cases"], ids=case_ids(FIXTURE)) +def test_capability_discovery(case: dict[str, Any]) -> None: + case_input, expected = case["input"], case["expected"] + audits = [] + acl = ACL(rules=[ACLRule(**rule) for rule in case_input["rules"]], audit_logger=audits.append) + registry = Registry() + for row in load_fixture(FIXTURE)["driver_contract"]["modules"]: + registry.register(row["module_id"], Operation(row)) + with Executor( + registry, + acl=acl, + approval_handler=Approval(), + policy_evaluator=Evaluator() if case_input.get("policy_evaluator") else None, + ) as executor: + context = Context.create(identity=Identity("fixture-user", roles=tuple(case_input.get("roles", [])))) + if caller_id := case_input.get("caller_id"): + context = context.child(caller_id) + page = executor.list_callable(context, **case_input.get("options", {})) + definitions = executor.get_callable_definitions( + ["demo.hidden", "demo.echo", "demo.review", "demo.unknown", "demo.echo"], context + ) + assert [{"module_id": item.module_id, "access_hint": item.access_hint} for item in page.items] == expected["items"] + for item in page.items: + assert "input_schema" not in asdict(item) + assert item.version == "1.0.0" + assert len(audits) == expected["audit_entries"] + assert [entry.module_id for entry in definitions] == expected.get( + "definitions", [item["module_id"] for item in expected["items"]] + ) + for entry in definitions: + assert entry.input_schema == INPUT_SCHEMA + assert entry.output_schema == OUTPUT_SCHEMA diff --git a/python/tests/test_capability_discovery.py b/python/tests/test_capability_discovery.py new file mode 100644 index 00000000..eb3298ca --- /dev/null +++ b/python/tests/test_capability_discovery.py @@ -0,0 +1,228 @@ +"""Discovery isolation and lifecycle cases that need the owning Python host.""" + +from typing import Any + +import pytest + +from apcore import APCore, Context, Executor, Identity, ModuleAnnotations, Registry +from apcore.acl import ACL, ACLRule +from apcore.config import Config +from apcore.errors import ACLDeniedError, InvalidInputError, SchemaValidationError + + +class Module: + input_schema = {"type": "object", "properties": {"key": {"type": "string"}}} + output_schema = {"type": "object"} + description = "Test module" + + def __init__(self, *, discoverable: bool = True, version: str = "1.0.0") -> None: + self.version = version + self.annotations = ModuleAnnotations(discoverable=discoverable) + + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + pytest.fail("Discovery must not enter a module") + + +def test_cursor_is_scoped_rechecked_and_input_validation_is_generic() -> None: + registry = Registry() + for module_id in ("demo.a", "demo.b", "demo.c"): + registry.register(module_id, Module()) + acl = ACL([ACLRule(["@external"], ["demo.*"], "allow")]) + with Executor(registry, acl=acl) as executor: + identity = Identity("reader", roles=("staff",), attrs={"tenant": {"region": "north"}}) + context = Context.create(identity=identity) + first = executor.list_callable(context, limit=1) + assert [item.module_id for item in first.items] == ["demo.a"] + assert first.next_cursor + for foreign in ( + Context.create(identity=Identity("other", roles=identity.roles, attrs=identity.attrs)), + Context.create(identity=Identity("reader", roles=("other",), attrs=identity.attrs)), + Context.create(identity=Identity("reader", roles=identity.roles, attrs={"tenant": {"region": "south"}})), + context.child("other.module"), + ): + with pytest.raises(InvalidInputError, match="Invalid discovery cursor"): + executor.list_callable(foreign, limit=1, cursor=first.next_cursor) + with pytest.raises(InvalidInputError, match="Invalid discovery cursor"): + executor.list_callable(context, limit=1, prefix="demo.", cursor=first.next_cursor) + with pytest.raises(InvalidInputError, match="Invalid discovery cursor"): + executor.list_callable(context, limit=1, cursor=f"{first.next_cursor}unexpected") + acl.add_rule(callers=["@external"], targets=["demo.b"], effect="deny") + second = executor.list_callable(context, limit=1, cursor=first.next_cursor) + assert [item.module_id for item in second.items] == ["demo.c"] + assert second.next_cursor is None + + +@pytest.mark.parametrize(("original", "other"), [(True, 1), (1, 1.0), (-0.0, 0.0)]) +def test_cursor_distinguishes_identity_attribute_types(original: Any, other: Any) -> None: + registry = Registry() + for module_id in ("demo.a", "demo.b"): + registry.register(module_id, Module()) + with Executor(registry) as executor: + context = Context.create(identity=Identity("reader", attrs={"tenant": [original]})) + first = executor.list_callable(context, limit=1) + assert first.next_cursor + altered = Context.create(identity=Identity("reader", attrs={"tenant": [other]})) + with pytest.raises(InvalidInputError, match="Invalid discovery cursor"): + executor.list_callable(altered, limit=1, cursor=first.next_cursor) + + +def test_full_definition_uses_live_version_and_detaches_schemas() -> None: + registry = Registry() + registry.register("demo.versioned", Module(discoverable=False), version="1.0.0") + registry.register("demo.versioned", Module(version="2.0.0"), version="2.0.0") + with Executor(registry) as executor: + assert executor.get_callable_definition("demo.versioned", version_hint="1.0.0") is None + definition = executor.get_callable_definition("demo.versioned", version_hint="2.0.0") + assert definition is not None and definition.version == "2.0.0" + definition.input_schema["properties"].clear() + assert executor.get_callable_definitions(["demo.versioned"])[0].input_schema == Module.input_schema + executor.toggle_state.disable("demo.versioned") + try: + assert executor.get_callable_definition("demo.versioned") is None + assert not executor.list_callable().items + finally: + executor.toggle_state.enable("demo.versioned") + + +def test_summary_readonly_uses_descriptor_while_approval_uses_both_annotations() -> None: + registry = Registry() + module = Module() + module.annotations = ModuleAnnotations(requires_approval=True) + registry.register( + "demo.annotated", module, metadata={"annotations": {"readonly": True, "requires_approval": False}} + ) + with Executor(registry) as executor: + (summary,) = executor.list_callable(readonly=True).items + assert summary.readonly and summary.access_hint == "requires_approval" + + +def test_search_provider_output_cannot_disclose_hidden_or_denied_ids() -> None: + registry = Registry() + for module_id in ("demo.allowed", "demo.denied"): + registry.register(module_id, Module()) + registry.register("demo.hidden", Module(discoverable=False)) + + class SearchProvider: + def search(self, query: str | None, candidates: tuple[str, ...]) -> list[str]: + assert query == "semantic match" + assert candidates == ("demo.allowed",) + return ["demo.hidden", "demo.denied", "demo.unknown", "demo.allowed", "demo.allowed"] + + acl = ACL([ACLRule(["@external"], ["demo.allowed"], "allow")]) + with Executor(registry, acl=acl, capability_search_provider=SearchProvider()) as executor: + assert [item.module_id for item in executor.list_callable(query="semantic match").items] == ["demo.allowed"] + + +def test_summary_page_drops_a_replaced_registration_before_emission(monkeypatch: pytest.MonkeyPatch) -> None: + registry = Registry() + for module_id in ("demo.a", "demo.b"): + registry.register(module_id, Module()) + snapshot = registry._discovery_registration + + def replace_prior_registration(module_id: str, version_hint: str | None) -> Any: + if module_id == "demo.b" and registry.has("demo.a"): + assert registry.unregister("demo.a") + return snapshot(module_id, version_hint) + + monkeypatch.setattr(registry, "_discovery_registration", replace_prior_registration) + with Executor(registry) as executor: + assert [item.module_id for item in executor.list_callable().items] == ["demo.b"] + + +def test_effective_custom_condition_is_never_called_and_faults_stay_silent(monkeypatch: pytest.MonkeyPatch) -> None: + class Replacement: + async def evaluate(self, value: Any, context: Context) -> bool: + pytest.fail("Discovery must not invoke a registered replacement") + + monkeypatch.setitem(ACL._async_condition_handlers, "roles", Replacement()) + audits = [] + acl = ACL( + [ + ACLRule(["@external"], ["demo.*"], "deny", conditions={"roles": ["reader"]}), + ACLRule(["@external"], ["demo.*"], "allow"), + ], + audit_logger=audits.append, + ) + context = Context.create(identity=Identity("actor", roles=("operator",))) + assert not acl.evaluate_visibility(None, "demo.allowed", context.child("demo.allowed")).visible + assert not audits + + +@pytest.mark.asyncio +@pytest.mark.parametrize("conditions", [{"$or": [{}]}, {"$not": {"roles": ["unknown"]}}]) +async def test_discovery_uses_registered_compound_condition_identity( + monkeypatch: pytest.MonkeyPatch, conditions: dict[str, Any] +) -> None: + calls: list[str] = [] + + class Replacement: + async def evaluate(self, value: Any, context: Context) -> bool: + calls.append("evaluated") + return False + + key = next(iter(conditions)) + monkeypatch.setattr(ACL, "_async_condition_handlers", ACL._async_condition_handlers.copy()) + ACL.register_async_condition(key, Replacement()) + registry = Registry() + registry.register("demo.visible", Module()) + acl = ACL([ACLRule(["@external"], ["demo.visible"], "allow", conditions=conditions)]) + context = Context.create(identity=Identity("reader", roles=("staff",))) + with Executor(registry, acl=acl) as executor: + with pytest.raises(ACLDeniedError): + await executor.call_async("demo.visible", {}, context) + assert calls == ["evaluated"] + assert executor.get_callable_descriptor("demo.visible", context) is None + assert not executor.list_callable(context).items + assert calls == ["evaluated"] + + +def test_definition_discards_schema_when_the_same_version_is_replaced(monkeypatch: pytest.MonkeyPatch) -> None: + registry = Registry() + registry.register("demo.versioned", Module(), version="1.0.0") + describe = registry._describe_registration + replaced = False + + def replace_registration(*args: Any, **kwargs: Any) -> Any: + nonlocal replaced + metadata = describe(*args, **kwargs) + if not replaced: + replaced = True + assert registry.unregister("demo.versioned") + registry.register("demo.versioned", Module(discoverable=False), version="1.0.0") + return metadata + + monkeypatch.setattr(registry, "_describe_registration", replace_registration) + with Executor(registry) as executor: + assert executor.get_callable_descriptor("demo.versioned", version_hint="1.0.0") is None + assert replaced + + +@pytest.mark.asyncio +async def test_manifest_search_does_not_use_its_own_caller_grant() -> None: + registry = Registry() + registry.register("demo.visible", Module()) + registry.register("demo.private", Module()) + acl = ACL( + [ + ACLRule(["@external"], ["system.manifest.search"], "allow"), + ACLRule(["@external"], ["demo.visible"], "allow", conditions={"max_call_depth": 1}), + ACLRule(["system.manifest.search"], ["demo.private"], "allow"), + ] + ) + config = Config({"sys_modules": {"enabled": True}}) + with Executor(registry, acl=acl) as executor: + app = APCore(executor=executor, config=config) + result = await app.call_async("system.manifest.search", {"prefix": "demo."}) + assert [item["module_id"] for item in result["items"]] == ["demo.visible"] + + +@pytest.mark.asyncio +async def test_manifest_search_rejects_null_wire_options() -> None: + app = APCore(config=Config({"sys_modules": {"enabled": True}})) + try: + for name in ("query", "prefix", "tags", "readonly", "limit", "cursor", "include_approval_required"): + with pytest.raises(SchemaValidationError): + await app.call_async("system.manifest.search", {name: None}) + assert (await app.call_async("system.manifest.search", {}))["next_cursor"] is None + finally: + await app.shutdown() diff --git a/python/tests/test_extensions.py b/python/tests/test_extensions.py index 6850a57e..ea2cabfe 100644 --- a/python/tests/test_extensions.py +++ b/python/tests/test_extensions.py @@ -50,10 +50,10 @@ def export(self, span: Any) -> None: class TestExtensionManagerInit: - def test_has_seven_built_in_points(self) -> None: + def test_has_eight_built_in_points(self) -> None: mgr = ExtensionManager() points = mgr.list_points() - assert len(points) == 7 + assert len(points) == 8 def test_built_in_point_names(self) -> None: mgr = ExtensionManager() @@ -66,6 +66,7 @@ def test_built_in_point_names(self) -> None: "module_validator", "approval_handler", "policy_evaluator", + "capability_search_provider", } def test_list_points_returns_extension_point_instances(self) -> None: diff --git a/python/tests/test_public_api.py b/python/tests/test_public_api.py index ff6134ea..f05db9a9 100644 --- a/python/tests/test_public_api.py +++ b/python/tests/test_public_api.py @@ -455,6 +455,12 @@ class TestPublicAPIAll: "ApprovalResult", "AutoApproveHandler", "CancelToken", + "AccessHint", + "CallableDefinition", + "CapabilityPage", + "CapabilitySearchProvider", + "ModuleSummary", + "VisibilityDecision", "Context", "ErrorCodes", "ExecutionPolicy", diff --git a/python/uv.lock b/python/uv.lock index 295688e3..3cfdb6cf 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -199,7 +199,7 @@ wheels = [ [[package]] name = "apcore" -version = "1.0.0a3" +version = "1.0.0a4" source = { editable = "." } dependencies = [ { name = "jsonschema" }, diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 15ab0d16..db7e30ff 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -42,7 +42,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.3" +version = "1.0.0-alpha.4" dependencies = [ "async-stream", "async-trait", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index b3754569..a75722e0 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore" -version = "1.0.0-alpha.3" +version = "1.0.0-alpha.4" edition = "2021" # Minimum supported Rust version. Verified with `cargo +1.86 check --all-features`. # The binding language constraint is `std::task::Waker::noop()` (used by the diff --git a/rust/apcore-conformance.yaml b/rust/apcore-conformance.yaml index 6124a5e5..42abe97d 100644 --- a/rust/apcore-conformance.yaml +++ b/rust/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-rust - version: 1.0.0-alpha.3 + version: 1.0.0-alpha.4 language: rust spec_version: 1.65.0 maintainer: AI Perceivable diff --git a/rust/src/acl.rs b/rust/src/acl.rs index f4cb480f..52311074 100644 --- a/rust/src/acl.rs +++ b/rust/src/acl.rs @@ -937,6 +937,16 @@ impl RuleValidationFinding { } } +/// Discovery distinguishes an unknown but structurally valid rule from a +/// malformed rule that must follow the existing fail-closed semantics. +#[derive(Clone, Copy, PartialEq, Eq)] +enum DiscoveryRule { + Match, + NoMatch, + Unknown, + Malformed, +} + /// Outcome of matching one ACL rule against a call (PROTOCOL_SPEC §6.3). /// /// Three variants rather than a `bool`, because a rule whose conditions could @@ -1751,6 +1761,82 @@ impl ACL { decision } + /// Prove a target visible for the given caller without evaluating custom + /// conditions, writing an audit entry, or reading submitted arguments. + /// + /// The context, when supplied, is the prospective invocation frame. + /// Returns no hint when any reachable rule could deny access. + #[must_use] + pub fn evaluate_visibility( + &self, + caller_id: Option<&str>, + target_id: &str, + ctx: Option<&Context>, + ) -> Option { + use crate::capability::AccessHint; + let caller = caller_id.unwrap_or(EXTERNAL_CALLER); + let mut pending_approval = false; + let mut possible_without_approval = false; + let mut possible_with_approval = false; + for rule in &self.rules { + let decision = Self::discovery_rule(rule, caller, target_id, ctx); + let requires_approval = rule.approval_required(); + match decision { + DiscoveryRule::NoMatch => continue, + DiscoveryRule::Malformed if rule.effect == "allow" => { + pending_approval |= requires_approval; + continue; + } + _ if rule.effect != "allow" => return None, + _ => {} + } + possible_with_approval |= requires_approval || pending_approval; + possible_without_approval |= !(requires_approval || pending_approval); + if decision == DiscoveryRule::Match { + return Some(AccessHint::from_approval_outcomes( + possible_with_approval, + possible_without_approval, + )); + } + } + (self.default_effect == "allow").then(|| { + AccessHint::from_approval_outcomes( + possible_with_approval || pending_approval, + possible_without_approval || !pending_approval, + ) + }) + } + + fn discovery_rule( + rule: &ACLRule, + caller: &str, + target: &str, + ctx: Option<&Context>, + ) -> DiscoveryRule { + if !Self::precheck_pattern_faults(rule).is_empty() { + return DiscoveryRule::Malformed; + } + if !Self::match_patterns(&rule.callers, caller, ctx) + || !Self::match_patterns(&rule.targets, target, ctx) + { + return DiscoveryRule::NoMatch; + } + let Some(conditions) = &rule.conditions else { + return DiscoveryRule::Match; + }; + if !precheck_conditions(conditions, PrecheckPath::Async).is_empty() { + return DiscoveryRule::Malformed; + } + let Some(ctx) = ctx else { + return DiscoveryRule::NoMatch; + }; + match crate::acl_handlers::discovery_conditions(conditions, ctx) { + ConditionOutcome::Satisfied => DiscoveryRule::Match, + ConditionOutcome::Unsatisfied => DiscoveryRule::NoMatch, + ConditionOutcome::Unevaluable => DiscoveryRule::Unknown, + } + } + fn check_inner( &self, caller_id: Option<&str>, diff --git a/rust/src/acl_handlers.rs b/rust/src/acl_handlers.rs index c1f42592..f1d298c3 100644 --- a/rust/src/acl_handlers.rs +++ b/rust/src/acl_handlers.rs @@ -1295,11 +1295,81 @@ fn collect_argument_faults(value: &Value, key_path: &str, out: &mut Vec> = + LazyLock::new(|| Arc::new(IdentityTypesHandler)); +static DISCOVERY_ROLES: LazyLock> = + LazyLock::new(|| Arc::new(RolesHandler)); +static DISCOVERY_MAX_CALL_DEPTH: LazyLock> = + LazyLock::new(|| Arc::new(MaxCallDepthHandler)); +static DISCOVERY_OR: LazyLock> = + LazyLock::new(|| Arc::new(OrHandler::new(CompoundMode::Async))); +static DISCOVERY_NOT: LazyLock> = + LazyLock::new(|| Arc::new(NotHandler::new(CompoundMode::Async))); + +fn stock_discovery_handler(key: &str) -> Option<&'static Arc> { + let stock = match key { + "identity_types" => &*DISCOVERY_IDENTITY_TYPES, + "roles" => &*DISCOVERY_ROLES, + "max_call_depth" => &*DISCOVERY_MAX_CALL_DEPTH, + "$or" => &*DISCOVERY_OR, + "$not" => &*DISCOVERY_NOT, + _ => return None, + }; + let async_handlers = ASYNC_CONDITION_HANDLERS.read(); + let handlers = CONDITION_HANDLERS.read(); + async_handlers + .get(key) + .or_else(|| handlers.get(key)) + .is_some_and(|handler| Arc::ptr_eq(handler, stock)) + .then_some(stock) +} + +/// Evaluate a prechecked condition tree with no business arguments. Here +/// Unevaluable means a well-formed condition with an unknown call-time result. +pub(crate) fn discovery_conditions(conditions: &Value, ctx: &Context) -> ConditionOutcome { + let Some(conditions) = conditions.as_object() else { + return ConditionOutcome::Unevaluable; + }; + conditions + .iter() + .fold(ConditionOutcome::Satisfied, |result, (key, value)| { + result.and(discovery_condition(key, value, ctx)) + }) +} + +fn discovery_condition(key: &str, value: &Value, ctx: &Context) -> ConditionOutcome { + let Some(handler) = stock_discovery_handler(key) else { + return ConditionOutcome::Unevaluable; + }; + match key { + "$or" => { + let Some(branches) = value.as_array() else { + return ConditionOutcome::Unevaluable; + }; + branches + .iter() + .fold(ConditionOutcome::Unsatisfied, |result, branch| { + result.or(discovery_conditions(branch, ctx)) + }) + } + "$not" => discovery_conditions(value, ctx).negate(), + _ => { + use futures_util::FutureExt; + handler + .evaluate_outcome(value, ctx) + .now_or_never() + .unwrap_or(ConditionOutcome::Unevaluable) + } + } +} + /// Register all built-in handlers. Called once during initialization. pub fn register_builtin_handlers() { - seed_condition("identity_types", || Arc::new(IdentityTypesHandler)); - seed_condition("roles", || Arc::new(RolesHandler)); - seed_condition("max_call_depth", || Arc::new(MaxCallDepthHandler)); + seed_condition("identity_types", || Arc::clone(&DISCOVERY_IDENTITY_TYPES)); + seed_condition("roles", || Arc::clone(&DISCOVERY_ROLES)); + seed_condition("max_call_depth", || Arc::clone(&DISCOVERY_MAX_CALL_DEPTH)); // §6.1.7: `arguments` is part of the language §6.1 already defines, not a // mechanism beside it, so it is seeded here with the other built-ins and // has no registration point of its own. @@ -1307,8 +1377,8 @@ pub fn register_builtin_handlers() { // Mode-matched pairs — see `CompoundMode`. seed_condition("$or", || Arc::new(OrHandler::new(CompoundMode::Sync))); seed_condition("$not", || Arc::new(NotHandler::new(CompoundMode::Sync))); - seed_async_condition("$or", || Arc::new(OrHandler::new(CompoundMode::Async))); - seed_async_condition("$not", || Arc::new(NotHandler::new(CompoundMode::Async))); + seed_async_condition("$or", || Arc::clone(&DISCOVERY_OR)); + seed_async_condition("$not", || Arc::clone(&DISCOVERY_NOT)); } /// Install a built-in handler ONLY if `key` is unclaimed. diff --git a/rust/src/builtin_steps.rs b/rust/src/builtin_steps.rs index 7092382a..e927450a 100644 --- a/rust/src/builtin_steps.rs +++ b/rust/src/builtin_steps.rs @@ -314,6 +314,10 @@ impl Step for BuiltinCallChainGuard { #[async_trait] impl Step for BuiltinModuleLookup { + fn builtin_module_is_enabled(&self, module_id: &str) -> Option { + Some(!self.toggle_state.is_disabled(module_id)) + } + fn name(&self) -> &'static str { "module_lookup" } diff --git a/rust/src/capability.rs b/rust/src/capability.rs new file mode 100644 index 00000000..21b5f047 --- /dev/null +++ b/rust/src/capability.rs @@ -0,0 +1,515 @@ +//! Caller-scoped discovery of public, active capabilities. + +use std::collections::{HashSet, VecDeque}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use parking_lot::{Mutex, RwLock}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use uuid::Uuid; + +use crate::context::{Context, Identity}; +use crate::errors::ModuleError; +use crate::executor::Executor; +use crate::pipeline::BuiltinGate; +use crate::policy::ExecutionPolicy; + +const DEFAULT_LIMIT: usize = 20; +const MAX_LIMIT: usize = 100; +const CURSOR_TTL: Duration = Duration::from_secs(60); +const MAX_CURSORS: usize = 128; + +/// Advisory access requirements for a visible capability. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum AccessHint { + /// The known gates add no approval requirement. + Allowed, + /// The known gates require approval. + RequiresApproval, + /// The final requirements depend on the invocation. + Conditional, +} + +impl AccessHint { + pub(crate) fn from_approval_outcomes(required: bool, not_required: bool) -> Self { + match (required, not_required) { + (false, _) => Self::Allowed, + (true, false) => Self::RequiresApproval, + (true, true) => Self::Conditional, + } + } +} + +/// Filters and pagination controls for capability summaries. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +pub struct CapabilityQuery { + pub query: Option, + pub prefix: Option, + pub tags: Vec, + pub readonly: Option, + pub limit: usize, + pub cursor: Option, + pub include_approval_required: bool, +} + +impl Default for CapabilityQuery { + fn default() -> Self { + Self { + query: None, + prefix: None, + tags: Vec::new(), + readonly: None, + limit: DEFAULT_LIMIT, + cursor: None, + include_approval_required: true, + } + } +} + +impl CapabilityQuery { + fn normalize(&mut self) -> Result<(), ModuleError> { + if !(1..=MAX_LIMIT).contains(&self.limit) { + return Err(ModuleError::invalid_input( + "Capability limit must be between 1 and 100", + )); + } + self.query = self + .query + .as_deref() + .map(str::trim) + .filter(|query| !query.is_empty()) + .map(str::to_lowercase); + self.prefix = self.prefix.take().filter(|prefix| !prefix.is_empty()); + self.tags.sort_unstable(); + self.tags.dedup(); + Ok(()) + } + + fn matches_filters(&self, summary: &ModuleSummary) -> bool { + self.prefix + .as_ref() + .is_none_or(|prefix| summary.module_id.starts_with(prefix)) + && self + .readonly + .is_none_or(|readonly| summary.readonly == readonly) + && self.tags.iter().all(|tag| summary.tags.contains(tag)) + && (self.include_approval_required + || summary.access_hint != AccessHint::RequiresApproval) + } + + fn matches_query(&self, summary: &ModuleSummary) -> bool { + self.query.as_ref().is_none_or(|query| { + summary.module_id.to_lowercase().contains(query) + || summary.description.to_lowercase().contains(query) + || summary + .tags + .iter() + .any(|tag| tag.to_lowercase().contains(query)) + }) + } +} + +/// Lightweight discovery metadata. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct ModuleSummary { + pub module_id: String, + pub version: String, + pub description: String, + pub tags: Vec, + pub readonly: bool, + pub access_hint: AccessHint, +} + +/// A page of caller-scoped summaries. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct CapabilityPage { + pub items: Vec, + pub next_cursor: Option, +} + +/// Detached schemas for the selected callable registration. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct CallableDefinition { + pub module_id: String, + pub version: String, + pub input_schema: Value, + pub output_schema: Value, +} + +/// A host's optional ranking or selection of currently visible candidate IDs. +pub trait CapabilitySearchProvider: Send + Sync { + /// Return ranked IDs. The executor enforces filters and current visibility. + fn search(&self, query: Option<&str>, candidate_ids: &[String]) -> Vec; +} + +#[derive(Clone, PartialEq, Eq)] +struct CursorScope { + caller_id: Option, + call_chain: Vec, + identity: Option, +} + +impl From<&Context> for CursorScope { + fn from(context: &Context) -> Self { + Self { + caller_id: context.caller_id.clone(), + call_chain: context.call_chain.clone(), + identity: context.identity.clone(), + } + } +} + +#[derive(Clone)] +struct CursorPosition { + candidates: Arc>, + offset: usize, + custom_search: bool, + provider_revision: u64, +} + +struct CursorEntry { + token: Uuid, + scope: CursorScope, + query: CapabilityQuery, + position: CursorPosition, + created: Instant, +} + +#[derive(Clone, Default)] +struct SearchProvider { + implementation: Option>, + revision: u64, +} + +#[derive(Default)] +pub(crate) struct DiscoveryState { + provider: RwLock, + cursors: Mutex>, +} + +impl std::fmt::Debug for DiscoveryState { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("DiscoveryState") + .finish_non_exhaustive() + } +} + +impl DiscoveryState { + fn resume( + &self, + token: &str, + scope: &CursorScope, + query: &CapabilityQuery, + ) -> Result { + let invalid = || ModuleError::invalid_input("Invalid capability cursor"); + let token = Uuid::parse_str(token).map_err(|_| invalid())?; + let provider = self.provider.read(); + let mut cursors = self.cursors.lock(); + cursors.retain(|entry| { + entry.created.elapsed() < CURSOR_TTL + && entry.position.provider_revision == provider.revision + }); + cursors + .iter() + .find(|entry| entry.token == token && &entry.scope == scope && &entry.query == query) + .map(|entry| entry.position.clone()) + .ok_or_else(invalid) + } + + fn save(&self, scope: CursorScope, query: CapabilityQuery, position: CursorPosition) -> String { + let token = Uuid::new_v4(); + let mut cursors = self.cursors.lock(); + if cursors.len() == MAX_CURSORS { + cursors.pop_front(); + } + cursors.push_back(CursorEntry { + token, + scope, + query, + position, + created: Instant::now(), + }); + token.to_string() + } +} + +impl Executor { + /// Install or remove a provider for capability search. + pub fn set_capability_search_provider( + &self, + provider: Option>, + ) { + let mut registered = self.capability_discovery.provider.write(); + registered.implementation = provider; + registered.revision = registered.revision.wrapping_add(1); + self.capability_discovery.cursors.lock().clear(); + } + + /// Return a governed page of public capability summaries. Tokens can be + /// used only with the same executor, caller frame, and normalized filters. + pub fn list_callable( + &self, + context: Option<&Context>, + mut query: CapabilityQuery, + ) -> Result { + query.normalize()?; + let cursor = query.cursor.take(); + let anonymous = Context::anonymous(); + let context = context.unwrap_or(&anonymous); + let scope = CursorScope::from(context); + let position = match cursor { + Some(cursor) => self.capability_discovery.resume(&cursor, &scope, &query)?, + None => self.capability_candidates(context, &query), + }; + let mut items = Vec::new(); + let mut next_offset = None; + for (index, id) in position.candidates.iter().enumerate().skip(position.offset) { + let Some(summary) = self.discover_summary(id, context) else { + continue; + }; + if !query.matches_filters(&summary) + || (!position.custom_search && !query.matches_query(&summary)) + { + continue; + } + if items.len() == query.limit { + next_offset = Some(index); + break; + } + items.push(summary); + } + let next_cursor = next_offset.map(|offset| { + self.capability_discovery + .save(scope, query, CursorPosition { offset, ..position }) + }); + Ok(CapabilityPage { items, next_cursor }) + } + + fn capability_candidates( + &self, + context: &Context, + query: &CapabilityQuery, + ) -> CursorPosition { + let ids = self.registry.list(None, query.prefix.as_deref(), None); + let provider = self.capability_discovery.provider.read().clone(); + let custom_search = provider.implementation.is_some(); + let candidates = if let Some(provider) = provider.implementation { + let visible = ids + .into_iter() + .filter(|id| { + self.discover_summary(id, context) + .is_some_and(|summary| query.matches_filters(&summary)) + }) + .collect::>(); + let allowed: HashSet<&str> = visible.iter().map(String::as_str).collect(); + let mut seen = HashSet::new(); + provider + .search(query.query.as_deref(), &visible) + .into_iter() + .filter(|id| allowed.contains(id.as_str()) && seen.insert(id.clone())) + .collect() + } else { + ids + }; + CursorPosition { + candidates: Arc::new(candidates), + custom_search, + provider_revision: provider.revision, + offset: 0, + } + } + + /// Return definitions in request order, omitting duplicates and any + /// module that cannot be disclosed to the caller. + pub fn get_callable_definitions>( + &self, + module_ids: &[S], + context: Option<&Context>, + ) -> Vec { + let mut seen = HashSet::new(); + module_ids + .iter() + .map(AsRef::as_ref) + .filter(|id| seen.insert(*id)) + .filter_map(|id| self.get_callable_definition(id, None, context)) + .collect() + } + + /// Resolve a live, authorized definition, optionally checking an exact + /// expected version. Adapters can use this to reject stale exported IDs. + #[must_use] + pub fn get_callable_definition( + &self, + module_id: &str, + expected_version: Option<&str>, + context: Option<&Context>, + ) -> Option { + self.map_callable_descriptor( + module_id, + expected_version, + context, + self.strategy(), + |descriptor| CallableDefinition { + module_id: module_id.into(), + version: descriptor.version.clone(), + input_schema: descriptor.input_schema.clone(), + output_schema: descriptor.output_schema.clone(), + }, + ) + } + + /// Project a detached, currently authorized descriptor for a trusted adapter. + #[must_use] + pub fn get_callable_descriptor( + &self, + module_id: &str, + expected_version: Option<&str>, + context: Option<&Context>, + ) -> Option { + self.get_callable_descriptor_for_strategy( + module_id, + expected_version, + context, + self.strategy(), + ) + } + + /// Project a descriptor for an adapter using an explicit execution strategy. + #[must_use] + pub fn get_callable_descriptor_for_strategy( + &self, + module_id: &str, + expected_version: Option<&str>, + context: Option<&Context>, + strategy: &crate::ExecutionStrategy, + ) -> Option { + self.map_callable_descriptor( + module_id, + expected_version, + context, + strategy, + |descriptor| { + let mut live = descriptor.clone(); + module_id.clone_into(&mut live.module_id); + live + }, + ) + } + + fn map_callable_descriptor( + &self, + module_id: &str, + expected_version: Option<&str>, + context: Option<&Context>, + strategy: &crate::ExecutionStrategy, + map: impl FnOnce(&crate::registry::ModuleDescriptor) -> T, + ) -> Option { + let anonymous = Context::anonymous(); + let context = context.unwrap_or(&anonymous); + self.visibility_hint(module_id, context, strategy)?; + self.registry + .with_discoverable_descriptor(module_id, |descriptor, _| { + if expected_version.is_some_and(|version| version != descriptor.version) { + return None; + } + Some(map(descriptor)) + })? + } + + fn visibility_hint( + &self, + module_id: &str, + parent: &Context, + strategy: &crate::ExecutionStrategy, + ) -> Option { + if self.pipeline_load_error.is_some() || self.acl_load_error.is_some() { + return None; + } + let permits_lookup = strategy + .steps() + .iter() + .find_map(|step| step.builtin_module_is_enabled(module_id)); + if permits_lookup != Some(true) { + return None; + } + if !strategy + .steps() + .iter() + .any(|step| step.builtin_gate() == Some(BuiltinGate::Acl)) + { + return None; + } + if let Some(acl) = &self.acl { + let prospective = parent.child(module_id); + return acl.evaluate_visibility( + prospective.caller_id.as_deref(), + module_id, + Some(&prospective), + ); + } + Some(AccessHint::Allowed) + } + + fn has_discovery_gate(&self, gate: BuiltinGate) -> bool { + self.strategy() + .steps() + .iter() + .any(|step| step.builtin_gate() == Some(gate)) + } + + fn discover_summary(&self, module_id: &str, context: &Context) -> Option { + let acl = self.visibility_hint(module_id, context, self.strategy())?; + let (mut summary, module, declared) = + self.registry + .with_discoverable_descriptor(module_id, |descriptor, module| { + ( + ModuleSummary { + module_id: module_id.into(), + version: descriptor.version.clone(), + description: descriptor.description.clone(), + tags: descriptor.tags.clone(), + readonly: descriptor.annotations.as_ref().is_some_and(|a| a.readonly), + access_hint: acl, + }, + Arc::clone(module), + descriptor.annotations.clone(), + ) + })?; + let annotations = module.annotations(); + summary.readonly = declared + .as_ref() + .map_or(annotations.readonly, |value| value.readonly); + summary.tags.extend(module.tags()); + summary.tags.sort_unstable(); + summary.tags.dedup(); + let annotations = crate::module::ModuleAnnotations::governance_union( + Some(&annotations), + declared.as_ref(), + ); + let evaluator = self.has_discovery_gate(BuiltinGate::PostValidationPolicy); + let policy = ExecutionPolicy::effective(self.policy.as_deref()); + let approval_enforced = self.has_discovery_gate(BuiltinGate::Approval) + && (policy.strict || self.approval_handler.is_some() || evaluator); + if !approval_enforced { + summary.access_hint = AccessHint::Allowed; + } else if policy + .resolve(module_id, annotations.as_ref()) + .needs_approval + { + summary.access_hint = AccessHint::RequiresApproval; + } + if summary.access_hint == AccessHint::Allowed && evaluator { + summary.access_hint = AccessHint::Conditional; + } + self.registry + .with_discoverable_descriptor(module_id, |descriptor, current| { + (Arc::ptr_eq(current, &module) && descriptor.version == summary.version) + .then_some(summary) + })? + } +} diff --git a/rust/src/client.rs b/rust/src/client.rs index 875ee866..2ffe467c 100644 --- a/rust/src/client.rs +++ b/rust/src/client.rs @@ -651,6 +651,45 @@ impl APCore { ) } + /// Install or remove a provider for capability search. + pub fn set_capability_search_provider( + &self, + provider: Option>, + ) { + self.executor.set_capability_search_provider(provider); + } + + /// List public capability summaries for the supplied caller. + pub fn list_callable( + &self, + context: Option<&Context>, + query: crate::CapabilityQuery, + ) -> Result { + self.executor.list_callable(context, query) + } + + /// Expand selected callable definitions for this caller. + #[must_use] + pub fn get_callable_definitions>( + &self, + module_ids: &[S], + context: Option<&Context>, + ) -> Vec { + self.executor.get_callable_definitions(module_ids, context) + } + + /// Read the current governed descriptor for an adapter projection. + #[must_use] + pub fn get_callable_descriptor( + &self, + module_id: &str, + expected_version: Option<&str>, + context: Option<&Context>, + ) -> Option { + self.executor + .get_callable_descriptor(module_id, expected_version, context) + } + /// Call (execute) a module by ID with the given inputs. /// /// `inputs` accepts either a `serde_json::Value` directly or `None`. diff --git a/rust/src/executor.rs b/rust/src/executor.rs index f5dc68e5..d4ed153c 100644 --- a/rust/src/executor.rs +++ b/rust/src/executor.rs @@ -842,6 +842,7 @@ pub struct Executor { /// (apcore#76 RFC pilot). Flows to the gate via `PipelineContext`. pub policy: Option>, policy_evaluator: Option>, + pub(crate) capability_discovery: crate::capability::DiscoveryState, /// Event emitter for governance events (apcore#77). When set, the ACL and /// approval-gate steps publish `apcore.acl.denied` / /// `apcore.approval.decision` / `apcore.policy.override` on the bus. @@ -980,6 +981,7 @@ impl Executor { approval_handler: None, policy: None, policy_evaluator: None, + capability_discovery: crate::capability::DiscoveryState::default(), event_emitter: None, governance_warned: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())), redaction: std::sync::OnceLock::new(), @@ -1010,6 +1012,7 @@ impl Executor { approval_handler: None, policy: None, policy_evaluator: None, + capability_discovery: crate::capability::DiscoveryState::default(), event_emitter: None, governance_warned: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())), redaction: std::sync::OnceLock::new(), @@ -1036,6 +1039,7 @@ impl Executor { approval_handler: None, policy: None, policy_evaluator: None, + capability_discovery: crate::capability::DiscoveryState::default(), event_emitter: None, governance_warned: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())), redaction: std::sync::OnceLock::new(), @@ -1078,6 +1082,7 @@ impl Executor { approval_handler: approval_handler.map(|h| Arc::from(h) as Arc), policy: None, policy_evaluator: None, + capability_discovery: crate::capability::DiscoveryState::default(), event_emitter: None, governance_warned: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())), redaction: std::sync::OnceLock::new(), diff --git a/rust/src/extensions.rs b/rust/src/extensions.rs index 85bb1c86..2817a3fd 100644 --- a/rust/src/extensions.rs +++ b/rust/src/extensions.rs @@ -60,6 +60,8 @@ pub enum ExtensionKind { ApprovalHandler(Arc), /// Post-validation evaluator for an executor. PolicyEvaluator(Arc), + /// Ranking provider for authorized capability discovery. + CapabilitySearchProvider(Arc), } impl std::fmt::Debug for ExtensionKind { @@ -78,6 +80,9 @@ impl std::fmt::Debug for ExtensionKind { write!(f, "ExtensionKind::ApprovalHandler({h:?})") } ExtensionKind::PolicyEvaluator(_) => write!(f, "ExtensionKind::PolicyEvaluator(...)"), + ExtensionKind::CapabilitySearchProvider(_) => { + write!(f, "ExtensionKind::CapabilitySearchProvider(...)") + } } } } @@ -99,6 +104,9 @@ impl ExtensionKind { ExtensionKind::SpanExporter(e) => std::ptr::from_ref(&**e).cast::<()>(), ExtensionKind::ModuleValidator(v) => std::ptr::from_ref(&**v).cast::<()>(), ExtensionKind::ApprovalHandler(h) => std::ptr::from_ref(&**h).cast::<()>(), + ExtensionKind::CapabilitySearchProvider(provider) => { + std::ptr::from_ref(&**provider).cast::<()>() + } ExtensionKind::PolicyEvaluator(evaluator) => { std::ptr::from_ref(&**evaluator).cast::<()>() } @@ -115,6 +123,7 @@ impl ExtensionKind { ExtensionKind::ModuleValidator(_) => "module_validator", ExtensionKind::ApprovalHandler(_) => "approval_handler", ExtensionKind::PolicyEvaluator(_) => "policy_evaluator", + ExtensionKind::CapabilitySearchProvider(_) => "capability_search_provider", } } } @@ -181,6 +190,14 @@ fn built_in_points() -> HashMap { multiple: false, }, ); + points.insert( + "capability_search_provider".to_string(), + ExtensionPoint { + name: "capability_search_provider".to_string(), + description: "Ranking for authorized capability discovery".to_string(), + multiple: false, + }, + ); points } @@ -190,8 +207,7 @@ fn built_in_points() -> HashMap { /// Manages extension points and their registered implementations. /// -/// Pre-registers six built-in extension points: discoverer, middleware, -/// acl, `span_exporter`, `module_validator`, and `approval_handler`. +/// Pre-registers built-in points for discovery, invocation, and observability. /// /// Extensions are registered as [`ExtensionKind`] variants, ensuring type /// safety at compile time rather than relying on runtime `isinstance` checks @@ -575,6 +591,12 @@ impl ExtensionManager { executor.set_policy_evaluator(Some(Arc::clone(evaluator)))?; } + if let Some(ExtensionKind::CapabilitySearchProvider(provider)) = + self.first_builtin("capability_search_provider") + { + executor.set_capability_search_provider(Some(Arc::clone(provider))); + } + // Discoverer if let Some(ExtensionKind::Discoverer(d)) = self.first_builtin("discoverer") { registry.set_discoverer_shared(Arc::clone(d)); @@ -673,6 +695,7 @@ impl ExtensionManager { "module_validator" => "ModuleValidator", "approval_handler" => "ApprovalHandler", "policy_evaluator" => "PolicyEvaluator", + "capability_search_provider" => "CapabilitySearchProvider", _ => "Unknown", } } @@ -686,7 +709,7 @@ mod tests { fn test_new_has_built_in_points() { let mgr = ExtensionManager::new(); let points = mgr.list_points(); - assert_eq!(points.len(), 7); + assert_eq!(points.len(), 8); let names: Vec = points.iter().map(|p| p.name.clone()).collect(); assert!(names.contains(&"discoverer".to_string())); @@ -696,6 +719,7 @@ mod tests { assert!(names.contains(&"module_validator".to_string())); assert!(names.contains(&"approval_handler".to_string())); assert!(names.contains(&"policy_evaluator".to_string())); + assert!(names.contains(&"capability_search_provider".to_string())); } #[test] @@ -951,7 +975,7 @@ mod tests { #[test] fn test_default_impl() { let mgr = ExtensionManager::default(); - assert_eq!(mgr.list_points().len(), 7); + assert_eq!(mgr.list_points().len(), 8); } #[test] diff --git a/rust/src/lib.rs b/rust/src/lib.rs index f6f8e9f2..8a445a30 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -18,6 +18,7 @@ pub mod async_task; pub mod bindings; pub mod builtin_steps; pub mod cancel; +pub mod capability; pub mod client; pub mod config; pub mod context; @@ -55,6 +56,10 @@ pub use approval::{ AlwaysDenyHandler, ApprovalHandler, ApprovalRequest, ApprovalResult, AutoApproveHandler, CallbackApprovalHandler, }; +pub use capability::{ + AccessHint, CallableDefinition, CapabilityPage, CapabilityQuery, CapabilitySearchProvider, + ModuleSummary, +}; // Note: `async_task::RetryConfig` is re-exported at the crate root as // `AsyncRetryConfig` to avoid colliding with `middleware::RetryConfig`, // mirroring the Python/TypeScript SDKs which both rename-export the same diff --git a/rust/src/pipeline.rs b/rust/src/pipeline.rs index ec69b71a..84cec066 100644 --- a/rust/src/pipeline.rs +++ b/rust/src/pipeline.rs @@ -182,6 +182,12 @@ pub trait Step: Send + Sync + std::any::Any { None } + /// Report toggled availability from the built-in module lookup, if present. + #[doc(hidden)] + fn builtin_module_is_enabled(&self, _module_id: &str) -> Option { + None + } + /// `PipelineContext` fields this step writes (e.g. `["output"]`). Advisory only. fn provides(&self) -> &[&str] { &[] diff --git a/rust/src/pipeline_config.rs b/rust/src/pipeline_config.rs index 168b346f..460809ff 100644 --- a/rust/src/pipeline_config.rs +++ b/rust/src/pipeline_config.rs @@ -126,6 +126,18 @@ impl Step for ConfiguredStep { fn builtin_gate(&self) -> Option { self.inner.builtin_gate() } + fn builtin_module_is_enabled(&self, module_id: &str) -> Option { + self.inner + .builtin_module_is_enabled(module_id) + .map(|enabled| { + enabled + && self.match_modules().is_none_or(|patterns| { + patterns + .iter() + .any(|pattern| crate::utils::helpers::match_pattern(pattern, module_id)) + }) + }) + } fn requires(&self) -> &[&str] { self.inner.requires() } diff --git a/rust/src/registry/registry.rs b/rust/src/registry/registry.rs index 03c101d4..5a266916 100644 --- a/rust/src/registry/registry.rs +++ b/rust/src/registry/registry.rs @@ -1580,6 +1580,25 @@ impl Registry { ModuleAnnotations::governance_union(Some(&module.annotations()), declared.as_ref()) } + /// Read metadata for the active public registration in one locked snapshot. + /// The caller performs authorization and invokes no host logic under this lock. + pub(crate) fn with_discoverable_descriptor( + &self, + name: &str, + read: impl FnOnce(&ModuleDescriptor, &Arc) -> T, + ) -> Option { + let core = self.core.read(); + if core.closed || core.draining.contains(name) || core.unavailable.contains(name) { + return None; + } + let descriptor = core.descriptors.get(name)?; + let module = core.modules.get(name)?; + if !descriptor.enabled || !descriptor_is_discoverable(Some(descriptor)) { + return None; + } + Some(read(descriptor, module)) + } + /// Get the definition (descriptor) for a module by name. /// /// Returns a cloned `ModuleDescriptor` because the underlying storage diff --git a/rust/src/sys_modules/manifest.rs b/rust/src/sys_modules/manifest.rs index 80b56b8f..cb908462 100644 --- a/rust/src/sys_modules/manifest.rs +++ b/rust/src/sys_modules/manifest.rs @@ -363,3 +363,106 @@ impl Module for ManifestFullModule { })) } } + +/// Read-only governed discovery facade. The Executor is resolved from the +/// actual call context, so registry ownership does not form a reference cycle. +pub(crate) struct ManifestSearchModule; + +impl ManifestSearchModule { + pub(crate) const ID: &str = "system.manifest.search"; + + fn originating_frame( + context: &Context, + ) -> Result, ModuleError> { + let mut parent = context.clone(); + if parent.call_chain.last().map(String::as_str) != Some(Self::ID) { + return Err(ModuleError::invalid_input( + "Manifest search requires its invocation context", + )); + } + parent.call_chain.pop(); + parent.caller_id = parent.call_chain.iter().rev().nth(1).cloned(); + Ok(parent) + } +} + +#[async_trait] +impl Module for ManifestSearchModule { + fn description(&self) -> &'static str { + "Find public capabilities visible to the current caller" + } + + fn annotations(&self) -> crate::ModuleAnnotations { + crate::ModuleAnnotations { + readonly: true, + idempotent: true, + open_world: false, + ..Default::default() + } + } + + fn input_schema(&self) -> serde_json::Value { + json!({ + "type": "object", + "additionalProperties": false, + "properties": { + "query": {"type": "string"}, + "prefix": {"type": "string"}, + "tags": {"type": "array", "items": {"type": "string"}, "default": []}, + "readonly": {"type": "boolean"}, + "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}, + "cursor": {"type": "string"}, + "include_approval_required": {"type": "boolean", "default": true} + } + }) + } + + fn output_schema(&self) -> serde_json::Value { + json!({ + "type": "object", + "required": ["items", "next_cursor"], + "additionalProperties": false, + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "required": ["module_id", "version", "description", "tags", "readonly", "access_hint"], + "additionalProperties": false, + "properties": { + "module_id": {"type": "string"}, + "version": {"type": "string"}, + "description": {"type": "string"}, + "tags": {"type": "array", "items": {"type": "string"}}, + "readonly": {"type": "boolean"}, + "access_hint": {"enum": ["allowed", "requires_approval", "conditional"]} + } + } + }, + "next_cursor": {"type": ["string", "null"]} + } + }) + } + + async fn execute( + &self, + inputs: serde_json::Value, + ctx: &Context, + ) -> Result { + let executor = ctx.executor().ok_or_else(|| { + ModuleError::new( + crate::ErrorCode::ConfigInvalid, + "Manifest search requires a shared Executor", + ) + })?; + let parent = Self::originating_frame(ctx)?; + let query = serde_json::from_value(inputs) + .map_err(|_| ModuleError::invalid_input("Invalid capability query"))?; + serde_json::to_value(executor.list_callable(Some(&parent), query)?).map_err(|_| { + ModuleError::new( + crate::ErrorCode::GeneralInternalError, + "Capability summary could not be encoded", + ) + }) + } +} diff --git a/rust/src/sys_modules/mod.rs b/rust/src/sys_modules/mod.rs index 289d4459..574fd89a 100644 --- a/rust/src/sys_modules/mod.rs +++ b/rust/src/sys_modules/mod.rs @@ -812,6 +812,11 @@ pub(crate) fn register_sys_modules_for_client( ), vec!["system".into(), "manifest".into()], ), + ( + manifest::ManifestSearchModule::ID, + Box::new(manifest::ManifestSearchModule), + vec!["system".into(), "manifest".into()], + ), ]); } if usage_enabled { diff --git a/rust/tests/capability_discovery.rs b/rust/tests/capability_discovery.rs new file mode 100644 index 00000000..bb1dfe50 --- /dev/null +++ b/rust/tests/capability_discovery.rs @@ -0,0 +1,355 @@ +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use apcore::{ + CapabilityQuery, CapabilitySearchProvider, Config, Context, Executor, Identity, Module, + ModuleAnnotations, ModuleError, PolicyEvaluationRequest, PolicyEvaluator, PolicyVerdict, + Registry, ACL, +}; +use async_trait::async_trait; +use serde_json::{json, Value}; + +use super::conformance_env; + +struct DiscoveryModule { + annotations: ModuleAnnotations, + description: String, + tags: Vec, +} + +#[async_trait] +impl Module for DiscoveryModule { + fn description(&self) -> &str { + &self.description + } + + fn tags(&self) -> Vec { + self.tags.clone() + } + + fn annotations(&self) -> ModuleAnnotations { + self.annotations.clone() + } + + fn input_schema(&self) -> Value { + schema() + } + + fn output_schema(&self) -> Value { + schema() + } + + async fn execute(&self, _: Value, _: &Context) -> Result { + panic!("discovery must not execute a module") + } +} + +fn schema() -> Value { + json!({"type":"object", "properties":{"message":{"type":"string"}}}) +} + +struct NeverEvaluate; + +#[async_trait] +impl PolicyEvaluator for NeverEvaluate { + async fn evaluate(&self, _: &PolicyEvaluationRequest) -> Result { + panic!("discovery must not call the policy evaluator") + } +} + +fn reader(id: &str, roles: Vec) -> Context { + Context::new(Identity::new( + id.into(), + "user".into(), + roles, + HashMap::new(), + )) +} + +fn register(executor: &Executor, fixture: &Value) { + let module_id = fixture["module_id"].as_str().unwrap(); + let module = Box::new(DiscoveryModule { + annotations: ModuleAnnotations { + discoverable: fixture["discoverable"].as_bool().unwrap_or(true), + readonly: fixture["readonly"].as_bool().unwrap_or(false), + requires_approval: fixture["requires_approval"].as_bool().unwrap_or(false), + ..Default::default() + }, + description: fixture["description"].as_str().unwrap_or("A tool").into(), + tags: serde_json::from_value(fixture.get("tags").cloned().unwrap_or(json!([]))).unwrap(), + }); + executor + .registry() + .register_module(module_id, module) + .unwrap(); +} + +#[test] +fn test_capability_discovery_conformance() { + let fixture_path = conformance_env::find_fixtures_root().join("capability_discovery.json"); + let fixture: Value = serde_json::from_slice(&std::fs::read(fixture_path).unwrap()).unwrap(); + for case in fixture["test_cases"].as_array().unwrap() { + let case_id = case["id"].as_str().unwrap(); + let input = &case["input"]; + let expected = &case["expected"]; + let audit = Arc::new(AtomicUsize::new(0)); + let audit_capture = Arc::clone(&audit); + let mut executor = Executor::new(Registry::new(), Config::default()); + executor.set_acl(ACL::new( + serde_json::from_value(input["rules"].clone()).unwrap(), + "deny", + Some(Arc::new(move |_| { + audit_capture.fetch_add(1, Ordering::Relaxed); + })), + )); + for module in fixture["driver_contract"]["modules"].as_array().unwrap() { + register(&executor, module); + } + if input["policy_evaluator"].as_bool() == Some(true) { + executor + .set_policy_evaluator(Some(Arc::new(NeverEvaluate))) + .unwrap(); + } + let mut context = reader( + "test-user", + serde_json::from_value(input.get("roles").cloned().unwrap_or(json!([]))).unwrap(), + ); + if let Some(caller_id) = input["caller_id"].as_str() { + context.call_chain.push(caller_id.to_owned()); + } + let options = + serde_json::from_value(input.get("options").cloned().unwrap_or(json!({}))).unwrap(); + let page = executor.list_callable(Some(&context), options).unwrap(); + let items: Vec = page + .items + .iter() + .map(|item| { + assert_eq!(item.version, "1.0.0", "{case_id}"); + let encoded = serde_json::to_value(item).unwrap(); + assert!(encoded.get("input_schema").is_none(), "{case_id}"); + assert!(encoded.get("output_schema").is_none(), "{case_id}"); + json!({"module_id": item.module_id, "access_hint": item.access_hint}) + }) + .collect(); + assert_eq!(json!(items), expected["items"], "{case_id}"); + let definitions = executor.get_callable_definitions( + &[ + "demo.hidden", + "demo.echo", + "demo.review", + "demo.unknown", + "demo.echo", + ], + Some(&context), + ); + let names: Vec<_> = definitions + .iter() + .map(|definition| { + assert_eq!(definition.version, "1.0.0", "{case_id}"); + assert_eq!(definition.input_schema, schema(), "{case_id}"); + assert_eq!(definition.output_schema, schema(), "{case_id}"); + &definition.module_id + }) + .collect(); + let expected_names = expected.get("definitions").cloned().unwrap_or_else(|| { + json!(items + .iter() + .map(|item| &item["module_id"]) + .collect::>()) + }); + assert_eq!(json!(names), expected_names, "{case_id}"); + assert_eq!( + json!(audit.load(Ordering::Relaxed)), + expected["audit_entries"], + "{case_id}" + ); + } +} + +struct BroadProvider; + +impl CapabilitySearchProvider for BroadProvider { + fn search(&self, _: Option<&str>, visible_ids: &[String]) -> Vec { + assert_eq!(visible_ids, &["demo.a", "demo.b"]); + vec![ + "demo.hidden".into(), + "demo.disabled".into(), + "demo.b".into(), + "demo.b".into(), + "demo.a".into(), + ] + } +} + +#[test] +fn test_capability_cursor_is_bound_and_rechecks_current_registrations() { + let executor = Executor::new(Registry::new(), Config::default()); + for id in ["demo.a", "demo.b", "demo.disabled"] { + register(&executor, &json!({"module_id": id})); + } + register( + &executor, + &json!({"module_id": "demo.hidden", "discoverable": false}), + ); + executor.registry().disable("demo.disabled").unwrap(); + executor.set_capability_search_provider(Some(Arc::new(BroadProvider))); + let owner = reader("owner", vec!["reader".into()]); + let options = CapabilityQuery { + limit: 1, + ..Default::default() + }; + let first = executor + .list_callable(Some(&owner), options.clone()) + .unwrap(); + assert_eq!(first.items[0].module_id, "demo.b"); + let second = CapabilityQuery { + cursor: first.next_cursor, + ..options + }; + assert!(executor + .list_callable( + Some(&reader("intruder", vec!["reader".into()])), + second.clone() + ) + .is_err()); + assert!(executor + .list_callable( + Some(&reader("owner", vec!["writer".into()])), + second.clone() + ) + .is_err()); + executor.registry().disable("demo.a").unwrap(); + let resumed = executor + .list_callable(Some(&owner), second.clone()) + .unwrap(); + assert_eq!(resumed.items, []); + executor.set_capability_search_provider(None); + assert!(executor.list_callable(Some(&owner), second).is_err()); +} + +#[test] +fn test_capability_descriptors_check_current_version_and_same_version_replacement() { + let executor = Executor::new(Registry::new(), Config::default()); + register( + &executor, + &json!({"module_id": "demo.replace", "description": "old metadata"}), + ); + let old = executor + .get_callable_descriptor("demo.replace", Some("1.0.0"), None) + .unwrap(); + assert_eq!(old.description, "old metadata"); + assert!(executor + .get_callable_descriptor("demo.replace", Some("2.0.0"), None) + .is_none()); + executor.registry().unregister("demo.replace").unwrap(); + register( + &executor, + &json!({"module_id": "demo.replace", "description": "live replacement"}), + ); + let live = executor + .get_callable_descriptor("demo.replace", Some("1.0.0"), None) + .unwrap(); + assert_eq!(live.description, "live replacement"); + assert_eq!(old.description, "old metadata"); +} + +#[cfg(feature = "sys-modules")] +#[tokio::test] +async fn test_manifest_search_uses_the_originating_frame_and_acl() { + let mut config = Config::default(); + config.set("sys_modules.enabled", json!(true)); + let mut executor = Executor::new(Registry::new(), config.clone()); + let rules = serde_json::from_value(json!([ + {"callers": ["worker.reader"], "targets": ["system.manifest.search"], "effect": "allow"}, + {"callers": ["system.manifest.search"], "targets": ["demo.privileged"], "effect": "allow"}, + {"callers": ["worker.reader"], "targets": ["demo.ordinary"], "effect": "allow", + "conditions": {"max_call_depth": 2}} + ])) + .unwrap(); + executor.set_acl(ACL::new(rules, "deny", None)); + register(&executor, &json!({"module_id": "demo.privileged"})); + register(&executor, &json!({"module_id": "demo.ordinary"})); + let client = apcore::APCore::try_start(apcore::APCoreOptions { + executor: Some(executor), + config: Some(config), + ..Default::default() + }) + .unwrap(); + let mut requester = reader("requester", vec![]); + requester.call_chain.push("worker.reader".into()); + let args = json!({"prefix": "demo."}); + let result = client + .call( + "system.manifest.search", + args.clone(), + Some(&requester), + None, + ) + .await + .unwrap(); + assert_eq!(result["items"].as_array().unwrap().len(), 1); + assert_eq!(result["items"][0]["module_id"], "demo.ordinary"); + assert_eq!(result["next_cursor"], Value::Null); + assert!(client + .call( + "system.manifest.search", + json!({"query": null}), + Some(&requester), + None + ) + .await + .is_err()); + assert!(client + .call("system.manifest.search", args, None, None) + .await + .is_err()); +} + +#[test] +fn test_capability_discovery_fails_closed_without_the_stock_gate() { + let mut strategy = apcore::builtin_steps::build_standard_strategy(); + strategy.remove("acl_check").unwrap(); + let executor = Executor::with_strategy(Registry::new(), Config::default(), strategy); + register(&executor, &json!({"module_id": "demo.private"})); + let page = executor + .list_callable(None, CapabilityQuery::default()) + .unwrap(); + assert_eq!(page.items, []); + assert!(executor + .get_callable_descriptor("demo.private", None, None) + .is_none()); +} + +#[test] +fn test_capability_hint_tracks_the_legacy_unguarded_approval_profile() { + let mut executor = Executor::new(Registry::new(), Config::default()); + let mut acl_rule = apcore::ACLRule::new( + vec!["@external".into()], + vec!["demo.approve".into()], + "allow", + ); + acl_rule.approval = Some(apcore::ApprovalRequirement::Required); + executor.set_acl(ACL::new(vec![acl_rule], "deny", None)); + executor.set_policy(Some(apcore::ExecutionPolicy::default().with_strict(false))); + register( + &executor, + &json!({"module_id": "demo.approve", "requires_approval": true}), + ); + + let page = executor + .list_callable(None, CapabilityQuery::default()) + .unwrap(); + assert_eq!(page.items[0].access_hint, apcore::AccessHint::Allowed); + + executor + .set_policy_evaluator(Some(Arc::new(NeverEvaluate))) + .unwrap(); + let page = executor + .list_callable(None, CapabilityQuery::default()) + .unwrap(); + assert_eq!( + page.items[0].access_hint, + apcore::AccessHint::RequiresApproval + ); +} diff --git a/rust/tests/core_profile.rs b/rust/tests/core_profile.rs index 3ee32f2a..8d870cca 100644 --- a/rust/tests/core_profile.rs +++ b/rust/tests/core_profile.rs @@ -12,6 +12,7 @@ use async_trait::async_trait; use futures_util::{stream, StreamExt}; use serde_json::{json, Value}; +mod capability_discovery; #[path = "conformance_env.rs"] mod conformance_env; mod post_validation_policy; diff --git a/rust/tests/test_extensions.rs b/rust/tests/test_extensions.rs index 3589def1..061a942c 100644 --- a/rust/tests/test_extensions.rs +++ b/rust/tests/test_extensions.rs @@ -22,7 +22,7 @@ fn make_acl() -> ExtensionKind { #[test] fn test_new_has_six_built_in_points() { let mgr = ExtensionManager::new(); - assert_eq!(mgr.list_points().len(), 7); + assert_eq!(mgr.list_points().len(), 8); } #[test] @@ -47,7 +47,7 @@ fn test_list_points_contains_all_expected_names() { #[test] fn test_default_equals_new() { let mgr = ExtensionManager::default(); - assert_eq!(mgr.list_points().len(), 7); + assert_eq!(mgr.list_points().len(), 8); } // --------------------------------------------------------------------------- diff --git a/schemas/sys-manifest-search.schema.json b/schemas/sys-manifest-search.schema.json new file mode 100644 index 00000000..5dc2f570 --- /dev/null +++ b/schemas/sys-manifest-search.schema.json @@ -0,0 +1,38 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "system.manifest.search Output", + "description": "Page of active public module summaries authorized for the requesting caller.", + "type": "object", + "additionalProperties": false, + "required": ["items", "next_cursor"], + "properties": { + "items": { + "description": "Visible summaries in result order.", + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["module_id", "version", "description", "tags", "readonly", "access_hint"], + "properties": { + "module_id": {"type": "string", "description": "Canonical module ID."}, + "version": {"type": "string", "description": "Resolved module version."}, + "description": {"type": "string", "description": "Short, plain-text module description."}, + "tags": { + "type": "array", + "description": "Tags declared by the module.", + "items": {"type": "string"} + }, + "readonly": {"type": "boolean", "description": "Whether the module declares read-only behavior."}, + "access_hint": { + "enum": ["allowed", "requires_approval", "conditional"], + "description": "Advisory approval status for the current caller." + } + } + } + }, + "next_cursor": { + "type": ["string", "null"], + "description": "Opaque continuation for the same caller and filters, or null at the end." + } + } +} diff --git a/schemas/sys-modules.schema.json b/schemas/sys-modules.schema.json index 68a89026..b91b254e 100644 --- a/schemas/sys-modules.schema.json +++ b/schemas/sys-modules.schema.json @@ -30,7 +30,7 @@ "properties": { "enabled": { "type": "boolean", - "description": "Whether system.manifest.module and system.manifest.full are registered.", + "description": "Whether system.manifest.module, system.manifest.full, and system.manifest.search are registered.", "default": true } } diff --git a/typescript/apcore-conformance.yaml b/typescript/apcore-conformance.yaml index 7fc0d021..1a67c9a3 100644 --- a/typescript/apcore-conformance.yaml +++ b/typescript/apcore-conformance.yaml @@ -2,7 +2,7 @@ # It does not certify every fixture required by Level 1 or Level 2. implementation: name: apcore-typescript - version: "1.0.0-alpha.3" + version: "1.0.0-alpha.4" language: typescript spec_version: "1.65.0" maintainer: AI Perceivable diff --git a/typescript/package.json b/typescript/package.json index e3a6cbb6..652b93e7 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-js", - "version": "1.0.0-alpha.3", + "version": "1.0.0-alpha.4", "description": "Build once, invoke by code or AI — with schema, ACL, approval, and audit enforced at every call", "type": "module", "main": "./dist/index.js", diff --git a/typescript/src/acl.ts b/typescript/src/acl.ts index 37ab656f..48202453 100644 --- a/typescript/src/acl.ts +++ b/typescript/src/acl.ts @@ -102,6 +102,25 @@ export interface AccessDecision { readonly reason: string; } +/** Authorization proved for discovery without evaluating invocation arguments. */ +export interface VisibilityDecision { + readonly visible: boolean; + readonly approvalRequired: boolean; + readonly approvalConditional: boolean; +} + +const HIDDEN_VISIBILITY: VisibilityDecision = Object.freeze({ + visible: false, approvalRequired: false, approvalConditional: false, +}); + +const visibilityHandlers = new Map([ + ['identity_types', new IdentityTypesHandler()], + ['roles', new RolesHandler()], + ['max_call_depth', new MaxCallDepthHandler()], +]); + +type VisibilityCondition = boolean | 'unknown'; + /** * Per-call inputs to an ACL check beyond caller, target and `Context`. * @@ -1687,6 +1706,84 @@ export class ACL { return decision.access === 'allow' && !decision.approvalRequired; } + /** Prove visibility without auditing, evaluating custom handlers, or assuming input arguments. */ + evaluateVisibility( + callerId: string | null, + targetId: string, + context: Context | null = null, + ): VisibilityDecision { + // An inherited projection cannot describe a host's overridden access policy. + if (this.asyncCheckAccess !== ACL.prototype.asyncCheckAccess) return HIDDEN_VISIBILITY; + const caller = callerId ?? '@external'; + const possibleApprovals = new Set(); + let pendingApproval = false; + for (const rule of this._rules) { + const outcome = this._visibilityRule(rule, caller, targetId, context); + if (outcome === false) continue; + if (rule.effect !== 'allow') return HIDDEN_VISIBILITY; + if (outcome === 'unevaluable') { + pendingApproval ||= ACL._raisesPendingApproval(rule); + continue; + } + possibleApprovals.add(pendingApproval || rule.approval === 'required'); + if (outcome === true) return ACL._visibleApproval(possibleApprovals); + } + if (this._defaultEffect !== 'allow') return HIDDEN_VISIBILITY; + possibleApprovals.add(pendingApproval); + return ACL._visibleApproval(possibleApprovals); + } + + private static _visibleApproval(possibleApprovals: Set): VisibilityDecision { + return { + visible: true, + approvalRequired: !possibleApprovals.has(false), + approvalConditional: possibleApprovals.size > 1, + }; + } + + private _visibilityRule( + rule: ACLRule, callerId: string, targetId: string, context: Context | null, + ): VisibilityCondition | 'unevaluable' { + if (ACL._precheckPatternFields(rule).length > 0) return 'unevaluable'; + if (!this._matchPatterns(rule.callers, callerId, context) || + !this._matchPatterns(rule.targets, targetId, context)) return false; + if (rule.conditions == null) return true; + const faults: RuleFault[] = []; + precheckConditions(rule.conditions, '', 'async', faults); + if (faults.length > 0) return 'unevaluable'; + return context === null ? false : ACL._visibilityConditions(rule.conditions, context); + } + + private static _visibilityConditions(conditions: Record, context: Context): VisibilityCondition { + let uncertain = false; + for (const [key, value] of Object.entries(conditions)) { + const outcome = ACL._visibilityCondition(key, value, context); + if (outcome === false) return false; + if (outcome === 'unknown') uncertain = true; + } + return uncertain ? 'unknown' : true; + } + + private static _visibilityCondition(key: string, value: unknown, context: Context): VisibilityCondition { + const registered = ACL.asyncConditionHandlers.get(key) ?? ACL.conditionHandlers.get(key); + const handler = visibilityHandlers.get(key); + if (handler !== undefined && registered === handler) return handler.evaluate(value, context); + if (key === '$not' && registered === builtinNotHandlerAsync) { + const outcome = ACL._visibilityConditions(value as Record, context); + return outcome === 'unknown' ? outcome : !outcome; + } + if (key === '$or' && registered === builtinOrHandlerAsync) { + let uncertain = false; + for (const branch of value as Record[]) { + const outcome = ACL._visibilityConditions(branch, context); + if (outcome === true) return true; + if (outcome === 'unknown') uncertain = true; + } + return uncertain ? 'unknown' : false; + } + return 'unknown'; + } + /** * The structured decision for a call (PROTOCOL_SPEC §6.8.1) — authorization * and approval requirement as the two independent results §6.1.6 defines. @@ -2309,9 +2406,7 @@ export class ACL { // (`identity_types`, `roles`, `max_call_depth`). Singular aliases // were removed to align with Python (apcore-python commit 2c204fb) // and Rust (apcore-rust src/acl_handlers.rs). -ACL.registerCondition('identity_types', new IdentityTypesHandler()); -ACL.registerCondition('roles', new RolesHandler()); -ACL.registerCondition('max_call_depth', new MaxCallDepthHandler()); +for (const [condition, handler] of visibilityHandlers) ACL.registerCondition(condition, handler); // §6.1.7 — `arguments` is BUILT IN and there is no registration point for it. // It is registered here, with the other built-ins, precisely so that §6.1.4's // precheck covers it for free: `argument:` written for `arguments:` is then an diff --git a/typescript/src/browser/index.ts b/typescript/src/browser/index.ts index 3020b8d3..6d23d5f6 100644 --- a/typescript/src/browser/index.ts +++ b/typescript/src/browser/index.ts @@ -9,6 +9,9 @@ export type { APCoreOptions, APCorePlugin, ModuleOptions } from '../client.js'; export type { DrainAbortedContext, DrainAbortReason, DrainContext, LifecycleError, LifecycleEventFlush, LifecycleModuleReport, LifecycleOperation, LifecycleReport, LifecycleStatus, ShutdownOptions, UnregisterOptions, WatchOptions } from '../lifecycle.js'; export { Executor, REDACTED_VALUE } from '../executor.js'; +export type { + CallableDefinition, CapabilityAccessHint, CapabilityPage, CapabilitySearchOptions, CapabilitySearchProvider, ModuleSummary, +} from '../capability-discovery.js'; export type { StreamCompletion, StreamCompletionReason, StreamExecution, StreamStepOutcome } from '../stream-completion.js'; export { @@ -85,6 +88,7 @@ export type { ConditionOutcome, GovernanceProjection, RuleValidationFinding, + VisibilityDecision, } from '../acl.js'; // ---- Errors -------------------------------------------------------------- diff --git a/typescript/src/builtin-steps.ts b/typescript/src/builtin-steps.ts index e2f6bcf1..3641d93d 100644 --- a/typescript/src/builtin-steps.ts +++ b/typescript/src/builtin-steps.ts @@ -241,6 +241,11 @@ export class BuiltinModuleLookup implements Step { return this._toggleState; } + /** @internal Discovery must use the same registry as module lookup. */ + usesRegistry(registry: Registry): boolean { + return this._registry === registry; + } + async execute(ctx: PipelineContext): Promise { const invocation = policyInvocationOf(ctx); if (invocation) assertPolicyBinding(ctx, invocation); diff --git a/typescript/src/capability-discovery.ts b/typescript/src/capability-discovery.ts new file mode 100644 index 00000000..8c08bd9f --- /dev/null +++ b/typescript/src/capability-discovery.ts @@ -0,0 +1,143 @@ +import type { Context } from './context.js'; +import { InvalidInputError } from './errors.js'; +import { copyPolicyInputs } from './policy-evaluation.js'; +import { uuidV4 } from './utils/uuid.js'; + +/** A governance hint for discovery. Actual invocation still enforces the pipeline. */ +export type CapabilityAccessHint = 'allowed' | 'requires_approval' | 'conditional'; + +export interface ModuleSummary { + readonly moduleId: string; + readonly version: string; + readonly description: string; + readonly tags: readonly string[]; + readonly readonly: boolean; + readonly accessHint: CapabilityAccessHint; +} + +export interface CapabilityPage { + readonly items: readonly ModuleSummary[]; + readonly nextCursor: string | null; +} + +export interface CallableDefinition { + readonly moduleId: string; + readonly version: string; + readonly inputSchema: Record; + readonly outputSchema: Record; +} + +export interface CapabilitySearchOptions { + readonly query?: string; + readonly prefix?: string; + readonly tags?: readonly string[]; + readonly readonly?: boolean; + readonly limit?: number; + readonly cursor?: string | null; + readonly includeApprovalRequired?: boolean; +} + +/** An optional ranker that returns candidate module IDs in rank order. */ +export interface CapabilitySearchProvider { + search(query: string | undefined, candidates: readonly string[]): readonly string[]; +} + +type SearchFilters = Required> & + Pick; + +/** @internal Share filter normalization between paging, rankers, and matching. */ +export function normalizeCapabilitySearch(options: CapabilitySearchOptions): SearchFilters { + const { query = '', prefix = '', tags = [], limit = 20, includeApprovalRequired = true } = options; + if (typeof query !== 'string' || typeof prefix !== 'string') { + throw new InvalidInputError('Capability query and prefix must be strings'); + } + if (!Array.isArray(tags) || tags.some(tag => typeof tag !== 'string')) { + throw new InvalidInputError('Capability tags must be a list of strings'); + } + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { + throw new InvalidInputError('Capability limit must be an integer from 1 to 100'); + } + if (typeof includeApprovalRequired !== 'boolean' || + (options.readonly !== undefined && typeof options.readonly !== 'boolean')) { + throw new InvalidInputError('Capability approval and read-only filters must be booleans'); + } + return { + query: query.trim().toLowerCase(), + prefix, + tags: [...new Set(tags)].sort(), + readonly: options.readonly, + limit, includeApprovalRequired, + }; +} + +/** @internal Apply all mandatory filters after visibility has been established. */ +export function matchesCapability(summary: ModuleSummary, filters: SearchFilters, lexical: boolean): boolean { + if (!summary.moduleId.startsWith(filters.prefix) || + !filters.tags.every(tag => summary.tags.includes(tag)) || + (filters.readonly !== undefined && summary.readonly !== filters.readonly) || + (!filters.includeApprovalRequired && summary.accessHint === 'requires_approval')) return false; + if (!lexical || filters.query === '') return true; + return [summary.moduleId, summary.description, ...summary.tags].some( + value => value.toLowerCase().includes(filters.query), + ); +} + +interface CursorPosition { + readonly candidates: readonly string[]; + readonly offset: number; +} + +interface CursorRecord extends CursorPosition { + readonly binding: string; + readonly expiresAt: number; +} + +const MAX_CURSORS = 1024; +const CURSOR_TTL_MS = 5 * 60 * 1000; + +function invalidCursor(): InvalidInputError { + return new InvalidInputError('Invalid or expired capability cursor'); +} + +function buildCursorBinding(context: Context | null, filters: SearchFilters): string { + const identity = context?.identity; + try { + return copyPolicyInputs('capability discovery', { + principal: identity === null || identity === undefined ? null : { + id: identity.id, type: identity.type, roles: [...new Set(identity.roles)].sort(), attrs: identity.attrs, + }, + callerId: context?.callerId ?? null, + callChain: [...(context?.callChain ?? [])], + filters: { ...filters, readonly: filters.readonly ?? null }, + }).canonical.join(''); + } catch { + throw invalidCursor(); + } +} + +/** @internal Executor-scoped, bounded pagination state containing no module metadata. */ +export class CapabilityCursorStore { + private readonly _records = new Map(); + + clear(): void { + this._records.clear(); + } + + read(cursor: string, context: Context | null, filters: SearchFilters): CursorPosition { + const record = this._records.get(cursor); + if (record === undefined || record.expiresAt <= Date.now() || + record.binding !== buildCursorBinding(context, filters)) throw invalidCursor(); + return record; + } + + issue(position: CursorPosition, context: Context | null, filters: SearchFilters): string { + const binding = buildCursorBinding(context, filters); + const cursor = uuidV4(); + if (this._records.size >= MAX_CURSORS) { + const oldest = this._records.keys().next().value; + if (oldest !== undefined) this._records.delete(oldest); + } + this._records.set(cursor, { ...position, binding, expiresAt: Date.now() + CURSOR_TTL_MS }); + return cursor; + } +} diff --git a/typescript/src/client.ts b/typescript/src/client.ts index bffab9d3..d1e7defb 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -3,6 +3,7 @@ */ import type { ACL } from './acl.js'; +import type { CallableDefinition, CapabilityPage, CapabilitySearchOptions, CapabilitySearchProvider } from './capability-discovery.js'; import type { TSchema } from '@sinclair/typebox'; import type { Config } from './config.js'; import type { Context } from './context.js'; @@ -30,6 +31,7 @@ import type { ModuleAnnotations, ModuleExample, PreflightResult, ResourceLimits import type { MetricsCollector } from './observability/metrics.js'; import type { StreamExecution } from './stream-completion.js'; import { Registry } from './registry/registry.js'; +import type { ModuleDescriptor } from './registry/types.js'; import type { RegisterSysModulesOptions, SysModulesContext } from './sys-modules/registration.js'; import { ToggleState } from './sys-modules/toggle.js'; @@ -82,6 +84,8 @@ export interface APCoreOptions { * policy on that Executor directly (parity with config-driven ACL discovery). */ policy?: ExecutionPolicy; + /** Optional candidate ranker for a client-owned executor. */ + capabilitySearchProvider?: CapabilitySearchProvider; /** Throw on system-module registration failures during startup. Defaults to false. */ failOnError?: boolean; } @@ -185,6 +189,7 @@ export class APCore { toggleState: this._toggleState, // Execution-time governance overrides for the approval gate (apcore#76). policy: options?.policy ?? null, + capabilitySearchProvider: options?.capabilitySearchProvider, }); // Respect ACLs already configured on a supplied Executor. @@ -426,6 +431,26 @@ export class APCore { return this.executor.validate(moduleId, inputs, context); } + listCallable(context: Context | null = null, options: CapabilitySearchOptions = {}): CapabilityPage { + return this.executor.listCallable(context, options); + } + + getCallableDefinitions(moduleIds: readonly string[], context: Context | null = null): CallableDefinition[] { + return this.executor.getCallableDefinitions(moduleIds, context); + } + + getCallableDefinition( + moduleId: string, context: Context | null = null, versionHint: string | null = null, + ): CallableDefinition | null { + return this.executor.getCallableDefinition(moduleId, context, versionHint); + } + + getCallableDescriptor( + moduleId: string, context: Context | null = null, versionHint: string | null = null, + ): ModuleDescriptor | null { + return this.executor.getCallableDescriptor(moduleId, context, versionHint); + } + /** * Get module description info (for AI/LLM use). */ diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index a776ec3c..500fe57f 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -5,20 +5,32 @@ * Timeout uses Promise.race instead of threading. */ -import type { ACL } from './acl.js'; +import type { ACL, VisibilityDecision } from './acl.js'; import { createRedactionReferenceContext, resolveRedactionReference, type RedactionReferenceContext, } from './utils/redaction-references.js'; import { type ApprovalHandler, discardApprovalToken, prepareApprovalInputs, stripApprovalToken } from './approval.js'; -import { DEFAULT_EXECUTION_POLICY, type ExecutionPolicy } from './policy.js'; +import { DEFAULT_EXECUTION_POLICY, ExecutionPolicy } from './policy.js'; +import { + CapabilityCursorStore, + matchesCapability, + normalizeCapabilitySearch, + type CallableDefinition, + type CapabilityAccessHint, + type CapabilityPage, + type CapabilitySearchOptions, + type CapabilitySearchProvider, + type ModuleSummary, +} from './capability-discovery.js'; import { assertPolicyBinding, beginPolicyInvocation, endPolicyInvocation, policyIngressInputs, policyInvocationOf, type PolicyEvaluator, } from './policy-evaluation.js'; import { BuiltinACLCheck, BuiltinApprovalGate, + BuiltinContextCreation, BuiltinModuleLookup, buildInternalStrategy, buildMinimalStrategy, @@ -80,6 +92,8 @@ import { } from './pipeline.js'; import { MAX_MODULE_ID_LENGTH, MODULE_ID_PATTERN } from './registry/registry.js'; import type { Registry } from './registry/registry.js'; +import type { ModuleDescriptor } from './registry/types.js'; +import { matchesVersionHint } from './registry/version.js'; import { createStreamExecution, StreamCompletionTracker, type StreamExecution } from './stream-completion.js'; import { DEFAULT_TOGGLE_STATE, type ToggleState } from './sys-modules/toggle.js'; import { propagateError } from './utils/error-propagation.js'; @@ -90,6 +104,19 @@ export const REDACTED_VALUE: string = '***REDACTED***'; /** Steps whose removal withdraws a protection (PROTOCOL_SPEC §5.16 req 7). */ const SECURITY_STEPS = ['acl_check', 'approval_gate'] as const; +function matchesDiscoveryVersion(version: string, hint: string | null): boolean { + if (hint === null || hint === '') return true; + const requested = hint.trim(); + if (/^=?\d+\.\d+\.\d+(?:[-+][\w.+-]+)?$/.test(requested)) { + return requested.replace(/^=/, '') === version; + } + try { + return matchesVersionHint(version, requested); + } catch { + return false; + } +} + /** The `pipeline:` block of a loaded configuration, or `null`. */ /** * A per-callback identity for the `useBefore` / `useAfter` wrappers. @@ -540,6 +567,8 @@ export class Executor { private _approvalHandler: ApprovalHandler | null; private _policy: ExecutionPolicy | null; private _policyEvaluator: PolicyEvaluator | null = null; + private _capabilitySearchProvider: CapabilitySearchProvider | null = null; + private readonly _capabilityCursors = new CapabilityCursorStore(); private readonly _toggleState: ToggleState; private _eventEmitter: EventEmitter | null; private _eventEmitterConfigured: boolean; @@ -558,6 +587,7 @@ export class Executor { approvalHandler?: ApprovalHandler | null; policy?: ExecutionPolicy | null; policyEvaluator?: PolicyEvaluator | null; + capabilitySearchProvider?: CapabilitySearchProvider | null; toggleState?: ToggleState | null; eventEmitter?: EventEmitter | null; }) { @@ -641,6 +671,7 @@ export class Executor { // reported the gate as configured and wired. this._strategy = this._bindProviders(this._strategy); this.setPolicyEvaluator(options.policyEvaluator ?? null); + this.setCapabilitySearchProvider(options.capabilitySearchProvider ?? null); this._pipelineEngine = new PipelineEngine(); } @@ -775,6 +806,138 @@ export class Executor { ); } + /** + * Summarize currently callable public registrations without executing a module. + * A continuation uses its original ordering and rechecks visibility on each page. + */ + listCallable(context: Context | null = null, options: CapabilitySearchOptions = {}): CapabilityPage { + const filters = normalizeCapabilitySearch(options); + 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 } + : this._capabilityCursors.read(options.cursor, context, filters); + const items: ModuleSummary[] = []; + let nextCursor: string | null = null; + for (let offset = position.offset; offset < position.candidates.length; offset++) { + const summary = this._capabilitySummary(position.candidates[offset], parent); + if (summary === null || !matchesCapability(summary, filters, provider === null)) continue; + if (items.length === filters.limit) { + nextCursor = this._capabilityCursors.issue({ candidates: position.candidates, offset }, context, filters); + break; + } + items.push(summary); + } + return { items, nextCursor }; + } + + /** Return complete schemas for visible IDs, in first-seen request order. */ + getCallableDefinitions(moduleIds: readonly string[], context: Context | null = null): CallableDefinition[] { + if (!Array.isArray(moduleIds) || moduleIds.some(id => typeof id !== 'string')) { + throw new InvalidInputError('Capability module IDs must be a list of strings'); + } + const definitions: CallableDefinition[] = []; + for (const moduleId of new Set(moduleIds)) { + const definition = this.getCallableDefinition(moduleId, context); + if (definition !== null) definitions.push(definition); + } + return definitions; + } + + /** Return complete schemas for one live, visible registration. */ + getCallableDefinition( + moduleId: string, context: Context | null = null, versionHint: string | null = null, + ): CallableDefinition | null { + const descriptor = this.getCallableDescriptor(moduleId, context, versionHint); + if (descriptor === null) return null; + const { version, inputSchema, outputSchema } = descriptor; + return { moduleId, version, inputSchema, outputSchema }; + } + + /** Obtain the authorized live descriptor for a host's protocol projection. */ + getCallableDescriptor( + moduleId: string, context: Context | null = null, versionHint: string | null = null, + ): ModuleDescriptor | null { + const parent = (context ?? Context.create()).withExecutor(this); + const candidate = this._discoverCapability(moduleId, parent); + if (candidate === null) return null; + const descriptor = this._registry.publicDefinition(moduleId, candidate.generation); + return descriptor !== null && matchesDiscoveryVersion(descriptor.version, versionHint) ? descriptor : null; + } + + private _capabilityCandidates( + parent: Context, provider: CapabilitySearchProvider | null, query: string, + ): 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]); + 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)); + } + + private _discoverCapability( + moduleId: string, parent: Context, + ): { generation: object; approvalRequired: boolean; approvalConditional: boolean } | null { + const steps = this._strategy.steps; + const lookup = steps.find(step => step.name === 'module_lookup'); + if (!(lookup instanceof BuiltinModuleLookup) || !lookup.usesRegistry(this._registry) || + lookup.toggleState.isDisabled(moduleId) || + !steps.some(step => step instanceof BuiltinContextCreation)) return null; + const generation = this._registry.publicGeneration(moduleId); + if (generation === null) return null; + const gates = steps.filter(step => step.name === 'acl_check' || step instanceof BuiltinACLCheck); + if (gates.length === 0) return null; + const target = parent.child(moduleId); + let approvalRequired = false; + let approvalConditional = false; + for (const gate of gates) { + if (!(gate instanceof BuiltinACLCheck) || gate.execute !== BuiltinACLCheck.prototype.execute) return null; + if (gate.acl === null) continue; + const result: VisibilityDecision | undefined = gate.acl.evaluateVisibility?.(target.callerId, moduleId, target); + if (result?.visible !== true) return null; + approvalRequired ||= result.approvalRequired; + approvalConditional ||= result.approvalConditional; + } + return this._registry.publicGeneration(moduleId) === generation + ? { generation, approvalRequired, approvalConditional } : null; + } + + private _capabilitySummary(moduleId: string, parent: Context): ModuleSummary | null { + const proof = this._discoverCapability(moduleId, parent); + if (proof === null) return null; + const metadata = this._registry.getModuleMetadata(moduleId); + const annotations = this._registry.getDeclaredAnnotations(moduleId); + const accessHint = this._capabilityAccessHint(moduleId, proof); + return this._registry.publicGeneration(moduleId) === proof.generation ? { + moduleId, + version: typeof metadata.version === 'string' ? metadata.version : '1.0.0', + description: typeof metadata.description === 'string' ? metadata.description : '', + tags: Array.isArray(metadata.tags) ? metadata.tags.filter((tag): tag is string => typeof tag === 'string') : [], + readonly: annotations?.readonly === true, + accessHint, + } : null; + } + + private _capabilityAccessHint( + moduleId: string, proof: Pick, + ): CapabilityAccessHint { + const gate = this._strategy.steps.find((step): step is BuiltinApprovalGate => + Object.getPrototypeOf(step) === BuiltinApprovalGate.prototype && + step.execute === BuiltinApprovalGate.prototype.execute); + const evaluatorActive = this._policyEvaluator !== null; + if (gate !== undefined) { + const enforces = gate.policy.strict || gate.approvalHandler !== null || evaluatorActive; + const knownPolicy = Object.getPrototypeOf(gate.policy) === ExecutionPolicy.prototype && + gate.policy.resolve === ExecutionPolicy.prototype.resolve; + const staticApproval = enforces && knownPolicy && + gate.policy.resolve(moduleId, this._moduleGovernanceAnnotations(moduleId)).needsApproval; + if (enforces && (proof.approvalRequired || staticApproval)) return 'requires_approval'; + if (!knownPolicy || (enforces && proof.approvalConditional)) return 'conditional'; + } + return evaluatorActive ? 'conditional' : 'allowed'; + } + /** * List registered module IDs with an approval declaration the built-in gate would skip. * Use after registration to report the default strategy's approval posture. @@ -980,6 +1143,15 @@ export class Executor { this._policyEvaluator = evaluator; } + /** Install or clear the optional capability ranking extension. */ + setCapabilitySearchProvider(provider: CapabilitySearchProvider | null): void { + if (provider !== null && typeof provider.search !== 'function') { + throw new TypeError('A capability search provider must provide a search method'); + } + this._capabilitySearchProvider = provider; + this._capabilityCursors.clear(); + } + private _strategyForInvocation(strategy = this._strategy): ExecutionStrategy { if (strategy !== this._strategy) strategy = this._bindProviders(strategy); return this._policyEvaluator === null ? strategy : withPostValidationPolicy(strategy, this._policyEvaluator, this._eventEmitter); diff --git a/typescript/src/extensions.ts b/typescript/src/extensions.ts index 96e785ce..54d48881 100644 --- a/typescript/src/extensions.ts +++ b/typescript/src/extensions.ts @@ -8,6 +8,7 @@ import type { ACL } from './acl.js'; import type { ApprovalHandler } from './approval.js'; +import type { CapabilitySearchProvider } from './capability-discovery.js'; import { InvalidInputError } from './errors.js'; import type { Executor } from './executor.js'; import { Middleware } from './middleware/index.js'; @@ -141,6 +142,14 @@ function builtInPoints(): Map { typeof (value as Partial).evaluate === 'function', typeName: 'PolicyEvaluator', }], + ['capability_search_provider', { + name: 'capability_search_provider', + description: 'Ranking provider for currently authorized capability candidates', + multiple: false, + typeCheck: value => typeof value === 'object' && value !== null && + typeof (value as Partial).search === 'function', + typeName: 'CapabilitySearchProvider', + }], ]); } @@ -286,6 +295,9 @@ export class ExtensionManager { const evaluator = this.get('policy_evaluator') as PolicyEvaluator | null; if (evaluator !== null) executor.setPolicyEvaluator(evaluator); + const searchProvider = this.get('capability_search_provider') as CapabilitySearchProvider | null; + if (searchProvider !== null) executor.setCapabilitySearchProvider(searchProvider); + // Middleware for (const mw of this.getAll('middleware')) { executor.use(mw as Middleware); diff --git a/typescript/src/node-api.ts b/typescript/src/node-api.ts index ce6954c0..1658c303 100644 --- a/typescript/src/node-api.ts +++ b/typescript/src/node-api.ts @@ -34,6 +34,9 @@ export { CTX_TRACING_SPANS, } from './executor.js'; export type { StreamCompletion, StreamCompletionReason, StreamExecution, StreamStepOutcome } from './stream-completion.js'; +export type { + CallableDefinition, CapabilityAccessHint, CapabilityPage, CapabilitySearchOptions, CapabilitySearchProvider, ModuleSummary, +} from './capability-discovery.js'; // Module types export { @@ -156,6 +159,7 @@ export type { StreamingModule } from './streaming.js'; export { ACL } from './acl.js'; export type { AccessCheckOptions, + VisibilityDecision, AccessDecision, ACLApproval, ACLRule, diff --git a/typescript/src/registry/registry.ts b/typescript/src/registry/registry.ts index 3c4c41a6..b3a410b4 100644 --- a/typescript/src/registry/registry.ts +++ b/typescript/src/registry/registry.ts @@ -99,6 +99,7 @@ interface DiscoveredRegistration { } interface ExecutionGeneration { + readonly discoveryToken: object; references: number; readonly drainWaiters: Set<() => void>; executions?: Map; @@ -1125,7 +1126,9 @@ export class Registry { } this._inFlight.delete(moduleId); this._modules.set(moduleId, module); - this._executionGenerations.set(moduleId, { references: 0, drainWaiters: new Set() }); + this._executionGenerations.set(moduleId, { + discoveryToken: Object.freeze({}), references: 0, drainWaiters: new Set(), + }); this._moduleMeta.set(moduleId, merged); this._lowercaseMap.set(moduleId.toLowerCase(), moduleId); if (options?.sourceFile !== undefined) this._sourceFiles.set(moduleId, options.sourceFile); @@ -1526,6 +1529,13 @@ export class Registry { return (meta['annotations'] as ModuleAnnotations | null) ?? null; } + /** @internal Read the generation eligible for public discovery without acquiring it. */ + publicGeneration(moduleId: string): object | null { + if (this._shutdown || this._inFlight.has(moduleId) || this._draining.has(moduleId) || + !this._isDiscoverable(moduleId)) return null; + return this._executionGenerations.get(moduleId)?.discoveryToken ?? null; + } + /** Return the module descriptor with detached schemas and metadata records. */ getDefinition(moduleId: string, versionHint?: string | null): ModuleDescriptor | null { // Keep the same invalid-ID error as the instance lookup. @@ -1533,6 +1543,17 @@ export class Registry { throw new ModuleNotFoundError(''); } this._warnIgnoredVersionHint('getDefinition', moduleId, versionHint); + return this._definition(moduleId, true); + } + + /** @internal Build a detached descriptor for a generation authorized by the executor. */ + publicDefinition(moduleId: string, generation: object): ModuleDescriptor | null { + if (this.publicGeneration(moduleId) !== generation) return null; + const definition = this._definition(moduleId, false); + return this.publicGeneration(moduleId) === generation ? definition : null; + } + + private _definition(moduleId: string, warnDeprecated: boolean): ModuleDescriptor | null { const module = this._modules.get(moduleId); if (module == null) return null; // INVARIANT: every registration site (`register`, `registerInternal`, @@ -1558,7 +1579,7 @@ export class Registry { const dep = deprecation as Record; const declared = dep['sunset_date']; sunsetDate = typeof declared === 'string' ? declared : null; - this._warnModuleDeprecated(moduleId, version, dep); + if (warnDeprecated) this._warnModuleDeprecated(moduleId, version, dep); } return snapshotRegistryData({ diff --git a/typescript/src/sys-modules/manifest.ts b/typescript/src/sys-modules/manifest.ts index 0c751cb0..62d0f150 100644 --- a/typescript/src/sys-modules/manifest.ts +++ b/typescript/src/sys-modules/manifest.ts @@ -4,15 +4,97 @@ import type { Registry } from '../registry/registry.js'; import type { Config } from '../config.js'; +import { Context } from '../context.js'; +import type { Executor } from '../executor.js'; import { InvalidInputError, ModuleNotFoundError } from '../errors.js'; import type { ModuleDescriptor } from '../registry/types.js'; import type { ModuleAnnotations } from '../module.js'; -import { annotationsToJSON } from '../module.js'; +import { annotationsToJSON, createAnnotations } from '../module.js'; import { governanceUnion } from '../schema/annotations.js'; /** D-110: the project name reported when `project.name` is not configured. */ const DEFAULT_PROJECT_NAME = 'apcore'; +/** Expose a page of summaries under the original trusted caller's ACL. */ +export class ManifestSearchModule { + static readonly moduleId = 'system.manifest.search'; + + readonly description = 'Search public modules visible to the requesting caller'; + readonly annotations = createAnnotations({ readonly: true, idempotent: true, openWorld: false }); + readonly inputSchema = { + type: 'object', + additionalProperties: false, + properties: { + query: { type: 'string', description: 'Text matched against module names, descriptions, and tags' }, + prefix: { type: 'string', description: 'Filter by canonical module ID prefix' }, + tags: { type: 'array', items: { type: 'string' }, description: 'Filter by all of the supplied tags' }, + readonly: { type: 'boolean', description: 'Filter by the read-only annotation' }, + limit: { type: 'integer', minimum: 1, maximum: 100, default: 20, description: 'Maximum summaries to return' }, + cursor: { type: 'string', description: 'Opaque continuation for the same caller and filters' }, + include_approval_required: { type: 'boolean', default: true, description: 'Include modules that require approval' }, + }, + }; + readonly outputSchema = { + type: 'object', + additionalProperties: false, + required: ['items', 'next_cursor'], + properties: { + items: { + description: 'Visible summaries in result order.', + type: 'array', + items: { + type: 'object', + additionalProperties: false, + required: ['module_id', 'version', 'description', 'tags', 'readonly', 'access_hint'], + properties: { + module_id: { type: 'string', description: 'Canonical module ID.' }, + version: { type: 'string', description: 'Resolved module version.' }, + description: { type: 'string', description: 'Short, plain-text module description.' }, + tags: { type: 'array', description: 'Tags declared by the module.', items: { type: 'string' } }, + readonly: { type: 'boolean', description: 'Whether the module declares read-only behavior.' }, + access_hint: { + enum: ['allowed', 'requires_approval', 'conditional'], + description: 'Advisory approval status for the current caller.', + }, + }, + }, + }, + next_cursor: { + type: ['string', 'null'], + description: 'Opaque continuation for the same caller and filters, or null at the end.', + }, + }, + }; + + constructor(private readonly _executor: Executor) {} + + execute(inputs: Record, context: Context): Record { + if (context.callChain.at(-1) !== ManifestSearchModule.moduleId) { + throw new InvalidInputError('Manifest search requires an invocation context'); + } + const callChain = context.callChain.slice(0, -1); + const parent = new Context( + context.traceId, callChain.at(-2) ?? null, callChain, context.executor, context.identity, + null, context.data, context.cancelToken, context.services, context.globalDeadline, + ); + const page = this._executor.listCallable(parent, { + query: inputs.query as string | undefined, + prefix: inputs.prefix as string | undefined, + tags: inputs.tags as string[] | undefined, + readonly: inputs.readonly as boolean | undefined, + limit: inputs.limit as number | undefined, + cursor: inputs.cursor as string | null | undefined, + includeApprovalRequired: inputs.include_approval_required as boolean | undefined, + }); + return { + items: page.items.map(({ moduleId, accessHint, ...item }) => ({ + ...item, module_id: moduleId, access_hint: accessHint, + })), + next_cursor: page.nextCursor, + }; + } +} + /** * SYS-5: emit `annotations` in the snake_case WIRE shape. * diff --git a/typescript/src/sys-modules/registration.ts b/typescript/src/sys-modules/registration.ts index 0f4484a3..4fe51fe3 100644 --- a/typescript/src/sys-modules/registration.ts +++ b/typescript/src/sys-modules/registration.ts @@ -22,7 +22,7 @@ import type { RetryConfig } from '../events/retry.js'; import { CircuitBreakerWrapper } from '../events/circuit-breaker.js'; import { PlatformNotifyMiddleware } from '../middleware/platform-notify.js'; import { HealthSummaryModule, HealthModule } from './health.js'; -import { ManifestFullModule, ManifestModule } from './manifest.js'; +import { ManifestFullModule, ManifestModule, ManifestSearchModule } from './manifest.js'; import { ToggleFeatureModule, DEFAULT_TOGGLE_STATE } from './toggle.js'; import type { ToggleState } from './toggle.js'; import { UpdateConfigModule, ReloadModule } from './control.js'; @@ -480,6 +480,7 @@ export function registerSysModules( if (_cfgGet(sysCfg, config, 'manifest.enabled', true)) { reg('system.manifest.module', new ManifestModule(registry, config)); reg('system.manifest.full', new ManifestFullModule(registry, config)); + reg(ManifestSearchModule.moduleId, new ManifestSearchModule(executor)); } if (_cfgGet(sysCfg, config, 'usage.enabled', true)) { diff --git a/typescript/tests/test-capability-discovery.test.ts b/typescript/tests/test-capability-discovery.test.ts new file mode 100644 index 00000000..65f5d850 --- /dev/null +++ b/typescript/tests/test-capability-discovery.test.ts @@ -0,0 +1,216 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it, vi } from 'vitest'; +import { + ACL, APCore, Context, ExecutionPolicy, Executor, Registry, createAnnotations, createIdentity, + type ACLRule, type CapabilitySearchOptions, +} from '../src/index.js'; +import { Config, ExtensionManager, registerSysModules } from '../src/full.js'; +import { findFixturesRoot } from './spec-repo.js'; + +interface DiscoveryCase { + id: string; + input: { + rules: Array>; + roles?: string[]; + caller_id?: string; + policy_evaluator?: boolean; + options?: { include_approval_required?: boolean; query?: string; tags?: string[]; prefix?: string }; + }; + expected: { + items: Array<{ module_id: string; access_hint: string }>; + definitions?: string[]; + audit_entries: number; + }; +} + +const fixture = JSON.parse(readFileSync(join(findFixturesRoot(), 'capability_discovery.json'), 'utf8')) as { + driver_contract: { + modules: Array<{ + module_id: string; description: string; tags?: string[]; readonly?: boolean; + discoverable?: boolean; requires_approval?: boolean; + }>; + }; + test_cases: DiscoveryCase[]; +}; + +const inputSchema = { + type: 'object', properties: { message: { type: 'string' } }, required: ['message'], +}; +const outputSchema = { type: 'object' }; + +async function fixtureRegistry(): Promise<{ registry: Registry; execute: ReturnType }> { + const registry = new Registry(); + const execute = vi.fn(async () => ({})); + for (const module of fixture.driver_contract.modules) { + await registry.register(module.module_id, { + inputSchema, outputSchema, description: module.description, + tags: module.tags ?? [], + annotations: createAnnotations({ + discoverable: module.discoverable ?? true, + readonly: module.readonly ?? false, + requiresApproval: module.requires_approval ?? false, + }), + execute, + }, '1.0.0'); + } + return { registry, execute }; +} + +function requester(roles: string[] = [], id = 'reader', attrs = {}): Context { + return Context.create(createIdentity(id, 'user', roles, attrs)); +} + +describe('capability_discovery.json', () => { + it.each(fixture.test_cases)('$id', async ({ input, expected }) => { + const { registry, execute } = await fixtureRegistry(); + const audit = vi.fn(); + const evaluate = vi.fn(async () => ({ decision: 'allow' as const })); + const acl = new ACL(input.rules.map(rule => ({ description: '', ...rule })), 'deny', audit); + const executor = new Executor({ + registry, acl, policyEvaluator: input.policy_evaluator ? { evaluate } : undefined, + }); + const base = requester(input.roles); + const context = input.caller_id ? base.child(input.caller_id) : base; + const options: CapabilitySearchOptions = { + ...input.options, includeApprovalRequired: input.options?.include_approval_required, + }; + const page = executor.listCallable(context, options); + expect(page.items.map(({ moduleId, accessHint }) => ({ + module_id: moduleId, access_hint: accessHint, + }))).toEqual(expected.items); + for (const summary of page.items) { + expect(summary).not.toHaveProperty('inputSchema'); + expect(summary).not.toHaveProperty('outputSchema'); + } + const definitions = executor.getCallableDefinitions([ + 'demo.hidden', 'demo.echo', 'demo.review', 'demo.unknown', 'demo.echo', + ], context); + expect(definitions.map(row => row.moduleId)).toEqual( + expected.definitions ?? expected.items.map(row => row.module_id).sort(), + ); + for (const definition of definitions) { + expect(definition).toMatchObject({ version: '1.0.0', inputSchema, outputSchema }); + } + expect(audit).toHaveBeenCalledTimes(expected.audit_entries); + expect(execute).not.toHaveBeenCalled(); + expect(evaluate).not.toHaveBeenCalled(); + }); +}); + +describe('capability discovery lifecycle and identity', () => { + it('reports approval only when the active gate enforces it', async () => { + const { registry } = await fixtureRegistry(); + const policy = new ExecutionPolicy(null, { strict: false }); + const executor = new Executor({ registry, policy }); + const context = requester(); + + expect(executor.listCallable(context).items.map(item => item.accessHint)).toEqual(['allowed', 'allowed']); + await expect(executor.call('demo.review', { message: 'test' }, context)).resolves.toEqual({}); + + const evaluate = vi.fn(async () => ({ decision: 'allow' as const })); + executor.setPolicyEvaluator({ evaluate }); + expect(executor.listCallable(context).items.map(item => item.accessHint)).toEqual([ + 'conditional', 'requires_approval', + ]); + expect(evaluate).not.toHaveBeenCalled(); + + const withoutGate = new Executor({ registry }); + withoutGate.currentStrategy.remove('approval_gate'); + expect(withoutGate.listCallable(context).items.map(item => item.accessHint)).toEqual(['allowed', 'allowed']); + }); + + it('withholds discovery when the active strategy has no built-in ACL gate', async () => { + const { registry } = await fixtureRegistry(); + const executor = new Executor({ registry, strategy: 'minimal' }); + expect(executor.listCallable(requester()).items).toEqual([]); + expect(executor.getCallableDefinition('demo.echo', requester())).toBeNull(); + }); + + it('scopes a continuation to principal, attrs, roles, parent frame, executor and filters', async () => { + const { registry } = await fixtureRegistry(); + const client = new APCore({ registry }); + const context = requester(['reader'], 'user', { team: 'east' }); + const page = client.listCallable(context, { query: ' message ', limit: 1 }); + expect(page.items.map(item => item.moduleId)).toEqual(['demo.echo']); + const options = { query: 'message', limit: 1, cursor: page.nextCursor! }; + expect(options.cursor).toEqual(expect.any(String)); + expect(client.listCallable(context, options).items.map(item => item.moduleId)).toEqual(['demo.review']); + const badContexts = [ + requester(['reader'], 'another', { team: 'east' }), + requester(['reader'], 'user', { team: 'west' }), + requester(['writer'], 'user', { team: 'east' }), + context.child('other.parent'), + ]; + for (const invalid of badContexts) { + expect(() => client.listCallable(invalid, options)).toThrow(/cursor/i); + } + expect(() => client.listCallable(context, { ...options, prefix: 'demo.' })).toThrow(/cursor/i); + expect(() => new APCore({ registry }).listCallable(context, options)).toThrow(/cursor/i); + }); + + it('filters revoked, inactive and unknown candidates on every request and returns detached definitions', async () => { + const { registry } = await fixtureRegistry(); + const search = vi.fn(() => ['demo.hidden', 'demo.echo', 'demo.review', 'demo.unknown', 'demo.echo']); + const acl = new ACL([{ callers: ['@external'], targets: ['demo.*'], effect: 'allow', description: '' }]); + const executor = new Executor({ registry, acl }); + const extensions = new ExtensionManager(); + extensions.register('capability_search_provider', { search }); + extensions.apply(registry, executor); + const first = executor.listCallable(requester(), { limit: 1 }); + expect(first.items.map(item => item.moduleId)).toEqual(['demo.echo']); + expect(search).toHaveBeenCalledTimes(1); + expect(search).toHaveBeenCalledWith(undefined, ['demo.echo', 'demo.review']); + expect(executor.getCallableDefinition('demo.echo', requester(), '2.0.0')).toBeNull(); + const current = executor.getCallableDefinition('demo.echo', requester(), '1.0.0'); + expect(current?.inputSchema).toEqual(inputSchema); + delete current!.inputSchema['properties']; + expect(executor.getCallableDefinition('demo.echo', requester())?.inputSchema).toEqual(inputSchema); + executor.toggleState.disable('demo.review'); + expect(executor.listCallable(requester(), { limit: 1, cursor: first.nextCursor! }).items).toEqual([]); + expect(executor.getCallableDefinition('demo.review', requester())).toBeNull(); + }); + + 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); + ACL.registerAsyncCondition('discovery-test-custom', { evaluate }); + const broad = { callers: ['@external'], targets: ['demo.*'], effect: 'allow', description: '' }; + const acl = new ACL([{ + ...broad, targets: ['demo.review'], effect: 'deny', conditions: { 'discovery-test-custom': true }, + }, broad]); + const search = vi.fn(() => { + acl.removeRule(broad.callers, broad.targets); + return ['demo.echo', 'demo.review']; + }); + const executor = new Executor({ registry, acl, capabilitySearchProvider: { search } }); + expect(executor.listCallable(requester()).items).toEqual([]); + expect(search).toHaveBeenCalledWith(undefined, ['demo.echo']); + expect(evaluate).not.toHaveBeenCalled(); + }); +}); + +it('authorizes a manifest query on its own ACL and uses only the originating caller for visibility', async () => { + const { registry } = await fixtureRegistry(); + const acl = new ACL([ + { callers: ['@external'], targets: ['system.manifest.search', 'demo.echo'], effect: 'allow', description: '' }, + { callers: ['system.manifest.search'], targets: ['demo.review'], effect: 'allow', description: '' }, + ]); + const executor = new Executor({ registry, acl }); + const config = Config.fromDefaults(); + config.set('sys_modules.enabled', true); + registerSysModules(registry, executor, config); + const canonical = JSON.parse(readFileSync( + join(findFixturesRoot(), '..', '..', 'schemas', 'sys-manifest-search.schema.json'), 'utf8', + )) as Record; + expect(registry.getDefinition('system.manifest.search')?.outputSchema).toEqual({ + type: canonical.type, additionalProperties: canonical.additionalProperties, + required: canonical.required, properties: canonical.properties, + }); + const result = await executor.call('system.manifest.search', { prefix: 'demo.' }, requester()); + expect(result).toMatchObject({ items: [{ module_id: 'demo.echo', access_hint: 'allowed' }], next_cursor: null }); + await expect(executor.call('system.manifest.search', { cursor: null }, requester())).rejects.toMatchObject({ + code: 'SCHEMA_VALIDATION_ERROR', + }); + expect(registry.getDefinition('system.manifest.full')).not.toBeNull(); +}); diff --git a/typescript/tests/test-extensions.test.ts b/typescript/tests/test-extensions.test.ts index 34ddd7f3..ad2c6dcf 100644 --- a/typescript/tests/test-extensions.test.ts +++ b/typescript/tests/test-extensions.test.ts @@ -40,16 +40,19 @@ class StubExporter implements SpanExporter { // --------------------------------------------------------------------------- describe('ExtensionManager init', () => { - it('has seven built-in extension points', () => { + it('has eight built-in extension points', () => { const mgr = new ExtensionManager(); const points = mgr.listPoints(); - expect(points).toHaveLength(7); + expect(points).toHaveLength(8); }); it('built-in point names match expected set', () => { const mgr = new ExtensionManager(); const names = new Set(mgr.listPoints().map((p: ExtensionPoint) => p.name)); - expect(names).toEqual(new Set(['discoverer', 'middleware', 'acl', 'span_exporter', 'module_validator', 'approval_handler', 'policy_evaluator'])); + expect(names).toEqual(new Set([ + 'discoverer', 'middleware', 'acl', 'span_exporter', 'module_validator', + 'approval_handler', 'policy_evaluator', 'capability_search_provider', + ])); }); it('listPoints returns ExtensionPoint objects', () => { diff --git a/typescript/tests/test-registration.test.ts b/typescript/tests/test-registration.test.ts index b31d1ef7..d51f9651 100644 --- a/typescript/tests/test-registration.test.ts +++ b/typescript/tests/test-registration.test.ts @@ -40,6 +40,7 @@ describe('registerSysModules', () => { registerSysModules(registry, executor, config); expect(registry.has('system.manifest.module')).toBe(true); expect(registry.has('system.manifest.full')).toBe(true); + expect(registry.has('system.manifest.search')).toBe(true); }); it('registers usage modules when enabled', () => { @@ -279,11 +280,11 @@ describe('sys_modules activation is opt-in in namespace mode (sync finding B-012 expect(registry.moduleIds).toEqual([]); }); - it('registers the six read modules when explicitly enabled', () => { + it('registers the seven read modules when explicitly enabled', () => { const cfg = loadNamespaceConfig('apcore:\n version: "1.0.0"\nsys_modules:\n enabled: true\n'); const registry = new Registry(); registerSysModules(registry, new Executor({ registry }), cfg); - expect(registry.moduleIds).toHaveLength(6); + expect(registry.moduleIds).toHaveLength(7); expect(registry.moduleIds.some((id) => id.startsWith('system.control.'))).toBe(false); }); @@ -293,7 +294,7 @@ describe('sys_modules activation is opt-in in namespace mode (sync finding B-012 ); const registry = new Registry(); registerSysModules(registry, new Executor({ registry }), cfg); - expect(registry.moduleIds).toHaveLength(9); + expect(registry.moduleIds).toHaveLength(10); expect(registry.moduleIds.filter((id) => id.startsWith('system.control.'))).toHaveLength(3); }); }); From 5df01b526638efc6859b1721cfadc6c36ed62249 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 02:31:30 +0800 Subject: [PATCH 3/5] docs(planning): record alpha.4 dual-repository verification Signed-off-by: tercel --- planning/capability-discovery/overview.md | 28 +++++++++++- planning/capability-discovery/state.json | 45 ++++++++++++------- .../capability-discovery/tasks/core-sdks.md | 2 +- .../tasks/shared-contract.md | 2 +- .../capability-discovery/tasks/surfaces.md | 2 +- 5 files changed, 59 insertions(+), 20 deletions(-) diff --git a/planning/capability-discovery/overview.md b/planning/capability-discovery/overview.md index 4d93dd69..bbf09002 100644 --- a/planning/capability-discovery/overview.md +++ b/planning/capability-discovery/overview.md @@ -4,13 +4,13 @@ Gap 3 follows the merged post-validation policy milestone. The Core base is `0da The milestone lets a trusted caller discover public modules that it is authorized to know about. Core owns the visibility decision, summaries, expansion, and pagination. MCP applies the same visibility decision to the modules it already exports and preserves complete `inputSchema` values on standard `tools/list`. -The [implementation plan](./plan.md) records the proposed contract. The maintainers review and approve changes to the normative protocol specification before it is edited. The target is draft revision 3 on the current protocol version line. +The [implementation plan](./plan.md) records the accepted design. The protocol specification records draft revision 3 on the current protocol version line. The merged baseline passed targeted ACL and system manifest checks in all three SDKs. Python passed 349 tests with 3 skips, TypeScript passed 71 tests, and Rust passed 326 tests with 1 ignored test. These runs verify the existing invocation and manifest behavior that discovery must preserve. ## Acceptance -- The same shared cases run through Python, TypeScript, and Rust. They cover hidden and inactive modules, caller-sensitive ACL, deferred decisions, approval hints, and cursor isolation. +- Shared cases and SDK-specific regressions run through Python, TypeScript, and Rust. They cover hidden and inactive modules, caller-sensitive ACL, deferred decisions, approval hints, and cursor isolation. - MCP client tests compare listing and execution for different authenticated identities and verify that listed tools retain the existing full input schema. - Core Profile and full SDK checks pass. Surfaces verify against the candidate wheel, npm tarball, and Rust crate and preserve declared stable minimum compatibility where applicable. @@ -20,3 +20,27 @@ The merged baseline passed targeted ACL and system manifest checks in all three 2. [Core SDKs](./tasks/core-sdks.md) 3. [MCP surfaces](./tasks/surfaces.md) 4. [Dual-repository verification](./tasks/verification.md) + +## Verification results + +The candidate Core distributions were built from `de0c797760796daeefc1ba70d1e44263ea6519f1` and tested against Surfaces commit `a6ac98c61f5ff44e9ae92e5056d218161f9d9e61`. The local candidate branches retain the corresponding source and lockfiles. + +| Gate | Python | TypeScript | Rust | +| --- | ---: | ---: | ---: | +| Core full suite | 6,706 passed | 5,907 passed | 3,254 passed | +| Toolkit with installed Core | 1,289 passed | 1,079 passed | 714 passed | +| MCP with installed Core | 1,281 passed | 997 passed | 1,155 passed | +| A2A with installed Core | 522 passed | 492 passed | 242 passed | +| CLI with installed Core | 1,098 passed | 950 passed | 1,052 passed | +| Toolkit with stable minimum Core | 1,289 passed | 1,079 passed | 714 passed | + +All three SDKs drive the 14 shared discovery cases. The repository inventory validates 100 fixtures and 1,252 cases. Rust 1.86 passed the 18-case minimal Core Profile. The isolated Python wheel and TypeScript browser-entry checks confirm discovery is available from the minimal package. Core and MCP strict documentation builds pass. + +Real MCP client tests cover authenticated role isolation, complete input schemas, document listing and direct reads, actual invocation enforcement, and redaction after a same-version replacement. Python's direct and MCP Golden Path passed with both wheels installed. + +| Core candidate artifact | SHA-256 | +| --- | --- | +| Python wheel | `a016417e8260d4d256a362415361a6afb7cfad8871a1f71abecda48e008814e1` | +| Python source distribution | `d6aad0217860162de84451f2f6ad369c4cb6f3804a8e49929839e868717af64e` | +| npm tarball | `1acc4775d2ec6c8006f5aca264d16d4c2fa9327f5f3ee7af28984109c41d7ed1` | +| Rust crate | `412082f3f58f5a59165f20e1df00f7191b5e382ea59f2369eb486f963cb7d604` | diff --git a/planning/capability-discovery/state.json b/planning/capability-discovery/state.json index f78eb00b..7cee2cab 100644 --- a/planning/capability-discovery/state.json +++ b/planning/capability-discovery/state.json @@ -1,45 +1,60 @@ { "feature": "capability-discovery", "created": "2026-11-27", - "updated": "2026-11-27", - "status": "in_progress", - "execution_order": ["shared-contract", "core-sdks", "surfaces", "verification"], + "updated": "2026-11-28", + "status": "completed", + "execution_order": [ + "shared-contract", + "core-sdks", + "surfaces", + "verification" + ], "progress": { "total_tasks": 4, - "completed": 0, + "completed": 4, "in_progress": 0, - "pending": 3, + "pending": 0, "skipped": 0, - "blocked": 1 + "blocked": 0 }, "tasks": [ { "id": "shared-contract", "file": "tasks/shared-contract.md", "title": "Shared contract and conformance", - "status": "blocked", - "blocker": "Maintainer approval for the proposed draft revision" + "status": "completed" }, { "id": "core-sdks", "file": "tasks/core-sdks.md", "title": "Python, TypeScript, and Rust discovery APIs", - "status": "pending", - "dependencies": ["shared-contract"] + "status": "completed", + "dependencies": [ + "shared-contract" + ] }, { "id": "surfaces", "file": "tasks/surfaces.md", "title": "MCP discovery projection", - "status": "pending", - "dependencies": ["core-sdks"] + "status": "completed", + "dependencies": [ + "core-sdks" + ] }, { "id": "verification", "file": "tasks/verification.md", "title": "Dual-repository verification", - "status": "pending", - "dependencies": ["core-sdks", "surfaces"] + "status": "completed", + "dependencies": [ + "core-sdks", + "surfaces" + ] } - ] + ], + "metadata": { + "core_commit": "de0c797760796daeefc1ba70d1e44263ea6519f1", + "surfaces_commit": "a6ac98c61f5ff44e9ae92e5056d218161f9d9e61" + } } diff --git a/planning/capability-discovery/tasks/core-sdks.md b/planning/capability-discovery/tasks/core-sdks.md index 69e2adc1..72ca3cd0 100644 --- a/planning/capability-discovery/tasks/core-sdks.md +++ b/planning/capability-discovery/tasks/core-sdks.md @@ -1,6 +1,6 @@ # Core SDK Implementation -The Python, TypeScript, and Rust implementations can proceed in parallel after the shared contract is approved. Each owns its SDK and conformance driver. Use the active built-in pipeline gate lookup and existing effective annotation and approval policy logic. Reuse the registry's registration generation and version resolution to guard the metadata view across asynchronous boundaries. +The Python, TypeScript, and Rust implementations and conformance drivers were verified independently. Each owns its SDK and conformance driver. Use the active built-in pipeline gate lookup and existing effective annotation and approval policy logic. Reuse the registry's registration generation and version resolution to guard the metadata view across asynchronous boundaries. 1. Add failing public-entry tests from the shared cases. Show that hidden entries stay hidden and single-ID expansion is equally protected. Assert that discovery leaves audit, error history, approval, evaluator, and module callback counters untouched. 2. Add the silent visibility branch at the ACL decision layer. Preserve existing call-path auditing and first-match semantics. Exercise policies with argument-dependent and custom rules without synthesizing request arguments. diff --git a/planning/capability-discovery/tasks/shared-contract.md b/planning/capability-discovery/tasks/shared-contract.md index 65560f66..52f6a8a4 100644 --- a/planning/capability-discovery/tasks/shared-contract.md +++ b/planning/capability-discovery/tasks/shared-contract.md @@ -1,6 +1,6 @@ # Shared Contract and Conformance -Approval is pending for the Gap 3 protocol changes. Amend the draft protocol only after maintainer approval. Keep version 2.0.0 and update the draft revision, revision history, changelog, and decision register together. Retain existing anchors and the source of truth for manifest schemas. +The approved contract is recorded in the protocol draft revision, revision history, changelog, decision register, and shared fixtures. Existing management manifest anchors and schemas remain available. Use the existing root conformance format and inventory checks. Define cases for an authenticated role grant and denial, an unavailable argument or custom condition, compound conditions, an uncertain deny overriding a later grant, a definite human approval requirement, a conditional approval, and a configured final-input evaluator. Include names that are hidden, inactive, absent, moved to a new generation, and injected by a search provider. diff --git a/planning/capability-discovery/tasks/surfaces.md b/planning/capability-discovery/tasks/surfaces.md index 7be11a82..457f8a08 100644 --- a/planning/capability-discovery/tasks/surfaces.md +++ b/planning/capability-discovery/tasks/surfaces.md @@ -1,6 +1,6 @@ # MCP discovery projection -Pending maintainer approval of the [shared discovery contract](./shared-contract.md). The Core SDK discovery APIs are a prerequisite for this task. +Verified against the [shared discovery contract](./shared-contract.md) and the installed candidate SDK distributions. ## Implementation From c6d9283c874f063d0296f4df7ba9430ccb6a2e6a Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 08:10:24 +0800 Subject: [PATCH 4/5] fix(discovery): match the active pipeline before disclosing modules Signed-off-by: tercel --- python/src/apcore/capabilities.py | 24 +++-- python/tests/test_capability_discovery.py | 59 +++++++++++- rust/src/capability.rs | 45 ++++++++- rust/src/pipeline_config.rs | 20 +++- rust/tests/capability_discovery.rs | 37 ++++++++ typescript/src/executor.ts | 18 +++- typescript/src/pipeline.ts | 35 +++---- .../tests/test-capability-discovery.test.ts | 95 +++++++++++++++++++ 8 files changed, 299 insertions(+), 34 deletions(-) diff --git a/python/src/apcore/capabilities.py b/python/src/apcore/capabilities.py index 49a6ac27..5b897b70 100644 --- a/python/src/apcore/capabilities.py +++ b/python/src/apcore/capabilities.py @@ -13,9 +13,10 @@ from apcore._post_validation_policy import _argument_digest from apcore.acl import ACL, VisibilityDecision -from apcore.builtin_steps import BuiltinACLCheck, BuiltinApprovalGate, BuiltinModuleLookup +from apcore.builtin_steps import BuiltinACLCheck, BuiltinApprovalGate, BuiltinContextCreation, BuiltinModuleLookup from apcore.context import Context, Identity from apcore.errors import InvalidInputError, PolicyEvaluationError +from apcore.pipeline import _any_match from apcore.policy import ExecutionPolicy from apcore.schema.annotations import governance_union @@ -310,16 +311,27 @@ def descriptor( def _visible( executor: Executor, module_id: str, context: Context, version_hint: str | None ) -> tuple[_Registration, VisibilityDecision] | None: - steps = executor.current_strategy.steps - lookup = next((step for step in steps if type(step) is BuiltinModuleLookup), None) + context_ready = False + lookup = None + gate = None + for step in executor.current_strategy.steps: + patterns = getattr(step, "match_modules", None) + if patterns is not None and not _any_match(patterns, module_id): + continue + if type(step) is BuiltinContextCreation: + context_ready = True + elif type(step) is BuiltinModuleLookup: + lookup = step + elif type(step) is BuiltinACLCheck: + gate = step + break + if not context_ready or gate is None: + return None if lookup is None or lookup._registry is not executor.registry or lookup.toggle_state.is_disabled(module_id): return None selected = executor.registry._discovery_registration(module_id, version_hint) if selected is None: return None - gate = next((step for step in steps if type(step) is BuiltinACLCheck), None) - if gate is None: - return None access = _visibility_decision(gate.acl, module_id, context) if access.visible and _still_current(executor, module_id, version_hint, selected): return selected, access diff --git a/python/tests/test_capability_discovery.py b/python/tests/test_capability_discovery.py index eb3298ca..56f86db4 100644 --- a/python/tests/test_capability_discovery.py +++ b/python/tests/test_capability_discovery.py @@ -5,9 +5,12 @@ import pytest from apcore import APCore, Context, Executor, Identity, ModuleAnnotations, Registry +from apcore import capabilities from apcore.acl import ACL, ACLRule +from apcore.builtin_steps import build_standard_strategy from apcore.config import Config -from apcore.errors import ACLDeniedError, InvalidInputError, SchemaValidationError +from apcore.errors import ACLDeniedError, InvalidInputError, ModuleError, SchemaValidationError +from apcore.pipeline import BaseStep, ExecutionStrategy, PipelineContext, StepResult class Module: @@ -66,6 +69,60 @@ def test_cursor_distinguishes_identity_attribute_types(original: Any, other: Any executor.list_callable(altered, limit=1, cursor=first.next_cursor) +def test_cursor_expires_at_its_monotonic_deadline(monkeypatch: pytest.MonkeyPatch) -> None: + registry = Registry() + for module_id in ("demo.a", "demo.b"): + registry.register(module_id, Module()) + now = 1_000.0 + monkeypatch.setattr(capabilities, "monotonic", lambda: now) + with Executor(registry) as executor: + cursor = executor.list_callable(limit=1).next_cursor + assert cursor + now = 1_299.999 + assert [item.module_id for item in executor.list_callable(limit=1, cursor=cursor).items] == ["demo.b"] + now = 1_300.0 + with pytest.raises(InvalidInputError, match="Invalid discovery cursor"): + executor.list_callable(limit=1, cursor=cursor) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("step_name", ["context_creation", "module_lookup"]) +async def test_discovery_omits_targets_skipped_by_essential_pipeline_step(step_name: str) -> None: + registry = Registry() + registry.register("demo.visible", Module()) + registry.register("demo.matching", Module()) + acl = ACL([ACLRule(["worker.reader"], ["demo.*"], "allow")]) + config = Config({"pipeline": {"configure": {step_name: {"match_modules": ["demo.match*"]}}}}) + context = Context.create().child("worker.reader") + with Executor(registry, acl=acl, config=config) as executor: + with pytest.raises(ModuleError) as actual: + await executor.call_async("demo.visible", {}, context) + if step_name == "context_creation": + assert isinstance(actual.value, ACLDeniedError) + assert executor.get_callable_descriptor("demo.visible", context) is None + assert [item.module_id for item in executor.list_callable(context).items] == ["demo.matching"] + + +@pytest.mark.asyncio +async def test_discovery_does_not_guess_a_custom_context_step() -> None: + class HostContextStep(BaseStep): + async def execute(self, ctx: PipelineContext) -> StepResult: + return StepResult(action="continue") + + registry = Registry() + registry.register("demo.visible", Module()) + acl = ACL([ACLRule(["worker.reader"], ["demo.*"], "allow")]) + steps = build_standard_strategy(registry=registry).steps + steps[0] = HostContextStep(name="context_creation", description="Host caller frame", provides=("context",)) + strategy = ExecutionStrategy("host-context", steps) + context = Context.create().child("worker.reader") + with Executor(registry, acl=acl, strategy=strategy) as executor: + with pytest.raises(ACLDeniedError): + await executor.call_async("demo.visible", {}, context) + assert executor.get_callable_descriptor("demo.visible", context) is None + assert not executor.list_callable(context).items + + def test_full_definition_uses_live_version_and_detaches_schemas() -> None: registry = Registry() registry.register("demo.versioned", Module(discoverable=False), version="1.0.0") diff --git a/rust/src/capability.rs b/rust/src/capability.rs index 21b5f047..24a5daf3 100644 --- a/rust/src/capability.rs +++ b/rust/src/capability.rs @@ -437,11 +437,13 @@ impl Executor { if permits_lookup != Some(true) { return None; } - if !strategy - .steps() + let steps = strategy.steps(); + let acl_index = steps .iter() - .any(|step| step.builtin_gate() == Some(BuiltinGate::Acl)) - { + .position(|step| step.builtin_gate() == Some(BuiltinGate::Acl))?; + if !steps[..acl_index].iter().any(|step| { + crate::pipeline_config::builtin_context_creation_applies(step.as_ref(), module_id) + }) { return None; } if let Some(acl) = &self.acl { @@ -513,3 +515,38 @@ impl Executor { })? } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Config, ErrorCode, Registry}; + + #[test] + fn test_capability_discovery_rejects_an_expired_cursor() { + let executor = Executor::new(Registry::new(), Config::default()); + let context = Context::anonymous(); + let query = CapabilityQuery::default(); + let token = executor.capability_discovery.save( + CursorScope::from(&context), + query.clone(), + CursorPosition { + candidates: Arc::new(Vec::new()), + offset: 0, + custom_search: false, + provider_revision: 0, + }, + ); + let resume = CapabilityQuery { + cursor: Some(token), + ..query + }; + assert!(executor + .list_callable(Some(&context), resume.clone()) + .is_ok()); + + executor.capability_discovery.cursors.lock()[0].created = Instant::now() - CURSOR_TTL; + let error = executor.list_callable(Some(&context), resume).unwrap_err(); + assert_eq!(error.code, ErrorCode::GeneralInvalidInput); + assert_eq!(error.message, "Invalid capability cursor"); + } +} diff --git a/rust/src/pipeline_config.rs b/rust/src/pipeline_config.rs index 460809ff..255b9094 100644 --- a/rust/src/pipeline_config.rs +++ b/rust/src/pipeline_config.rs @@ -7,7 +7,7 @@ use std::sync::OnceLock; use serde_json::Value; -use crate::builtin_steps::build_standard_strategy; +use crate::builtin_steps::{build_standard_strategy, BuiltinContextCreation}; use crate::errors::{ErrorCode, ModuleError}; use crate::pipeline::{ExecutionStrategy, Step}; @@ -87,6 +87,24 @@ struct ConfiguredStep { timeout_ms: u64, } +pub(crate) fn builtin_context_creation_applies(step: &dyn Step, module_id: &str) -> bool { + // The outermost overlay supplies the engine's matcher. Inspect wrapped + // steps only for their implementation identity. + step.match_modules().is_none_or(|patterns| { + patterns + .iter() + .any(|pattern| crate::utils::helpers::match_pattern(pattern, module_id)) + }) && is_builtin_context_creation(step) +} + +fn is_builtin_context_creation(step: &dyn Step) -> bool { + let implementation = step as &dyn std::any::Any; + implementation.downcast_ref::().map_or_else( + || implementation.is::(), + |configured| is_builtin_context_creation(configured.inner.as_ref()), + ) +} + #[async_trait::async_trait] impl Step for ConfiguredStep { fn name(&self) -> &str { diff --git a/rust/tests/capability_discovery.rs b/rust/tests/capability_discovery.rs index bb1dfe50..0e49ad81 100644 --- a/rust/tests/capability_discovery.rs +++ b/rust/tests/capability_discovery.rs @@ -321,6 +321,43 @@ fn test_capability_discovery_fails_closed_without_the_stock_gate() { .is_none()); } +#[tokio::test] +async fn test_capability_visibility_requires_context_creation_for_the_target() { + let strategy = apcore::pipeline_config::build_strategy_from_config(&json!({ + "configure": {"context_creation": {"match_modules": ["demo.included"]}} + })) + .unwrap(); + let mut executor = Executor::with_strategy(Registry::new(), Config::default(), strategy); + executor.set_acl(ACL::new( + vec![apcore::ACLRule::new( + vec!["worker.reader".into()], + vec!["demo.*".into()], + "allow", + )], + "deny", + None, + )); + for module_id in ["demo.included", "demo.skipped"] { + register(&executor, &json!({"module_id": module_id})); + } + let mut parent = reader("requester", vec![]); + parent.call_chain.push("worker.reader".into()); + let denied = executor + .call("demo.skipped", json!({}), Some(&parent), None) + .await + .unwrap_err(); + assert_eq!(denied.code, apcore::ErrorCode::ACLDenied); + + let page = executor + .list_callable(Some(&parent), CapabilityQuery::default()) + .unwrap(); + assert_eq!(page.items.len(), 1); + assert_eq!(page.items[0].module_id, "demo.included"); + assert!(executor + .get_callable_descriptor("demo.skipped", None, Some(&parent)) + .is_none()); +} + #[test] fn test_capability_hint_tracks_the_legacy_unguarded_approval_profile() { let mut executor = Executor::new(Registry::new(), Config::default()); diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index 500fe57f..fc91c965 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -89,6 +89,7 @@ import { PipelineEngine, PipelineStepError, StrategyNotFoundError, + stepMatchesModule, } from './pipeline.js'; import { MAX_MODULE_ID_LENGTH, MODULE_ID_PATTERN } from './registry/registry.js'; import type { Registry } from './registry/registry.js'; @@ -880,14 +881,21 @@ export class Executor { moduleId: string, parent: Context, ): { generation: object; approvalRequired: boolean; approvalConditional: boolean } | null { const steps = this._strategy.steps; - const lookup = steps.find(step => step.name === 'module_lookup'); - if (!(lookup instanceof BuiltinModuleLookup) || !lookup.usesRegistry(this._registry) || - lookup.toggleState.isDisabled(moduleId) || - !steps.some(step => step instanceof BuiltinContextCreation)) return null; + const contextIndex = steps.findIndex(step => step.name === 'context_creation'); + const lookupIndex = steps.findIndex(step => step.name === 'module_lookup'); + const createContext = steps[contextIndex]; + const lookup = steps[lookupIndex]; + if (!(createContext instanceof BuiltinContextCreation) || + Object.getPrototypeOf(createContext) !== BuiltinContextCreation.prototype || + createContext.execute !== BuiltinContextCreation.prototype.execute || + !stepMatchesModule(createContext, moduleId) || contextIndex >= lookupIndex) return null; + if (!(lookup instanceof BuiltinModuleLookup) || Object.getPrototypeOf(lookup) !== BuiltinModuleLookup.prototype || + lookup.execute !== BuiltinModuleLookup.prototype.execute || !stepMatchesModule(lookup, moduleId) || + !lookup.usesRegistry(this._registry) || lookup.toggleState.isDisabled(moduleId)) return null; const generation = this._registry.publicGeneration(moduleId); if (generation === null) return null; const gates = steps.filter(step => step.name === 'acl_check' || step instanceof BuiltinACLCheck); - if (gates.length === 0) return null; + if (gates.length === 0 || steps.indexOf(gates[0]) <= lookupIndex) return null; const target = parent.child(moduleId); let approvalRequired = false; let approvalConditional = false; diff --git a/typescript/src/pipeline.ts b/typescript/src/pipeline.ts index 35fd1abe..d312b336 100644 --- a/typescript/src/pipeline.ts +++ b/typescript/src/pipeline.ts @@ -55,6 +55,11 @@ export interface Step { execute(ctx: PipelineContext): Promise; } +/** @internal Check the module selector shared by execution and discovery. */ +export function stepMatchesModule(step: Step, moduleId: string): boolean { + return step.matchModules?.some(pattern => matchPattern(pattern, moduleId)) ?? true; +} + // --------------------------------------------------------------------------- // StepResult // --------------------------------------------------------------------------- @@ -1088,29 +1093,25 @@ export class PipelineEngine { observeStep?.(step.name, 'before_hooks'); // Read declarations (optional fields, backward compat via ?? defaults) - const stepMatchModules = step.matchModules ?? null; const stepIgnoreErrors = step.ignoreErrors ?? false; const stepPure = step.pure ?? false; const stepTimeoutMs = step.timeoutMs ?? 0; // 1 match_modules filter - if (stepMatchModules !== null) { - const matched = stepMatchModules.some((pattern) => matchPattern(pattern, ctx.moduleId)); - if (!matched) { - if (isDryRun()) { - for (const key of step.provides ?? []) failedProvides.add(key); - } - trace.steps.push({ - name: step.name, - durationMs: 0, - result: { action: 'continue' }, - skipped: true, - decisionPoint: false, - skipReason: 'no_match', - }); - idx += 1; - continue; + if (!stepMatchesModule(step, ctx.moduleId)) { + if (isDryRun()) { + for (const key of step.provides ?? []) failedProvides.add(key); } + trace.steps.push({ + name: step.name, + durationMs: 0, + result: { action: 'continue' }, + skipped: true, + decisionPoint: false, + skipReason: 'no_match', + }); + idx += 1; + continue; } // 2 dry_run filter: skip steps with side effects diff --git a/typescript/tests/test-capability-discovery.test.ts b/typescript/tests/test-capability-discovery.test.ts index 65f5d850..46cb0f5c 100644 --- a/typescript/tests/test-capability-discovery.test.ts +++ b/typescript/tests/test-capability-discovery.test.ts @@ -127,6 +127,31 @@ describe('capability discovery lifecycle and identity', () => { expect(executor.getCallableDefinition('demo.echo', requester())).toBeNull(); }); + it.each(['context_creation', 'module_lookup'] as const)( + 'withholds discovery when configured %s does not apply to the target', async step => { + const { registry, execute } = await fixtureRegistry(); + const context = requester().child('agent.reader'); + const acl = new ACL([{ + callers: ['agent.reader'], targets: ['demo.echo'], effect: 'allow', description: '', + conditions: { max_call_depth: 2 }, + }]); + const executorFor = (pattern: string): Executor => new Executor({ + registry, acl, + config: new Config({ pipeline: { configure: { [step]: { match_modules: [pattern] } } } }), + }); + const skipped = executorFor('other.*'); + + await expect(skipped.call('demo.echo', { message: 'test' }, context)).rejects.toThrow(); + expect(execute).not.toHaveBeenCalled(); + expect(skipped.listCallable(context).items).toEqual([]); + expect(skipped.getCallableDefinitions(['demo.echo'], context)).toEqual([]); + + const matching = executorFor('demo.*'); + expect(matching.listCallable(context).items.map(item => item.moduleId)).toEqual(['demo.echo']); + await expect(matching.call('demo.echo', { message: 'test' }, context)).resolves.toEqual({}); + }, + ); + it('scopes a continuation to principal, attrs, roles, parent frame, executor and filters', async () => { const { registry } = await fixtureRegistry(); const client = new APCore({ registry }); @@ -149,6 +174,75 @@ describe('capability discovery lifecycle and identity', () => { expect(() => new APCore({ registry }).listCallable(context, options)).toThrow(/cursor/i); }); + it('rejects a continuation at its expiry boundary', async () => { + const { registry } = await fixtureRegistry(); + const executor = new Executor({ registry }); + const context = requester(); + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000); + try { + const { nextCursor } = executor.listCallable(context, { limit: 1 }); + expect(nextCursor).toEqual(expect.any(String)); + now.mockReturnValue(301_000 - 1); + expect(executor.listCallable(context, { limit: 1, cursor: nextCursor }).items.map(item => item.moduleId)) + .toEqual(['demo.review']); + now.mockReturnValue(301_000); + expect(() => executor.listCallable(context, { limit: 1, cursor: nextCursor })) + .toThrow(/expired capability cursor/i); + } finally { + now.mockRestore(); + } + }); + + it.each([ + [{ query: 42 }, /query and prefix must be strings/i], + [{ tags: 'message' }, /tags must be a list/i], + [{ limit: 101 }, /limit must be an integer/i], + [{ includeApprovalRequired: 'false' }, /filters must be booleans/i], + [{ readonly: null }, /filters must be booleans/i], + ])('rejects invalid discovery options %j', async (options, error) => { + const { registry } = await fixtureRegistry(); + const executor = new Executor({ registry }); + expect(() => executor.listCallable(null, options as CapabilitySearchOptions)).toThrow(error); + }); + + it('lists read-only capabilities and rejects malformed definition and cursor requests', async () => { + const { registry } = await fixtureRegistry(); + const executor = new Executor({ registry }); + expect(executor.listCallable(null, { readonly: true }).items.map(item => item.moduleId)).toEqual(['demo.echo']); + expect(() => executor.getCallableDefinitions(['demo.echo', 5] as unknown as string[])) + .toThrow(/module IDs must be a list of strings/i); + expect(() => executor.listCallable(null, { cursor: 'not-issued' })).toThrow(/cursor/i); + + const page = executor.listCallable(null, { limit: 1 }); + expect(executor.listCallable(null, { cursor: page.nextCursor, limit: 1 }).items.map(item => item.moduleId)) + .toEqual(['demo.review']); + const nonCanonicalIdentity = requester([], 'reader', { groups: new Set(['test']) }); + expect(() => executor.listCallable(nonCanonicalIdentity, { limit: 1 })).toThrow(/cursor/i); + }); + + it('rejects a capability provider that returns a non-list', async () => { + const { registry } = await fixtureRegistry(); + const executor = new Executor({ registry, capabilitySearchProvider: { search: () => 'demo.echo' as never } }); + expect(() => executor.listCallable()).toThrow(/search must return a list of module IDs/i); + }); + + it.each([ + ['a proven branch of OR', { $or: [{ roles: ['reader'] }, { arguments: { has_key: ['message'] } }] }, true], + ['all false branches of OR', { $or: [{ roles: ['owner'] }, { roles: ['writer'] }] }, false], + ['an unknown branch of OR', { $or: [{ roles: ['owner'] }, { arguments: { has_key: ['message'] } }] }, false], + ['a false predicate under NOT', { $not: { roles: ['owner'] } }, true], + ['an unknown predicate under NOT', { $not: { arguments: { has_key: ['message'] } } }, false], + ] as const)('proves discovery outcomes for %s without call arguments', async (_label, conditions, visible) => { + const { registry, execute } = await fixtureRegistry(); + const acl = new ACL([{ + callers: ['@external'], targets: ['demo.echo'], effect: 'allow', description: '', conditions, + }]); + const executor = new Executor({ registry, acl }); + expect(executor.listCallable(requester(['reader'])).items.map(item => item.moduleId)) + .toEqual(visible ? ['demo.echo'] : []); + expect(execute).not.toHaveBeenCalled(); + }); + it('filters revoked, inactive and unknown candidates on every request and returns detached definitions', async () => { const { registry } = await fixtureRegistry(); const search = vi.fn(() => ['demo.hidden', 'demo.echo', 'demo.review', 'demo.unknown', 'demo.echo']); @@ -162,6 +256,7 @@ describe('capability discovery lifecycle and identity', () => { expect(search).toHaveBeenCalledTimes(1); expect(search).toHaveBeenCalledWith(undefined, ['demo.echo', 'demo.review']); expect(executor.getCallableDefinition('demo.echo', requester(), '2.0.0')).toBeNull(); + expect(executor.getCallableDefinition('demo.echo', requester(), '^1.0.0')?.version).toBe('1.0.0'); const current = executor.getCallableDefinition('demo.echo', requester(), '1.0.0'); expect(current?.inputSchema).toEqual(inputSchema); delete current!.inputSchema['properties']; From 625aa3ecbd1d0343fe62ab18c0a9943c17495199 Mon Sep 17 00:00:00 2001 From: tercel Date: Sat, 28 Nov 2026 08:11:37 +0800 Subject: [PATCH 5/5] test(discovery): use checked time arithmetic in Rust expiry coverage Signed-off-by: tercel --- rust/src/capability.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rust/src/capability.rs b/rust/src/capability.rs index 24a5daf3..6ff4e5ee 100644 --- a/rust/src/capability.rs +++ b/rust/src/capability.rs @@ -544,7 +544,8 @@ mod tests { .list_callable(Some(&context), resume.clone()) .is_ok()); - executor.capability_discovery.cursors.lock()[0].created = Instant::now() - CURSOR_TTL; + executor.capability_discovery.cursors.lock()[0].created = + Instant::now().checked_sub(CURSOR_TTL).unwrap(); let error = executor.list_callable(Some(&context), resume).unwrap_err(); assert_eq!(error.code, ErrorCode::GeneralInvalidInput); assert_eq!(error.message, "Invalid capability cursor");