From d274b1e4aa23efd4943cdb79fa4b2ac6712f10ad Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:13:50 +0800 Subject: [PATCH 01/10] refactor(python): assemble Core profiles and govern calls by default Signed-off-by: tercel --- python/apcore-conformance.yaml | 11 +- python/pyproject.toml | 23 +- python/src/apcore/__init__.py | 516 ++++-------------- python/src/apcore/_sync_bridge.py | 163 ++++++ python/src/apcore/acl.py | 4 +- python/src/apcore/bindings.py | 5 +- python/src/apcore/builtin_steps.py | 78 ++- python/src/apcore/client.py | 5 + python/src/apcore/config.py | 6 +- python/src/apcore/context.py | 49 -- python/src/apcore/discovery.py | 7 + python/src/apcore/events/__init__.py | 38 +- python/src/apcore/events/factory.py | 118 ++++ python/src/apcore/events/subscribers.py | 78 +-- python/src/apcore/executor.py | 194 ++----- python/src/apcore/full.py | 8 + python/src/apcore/observability/__init__.py | 5 +- .../observability/prometheus_exporter.py | 173 +----- .../apcore/observability/usage_exporter.py | 2 +- python/src/apcore/policy.py | 10 +- python/src/apcore/registry/metadata.py | 6 +- python/src/apcore/registry/registry.py | 8 +- python/src/apcore/registry/schema_export.py | 41 +- python/src/apcore/schema/__init__.py | 4 +- python/src/apcore/schema/exporter.py | 91 +-- python/src/apcore/schema/loader.py | 3 +- python/src/apcore/schema/ref_resolver.py | 4 +- python/src/apcore/schema/strict.py | 32 +- python/src/apcore/schema/types.py | 10 - python/src/apcore/sys_modules/control.py | 49 +- python/src/apcore/sys_modules/health.py | 29 +- python/src/apcore/sys_modules/overrides.py | 6 +- python/src/apcore/sys_modules/registration.py | 220 +------- .../test_core_profile_governance.py | 64 +++ .../conformance/test_governance_state.py | 3 +- .../conformance/test_issue123_contracts.py | 66 +-- .../conformance/test_reload_path_filter.py | 17 +- .../events/test_event_delivery_semantics.py | 13 +- .../events/test_event_management_hardening.py | 41 +- .../events/test_subscriber_retry_config.py | 33 +- python/tests/events/test_subscribers.py | 190 +------ .../test_observability_hardening.py | 7 +- .../test_observability_package.py | 2 +- .../test_prometheus_usage_metrics.py | 89 +-- .../tests/registry/test_ephemeral_modules.py | 6 +- python/tests/registry/test_schema_export.py | 10 - python/tests/schema/test_edge_cases.py | 2 - python/tests/schema/test_exporter.py | 224 +------- python/tests/schema/test_strict.py | 33 -- python/tests/schema/test_types.py | 19 - python/tests/sys_modules/test_control.py | 4 + .../tests/sys_modules/test_overrides_store.py | 6 +- python/tests/sys_modules/test_registration.py | 123 ++--- .../test_reload_dependents_deprecation.py | 89 +-- python/tests/test_apcore_client_spec.py | 5 + python/tests/test_approval_executor.py | 17 +- python/tests/test_builtin_steps.py | 3 +- .../test_call_chain_published_signature.py | 6 +- .../tests/test_circuit_breaker_middleware.py | 2 +- python/tests/test_client.py | 2 + python/tests/test_conformance.py | 8 +- .../tests/test_context_logger_deprecation.py | 77 +-- python/tests/test_context_serialization.py | 2 +- python/tests/test_deep_chain_v150.py | 5 +- .../tests/test_event_naming_and_identity.py | 24 +- python/tests/test_event_system_spec.py | 146 +---- python/tests/test_executor.py | 2 +- python/tests/test_executor_async.py | 145 +++-- python/tests/test_full_assembly.py | 117 ++++ python/tests/test_governance_state.py | 4 +- python/tests/test_observability_spec.py | 46 +- python/tests/test_policy.py | 39 +- python/tests/test_public_api.py | 401 ++------------ python/uv.lock | 342 +++++++++++- 74 files changed, 1489 insertions(+), 2941 deletions(-) create mode 100644 python/src/apcore/_sync_bridge.py create mode 100644 python/src/apcore/discovery.py create mode 100644 python/src/apcore/events/factory.py create mode 100644 python/src/apcore/full.py create mode 100644 python/tests/conformance/test_core_profile_governance.py create mode 100644 python/tests/test_full_assembly.py diff --git a/python/apcore-conformance.yaml b/python/apcore-conformance.yaml index 9b7edfa4..3e27cea9 100644 --- a/python/apcore-conformance.yaml +++ b/python/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-python - version: 1.0.0a1 + version: 1.0.0a2 language: python spec_version: 1.65.0 maintainer: AI Perceivable @@ -11,9 +11,9 @@ conformance: date: "2026-10-08" assessment_scope: issue-123-regressions-and-canonical-name fixture_results: - fixtures: 9 - cases: 79 - passed: 79 + fixtures: 8 + cases: 74 + passed: 74 failed: 0 skipped: 0 report: tests/conformance/test_issue123_contracts.py @@ -26,7 +26,6 @@ conformance: - env_prefix_dispatch - ephemeral_modules - error_details_shape - - export_profiles - json_input_native_types - preflight_check_reporting - timeout_cancellation @@ -34,7 +33,7 @@ conformance: known_deviations: - feature: full-fixture-verification spec: conformance §6.2 - reason: Only nine fixtures (47 issue-123 cases and 32 canonical-name cases) have individually verified case counts in this assessment. No claim is made that all 1107 canonical cases pass; Level 1 or 2 certification requires a complete case-level report. + reason: Only eight fixtures (42 issue-123 cases and 32 canonical-name cases) have individually verified case counts in this assessment. No claim is made that all 1107 canonical cases pass; Level 1 or 2 certification requires a complete case-level report. severity: major - feature: storage-backend-scalar-values spec: StorageBackend.save diff --git a/python/pyproject.toml b/python/pyproject.toml index 9d3d35eb..4907b234 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "apcore" -version = "1.0.0a1" +version = "1.0.0a2" 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" @@ -40,12 +40,11 @@ classifiers = [ "Typing :: Typed", ] dependencies = [ - # Upper bounds pin the major so a downstream major release (pydantic 3, - # pyyaml 7, jsonschema 5) does not silently break installs. Raise the + # Upper bounds pin the major so downstream major releases do not + # silently break installs. Raise the # upper bound deliberately after a compatibility check rather than # absorbing breakage from `pip install --upgrade`. "pydantic>=2.7,<3", - "pyyaml>=6.0,<7", "jsonschema>=4.21,<5", "referencing>=0.30,<1", ] @@ -58,14 +57,28 @@ Issues = "https://github.com/aiperceivable/apcore/issues" Changelog = "https://github.com/aiperceivable/apcore/blob/main/python/CHANGELOG.md" [project.optional-dependencies] +config = [ + "pyyaml>=6.0,<7", +] +discovery = [ + "pyyaml>=6.0,<7", + "watchdog>=3.0", +] events = [ "aiohttp>=3.9", ] +observability = [ + "opentelemetry-sdk>=1.34,<2", + "opentelemetry-exporter-otlp-proto-http>=1.34,<2", +] +all = [ + "apcore[config,discovery,events,observability]", +] dev = [ "pytest>=7.0", "pytest-asyncio>=0.23", "pytest-cov>=4.0", - "watchdog>=3.0", # Type-check and exercise the optional file watcher. + "apcore[config,discovery]", # Bound the minor: ruff 0.x treats the minor as its major, and each minor can # change lint defaults and formatter output. Raise deliberately. "ruff>=0.15.0,<0.17", diff --git a/python/src/apcore/__init__.py b/python/src/apcore/__init__.py index 93924d38..051a0ac3 100644 --- a/python/src/apcore/__init__.py +++ b/python/src/apcore/__init__.py @@ -1,3 +1,4 @@ +# ruff: noqa: F401 """apcore - Schema-driven module standard.""" from __future__ import annotations @@ -5,6 +6,7 @@ import asyncio from collections.abc import AsyncGenerator from contextlib import aclosing +from importlib import import_module from importlib.metadata import PackageNotFoundError from importlib.metadata import version as _get_version from typing import Any @@ -61,6 +63,7 @@ UnregisterOptions, ) from apcore.registry.types import DependencyInfo, DiscoveredModule, ModuleDescriptor +from apcore.events.emitter import EventSubscriber from apcore.executor import Executor from apcore.utils.redaction import REDACTED_VALUE, redact_sensitive @@ -77,13 +80,6 @@ ValidationResult, ) -# Config -from apcore.config import ( - RESERVED_NAMESPACES, - Config, - discover_config_file, -) - # Error Formatter from apcore.error_formatter import ErrorFormatter, ErrorFormatterRegistry from apcore.streaming import ( @@ -215,12 +211,8 @@ TaskStore, ) -# Bindings -from apcore.bindings import BindingLoader - # Schema from apcore.schema import ( - ExportProfile as ExportProfile, SchemaLoader as SchemaLoader, SchemaStrategy as SchemaStrategy, SchemaValidator as SchemaValidator, @@ -249,49 +241,6 @@ ) from apcore.utils.pattern import calculate_specificity as calculate_specificity -# Observability -from apcore.observability import ( - ContextLogger, - ErrorEntry, - ErrorHistory, - InMemoryExporter, - InMemoryStorageBackend, - MetricsCollector, - MetricsMiddleware, - NoopUsageExporter, - ObsLoggingMiddleware, - OTLPExporter, - PeriodicUsageExporter, - Span, - SpanExporter, - StdoutExporter, - StorageBackend, - TracingMiddleware, - UsageCollector, - UsageExporter, - UsageMiddleware, - create_span, -) -from apcore.observability.metrics import ( - METRIC_CALLS_TOTAL, - METRIC_DURATION_SECONDS, -) - -# Events -from apcore.events import ( - A2ASubscriber, - ApCoreEvent, - EventEmitter, - EventRetryConfig, - EventSubscriber, - FileSubscriber, - FilterSubscriber, - StdoutSubscriber, - WebhookSubscriber, - create_subscriber_from_config, - register_subscriber_factory, -) - # NOTE (audit D1-003, 2026-05-28): the events-layer circuit-breaker types # `CircuitBreakerWrapper` / `CircuitState` are intentionally NOT re-exported at # the top level. TypeScript and Rust export them at the package/crate root, but @@ -358,46 +307,6 @@ # Trace Context from apcore.trace_context import TraceContext, TraceParent -# System Modules -from apcore.sys_modules.registration import ( - SysModulesContext, - register_sys_modules, -) - -# Deprecated subscriber-type APIs — kept importable for back-compat, but -# NOT listed in __all__ so they don't appear in `from apcore import *` -# or in IDE auto-completion for new code. Use EventEmitter.subscribe() -# directly. -from apcore.sys_modules.registration import ( # noqa: F401 - register_subscriber_type as register_subscriber_type, - reset_subscriber_registry as reset_subscriber_registry, - unregister_subscriber_type as unregister_subscriber_type, -) -from apcore.sys_modules.health import ( - HealthModule, - HealthSummaryModule, - classify_health_status, -) -from apcore.sys_modules.manifest import ( - ManifestFullModule, - ManifestModule, -) -from apcore.sys_modules.usage import ( - UsageModule, - UsageSummaryModule, -) -from apcore.sys_modules.control import ( - ReloadModule, - ToggleFeatureModule, - ToggleState, - UpdateConfigModule, -) -from apcore.sys_modules.overrides import ( - FileOverridesStore, - InMemoryOverridesStore, - OverridesStore, -) - # --------------------------------------------------------------------------- # Default client for simplified global access # --------------------------------------------------------------------------- @@ -454,15 +363,70 @@ def close() -> None: client._close_owned_resources(terminal=True) -def __getattr__(name: str) -> Any: - """PEP 562 lazy attribute access for the default-client singleton. +# Explicit imports of extension names remain available during migration. +_EXTENSION_EXPORTS = { + "ApCoreEvent": "apcore.events", + "BindingLoader": "apcore.bindings", + "Config": "apcore.config", + "ContextLogger": "apcore.observability", + "ErrorEntry": "apcore.observability", + "ErrorHistory": "apcore.observability", + "EventEmitter": "apcore.events", + "EventRetryConfig": "apcore.events", + "FileOverridesStore": "apcore.sys_modules.overrides", + "FileSubscriber": "apcore.events", + "FilterSubscriber": "apcore.events", + "HealthModule": "apcore.sys_modules.health", + "HealthSummaryModule": "apcore.sys_modules.health", + "InMemoryExporter": "apcore.observability", + "InMemoryOverridesStore": "apcore.sys_modules.overrides", + "InMemoryStorageBackend": "apcore.observability", + "METRIC_CALLS_TOTAL": "apcore.observability.metrics", + "METRIC_DURATION_SECONDS": "apcore.observability.metrics", + "ManifestFullModule": "apcore.sys_modules.manifest", + "ManifestModule": "apcore.sys_modules.manifest", + "MetricsCollector": "apcore.observability", + "MetricsMiddleware": "apcore.observability", + "NoopUsageExporter": "apcore.observability", + "OTLPExporter": "apcore.observability", + "ObsLoggingMiddleware": "apcore.observability", + "OverridesStore": "apcore.sys_modules.overrides", + "PeriodicUsageExporter": "apcore.observability", + "RESERVED_NAMESPACES": "apcore.config", + "ReloadModule": "apcore.sys_modules.control", + "Span": "apcore.observability", + "SpanExporter": "apcore.observability", + "StdoutExporter": "apcore.observability", + "StdoutSubscriber": "apcore.events", + "StorageBackend": "apcore.observability", + "SysModulesContext": "apcore.sys_modules.registration", + "ToggleFeatureModule": "apcore.sys_modules.control", + "ToggleState": "apcore.sys_modules.control", + "TracingMiddleware": "apcore.observability", + "UpdateConfigModule": "apcore.sys_modules.control", + "UsageCollector": "apcore.observability", + "UsageExporter": "apcore.observability", + "UsageMiddleware": "apcore.observability", + "UsageModule": "apcore.sys_modules.usage", + "UsageSummaryModule": "apcore.sys_modules.usage", + "WebhookSubscriber": "apcore.events", + "classify_health_status": "apcore.sys_modules.health", + "create_span": "apcore.observability", + "create_subscriber_from_config": "apcore.events", + "discover_config_file": "apcore.config", + "register_sys_modules": "apcore.sys_modules.registration", +} - Access to ``apcore._default_client`` returns the same object the - convenience functions call; allocates it on first access. Other names - fall through to ``AttributeError``. - """ + +def __getattr__(name: str) -> Any: + """Lazily resolve the default client and explicit extension imports.""" if name == "_default_client": return _get_default_client() + extension = _EXTENSION_EXPORTS.get(name) + if extension is not None: + value = getattr(import_module(extension), name) + globals()[name] = value + return value raise AttributeError(f"module 'apcore' has no attribute {name!r}") @@ -619,341 +583,47 @@ def enable(module_id: str, reason: str = "Enabled via APCore client") -> dict[st __version__ = "unknown" __all__ = [ - # Core - "CancelToken", - "ExecutionCancelledError", - "Context", - "ContextFactory", - "ContextKey", - "TRACING_SPANS", - "TRACING_SAMPLED", - "METRICS_STARTS", - "LOGGING_START", - "REDACTED_OUTPUT", - "RETRY_COUNT_BASE", - "GovernanceProjection", - "Identity", - "Registry", - "Executor", + "ACL", + "ACLRule", "APCore", - "DrainAbortedContext", - "DrainContext", - "LifecycleError", - "LifecycleModuleReport", - "LifecycleOperation", - "LifecycleReport", - "ReloadOptions", - "ShutdownOptions", - "UnregisterOptions", - "close", - "call", - "call_async", - "stream", - "validate", - "register", - "describe", - "use", - "use_before", - "use_after", - "remove", - "discover", - "list_modules", - "on", - "off", - "disable", - "enable", - # Approval + "ApprovalDeniedError", "ApprovalHandler", + "ApprovalPendingError", "ApprovalRequest", "ApprovalResult", - "AlwaysDenyHandler", "AutoApproveHandler", - "CallbackApprovalHandler", - "ScopedApprovalHandler", - # Module types - "Change", - "DEFAULT_ANNOTATIONS", + "CancelToken", + "Context", + "ErrorCodes", + "ExecutionPolicy", + "ExecutionStrategy", + "Executor", + "Identity", + "Middleware", "Module", "ModuleAnnotations", - "ModuleExample", - "ValidationResult", - "PreflightCheckResult", + "ModuleError", + "PipelineEngine", "PreflightResult", "PreviewResult", - # Registry types - "ModuleDescriptor", - "DiscoveredModule", - "DependencyInfo", - # ID conflict detection - "ConflictResult", - "ConflictSeverity", - "ConflictType", - "detect_id_conflicts", - # Config - "Config", - "RESERVED_NAMESPACES", - "discover_config_file", - # Error Formatter - "ErrorFormatter", - "ErrorFormatterRegistry", - # Streaming + "Registry", + "ReloadOptions", + "SchemaExporter", + "SchemaValidator", + "ScopedApprovalHandler", + "ShutdownOptions", "StreamCompletion", - "StreamCompletionReason", "StreamExecution", "StreamingModule", - "StreamStepOutcome", - # Registry protocols - "Discoverer", - "ModuleValidator", - # Multi-class discovery - "class_name_to_segment", - "discover_multi_class", - # Registry module-id constants (parity with apcore-typescript / apcore-rust - # root exports; previously reachable only via apcore.registry.registry) - "DEFAULT_MODULE_VERSION", - "EPHEMERAL_NAMESPACE_PREFIX", - "MAX_MODULE_ID_LENGTH", - "MODULE_ID_PATTERN", - "REGISTRY_EVENTS", - "RESERVED_WORDS", - # Errors - "ErrorCodes", - "ModuleError", - "ACLDeniedError", - "ACLRuleError", - "ApprovalError", - "ApprovalDeniedError", - "ApprovalTimeoutError", - "ApprovalPendingError", - "BindingCallableNotFoundError", - "BindingFileInvalidError", - "BindingInvalidTargetError", - "BindingModuleNotFoundError", - "BindingNotCallableError", - "BindingSchemaInferenceFailedError", - "BindingSchemaMissingError", - "BindingSchemaModeConflictError", - "BindingStrictSchemaIncompatibleError", - "CallDepthExceededError", - "CallFrequencyExceededError", - "CircuitBreakerOpenError", - "CircuitOpenError", - "CircularCallError", - "CircularDependencyError", - "ConfigBindError", - "ConfigEnvMapConflictError", - "ConfigEnvPrefixConflictError", - "ConfigError", - "ConfigMountError", - "ConfigNamespaceDuplicateError", - "ConfigNamespaceReservedError", - "ConfigNotFoundError", - "ContextBindingError", - "DependencyNotFoundError", - "DependencyVersionMismatchError", - "ErrorFormatterDuplicateError", - "ErrorCodeCollisionError", - "ErrorCodeRegistry", - "FRAMEWORK_ERROR_CODE_PREFIXES", - "FuncMissingReturnTypeError", - "FuncMissingTypeHintError", - "IdTooLongError", - "InternalError", - "InvalidInputError", - "InvalidParentIdError", - "InvalidSegmentError", - "ModuleDisabledError", - "ModuleExecuteError", - "ModuleIdConflictError", - "ModuleLoadError", - "ModuleNotFoundError", - "ModuleReloadConflictError", - "ReloadFailedError", - "SysModuleRegistrationError", - "SysModulesDisabledError", - "StreamingInterfaceError", - "ModuleTimeoutError", - "SchemaCircularRefError", - "SchemaMaxDepthExceededError", - "SchemaNotFoundError", - "SchemaParseError", - "SchemaValidationError", - "TaskLimitExceededError", - "TaskStoreError", - "VersionConstraintError", - # ACL - "ACL", - "ACLRule", - "AccessDecision", - "AuditEntry", - "ConditionOutcome", - "RuleValidationFinding", - # Execution-time governance policy (apcore#76 RFC pilot) - "ExecutionPolicy", - "PolicyDecision", - "PolicyRule", - # Middleware - "Middleware", - "RetrySignal", - "MiddlewareManager", - "BeforeMiddleware", - "AfterMiddleware", - "LoggingMiddleware", - "MiddlewareChainError", - "NamespaceCheck", - "validate_context_key", - "APCORE_KEY_PREFIX", - "EXT_KEY_PREFIX", - "RetryConfig", - "RetryMiddleware", - "ErrorHistoryMiddleware", - "PlatformNotifyMiddleware", - "CircuitBreakerMiddleware", - "CircuitBreakerState", - # Decorators + "TraceContext", + "UnregisterOptions", + "call", + "call_async", + "close", "module", - "FunctionModule", - # NOTE: parse_docstring is intentionally NOT in __all__ — it is an - # implementation detail importable via apcore._docstrings. - # Extensions - "ExtensionManager", - "ExtensionPoint", - # Async tasks - "AsyncTaskManager", - "TaskStatus", - "TaskInfo", - "TaskStore", - "InMemoryTaskStore", - "AsyncRetryConfig", - "RetryPolicy", - "BackoffStrategy", - # Bindings - "BindingLoader", - # Schema - "SchemaStrategy", - "ExportProfile", - "SchemaLoader", - "SchemaValidator", - "SchemaExporter", - "RefResolver", - "to_strict_schema", - # Utilities - "match_pattern", - "guard_call_chain", - "DEFAULT_MAX_CALL_DEPTH", - "DEFAULT_MAX_MODULE_REPEAT", - "normalize_to_canonical_id", - "canonicalize_name", - "CanonicalNameError", - "CanonicalNameResult", - "calculate_specificity", - "propagate_error", "redact_sensitive", - "REDACTED_VALUE", - # Observability - "TracingMiddleware", - "ContextLogger", - "ObsLoggingMiddleware", - "MetricsMiddleware", - "METRIC_CALLS_TOTAL", - "METRIC_DURATION_SECONDS", - "MetricsCollector", - "Span", - "StdoutExporter", - "InMemoryExporter", - "OTLPExporter", - "SpanExporter", - "create_span", - "ErrorEntry", - "ErrorHistory", - "StorageBackend", - "InMemoryStorageBackend", - "UsageCollector", - "UsageExporter", - "UsageMiddleware", - "NoopUsageExporter", - "PeriodicUsageExporter", - # Events - "ApCoreEvent", - "EventEmitter", - "EventSubscriber", - "EventRetryConfig", - "WebhookSubscriber", - "A2ASubscriber", - "FileSubscriber", - "StdoutSubscriber", - "FilterSubscriber", - "register_subscriber_factory", - "create_subscriber_from_config", - # Trace Context - "TraceContext", - "TraceParent", - # Version - "VersionIncompatibleError", - "negotiate_version", - # Pipeline - "Step", - "BaseStep", - "StepMiddleware", - "StepResult", - "PipelineContext", - "PipelineEngine", - "PipelineTrace", - "StepTrace", - "ExecutionStrategy", - "GovernanceState", - "StrategyInfo", - "PipelineAbortError", - "PipelineState", - "PipelineStepError", - "PipelineStepNotFoundError", - "StepNotFoundError", - "StepNotRemovableError", - "StepNotReplaceableError", - "StepNameDuplicateError", - "StrategyNotFoundError", - "ConfigurationError", - "PipelineDependencyError", - # Pipeline Configuration - "register_step_type", - "unregister_step_type", - "registered_step_types", - "build_strategy_from_config", - # Pipeline Preset Builders (parity with apcore-typescript / apcore-rust) - "build_standard_strategy", - "build_internal_strategy", - "build_testing_strategy", - "build_performance_strategy", - "build_minimal_strategy", - # Builtin Pipeline Steps (parity with apcore-typescript / apcore-rust) - "BuiltinContextCreation", - "BuiltinCallChainGuard", - "BuiltinModuleLookup", - "BuiltinACLCheck", - "BuiltinApprovalGate", - "BuiltinMiddlewareBefore", - "BuiltinInputValidation", - "BuiltinExecute", - "BuiltinOutputValidation", - "BuiltinMiddlewareAfter", - "BuiltinReturnResult", - # System Modules - "register_sys_modules", - "SysModulesContext", - # System Module Implementations - "HealthSummaryModule", - "HealthModule", - "classify_health_status", - "ManifestFullModule", - "ManifestModule", - "UsageSummaryModule", - "UsageModule", - "UpdateConfigModule", - "ReloadModule", - "ToggleFeatureModule", - "ToggleState", - # Overrides Store (cross-language alignment with TS / Rust) - "OverridesStore", - "InMemoryOverridesStore", - "FileOverridesStore", + "register", + "stream", + "to_strict_schema", + "validate", ] diff --git a/python/src/apcore/_sync_bridge.py b/python/src/apcore/_sync_bridge.py new file mode 100644 index 00000000..f0000d67 --- /dev/null +++ b/python/src/apcore/_sync_bridge.py @@ -0,0 +1,163 @@ +"""Own the event loops and workers used by the Executor's synchronous entry points.""" + +from __future__ import annotations + +import asyncio +import logging +import threading +import time +import weakref +from collections.abc import Coroutine +from concurrent.futures import Future, ThreadPoolExecutor +from typing import Any + +from apcore.errors import ErrorCodes, ModuleError, ModuleTimeoutError + +_NESTED_WORKERS = 4 +_worker_thread = threading.local() +_logger = logging.getLogger("apcore.executor") + + +class _ThreadLoop: + def __init__(self) -> None: + self.loop = asyncio.new_event_loop() + self.active = False + self.retired = False + self.close = weakref.finalize(self, self.loop.close) + + +class _SyncBridge: + def __init__(self) -> None: + self._lock = threading.Lock() + self._local = threading.local() + self._loops: weakref.WeakSet[_ThreadLoop] = weakref.WeakSet() + self._pool: ThreadPoolExecutor | None = None + self._slots = threading.BoundedSemaphore(_NESTED_WORKERS) + + def close(self) -> None: + with self._lock: + loops = list(self._loops) + self._loops.clear() + for owner in loops: + owner.retired = True + if not owner.active: + owner.close() + pool, self._pool = self._pool, None + if pool is not None: + pool.shutdown(wait=False) + + def run(self, coro: Coroutine[Any, Any, Any], module_id: str, wait: float | None) -> Any: + try: + asyncio.get_running_loop() + except RuntimeError: + pass + else: + return self._run_on_worker(coro, module_id, wait) + + try: + with self._lock: + owner: _ThreadLoop | None = getattr(self._local, "owner", None) + if owner is None or owner.retired: + owner = _ThreadLoop() + self._local.owner = owner + self._loops.add(owner) + owner.active = True + except BaseException: + coro.close() + raise + + try: + return owner.loop.run_until_complete(coro) + finally: + with self._lock: + owner.active = False + if owner.retired: + owner.close() + + def _run_on_worker(self, coro: Coroutine[Any, Any, Any], module_id: str, wait: float | None) -> Any: + deadline = None if wait is None else time.monotonic() + wait + reentrant = getattr(_worker_thread, "active", False) + # A worker waiting for another slot could deadlock the pool. It can + # make a nested sync call while there is spare capacity. + admitted = self._slots.acquire(blocking=False) if reentrant else self._slots.acquire(timeout=wait) + if not admitted: + coro.close() + if reentrant: + raise ModuleError( + code=ErrorCodes.MODULE_EXECUTE_ERROR, + message="Sync bridge is busy. Await the asynchronous Executor method from a bridge worker.", + details={"module_id": module_id}, + ) + assert wait is not None + raise _bridge_timeout(module_id, wait) + + result: Future[Any] = Future() + expired = threading.Event() + worker: tuple[asyncio.AbstractEventLoop, asyncio.Task[Any]] | None = None + + def run() -> None: + nonlocal worker + _worker_thread.active = True + try: + if expired.is_set() or (deadline is not None and time.monotonic() >= deadline): + coro.close() + return + loop = asyncio.new_event_loop() + try: + task = loop.create_task(coro) + worker = loop, task + if expired.is_set(): + task.cancel() + result.set_result(loop.run_until_complete(task)) + except BaseException as exc: + result.set_exception(exc) + finally: + # Publish before draining so D-133 timeout/cancellation + # never waits for cooperative cleanup on the caller. + pending = asyncio.all_tasks(loop) + try: + if pending: + loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True)) + finally: + loop.close() + except BaseException as exc: + if not result.done(): + coro.close() + result.set_exception(exc) + else: + _logger.warning("Sync bridge cleanup failed", exc_info=True) + finally: + _worker_thread.active = False + self._slots.release() + + try: + with self._lock: + if self._pool is None: + self._pool = ThreadPoolExecutor(max_workers=_NESTED_WORKERS, thread_name_prefix="apcore-sync") + self._pool.submit(run) + except BaseException: + self._slots.release() + coro.close() + raise + + remaining = None if deadline is None else max(0.0, deadline - time.monotonic()) + try: + return result.result(remaining) + except TimeoutError: + if result.done() or wait is None: + return result.result() + + expired.set() + if worker is not None: + loop, task = worker + try: + loop.call_soon_threadsafe(task.cancel) + except RuntimeError: + # The worker finished between the wait and the cancellation. + pass + raise _bridge_timeout(module_id, wait) + + +def _bridge_timeout(module_id: str, wait: float) -> ModuleTimeoutError: + _logger.warning("Sync bridge wait expired for module %s", module_id) + return ModuleTimeoutError(module_id=module_id, timeout_ms=round(wait * 1000), retryable=False) diff --git a/python/src/apcore/acl.py b/python/src/apcore/acl.py index dd224242..88904ab7 100644 --- a/python/src/apcore/acl.py +++ b/python/src/apcore/acl.py @@ -18,8 +18,6 @@ from pathlib import Path from typing import Any, Callable, ClassVar -import yaml - from apcore.acl_handlers import ( ACLConditionHandler, ConditionOutcome, @@ -1640,6 +1638,8 @@ def load( if not os.path.isfile(yaml_path): raise ConfigNotFoundError(config_path=yaml_path) + import yaml + with open(yaml_path, encoding="utf-8") as f: try: data = yaml.safe_load(f) diff --git a/python/src/apcore/bindings.py b/python/src/apcore/bindings.py index 6274bb3c..93142065 100644 --- a/python/src/apcore/bindings.py +++ b/python/src/apcore/bindings.py @@ -11,7 +11,6 @@ import re from typing import Any, Callable -import yaml from pydantic import BaseModel from apcore.config import Config @@ -277,6 +276,8 @@ def load_bindings( binding_file_dir = resolved_binding.parent schema_loader = SchemaLoader(config if config is not None else Config(), schemas_dir=binding_file_dir) + import yaml + try: data = yaml.safe_load(content) except yaml.YAMLError as exc: @@ -546,6 +547,8 @@ def _resolve_schema( # Mode 2: external reference if "schema_ref" in binding: + import yaml + ref_path = _schema_ref_path(binding["schema_ref"], binding_file_dir, config, file_path) try: ref_data = yaml.safe_load(ref_path.read_text(encoding="utf-8")) diff --git a/python/src/apcore/builtin_steps.py b/python/src/apcore/builtin_steps.py index e5e69c3f..6e2e9d52 100644 --- a/python/src/apcore/builtin_steps.py +++ b/python/src/apcore/builtin_steps.py @@ -704,12 +704,9 @@ class BuiltinApprovalGate(_GovernanceGateFields): translates the result into either continued execution or the appropriate ``ApprovalError`` subclass. - Fail-loud governance (apcore#76): when a module needs approval but no - handler is configured, the gate keeps the PROTOCOL_SPEC §7.4 skip - behavior but logs a warning (once per module). With - ``ExecutionPolicy(strict=True)`` it fails closed instead. A module whose - effective ``destructive`` annotation is true but that no approval gate - covers is also warned about once per module. + Without an approval handler, the default policy rejects calls that need + approval. An explicit non-strict policy continues and logs a warning once + per module. The default policy also gates destructive modules. """ def __init__( @@ -728,7 +725,7 @@ def __init__( requires=("context", "module"), ) self._handler = handler - self._policy = policy + self._policy = policy if policy is not None else ExecutionPolicy() self._event_emitter = event_emitter self._warned: set[str] = set() @@ -737,8 +734,8 @@ def set_handler(self, handler: Any | None) -> None: self._handler = handler def set_policy(self, policy: ExecutionPolicy | None) -> None: - """Replace the execution policy used by this step at runtime.""" - self._policy = policy + """Replace the execution policy or restore its defaults with None.""" + self._policy = policy if policy is not None else ExecutionPolicy() def set_event_emitter(self, event_emitter: Any | None) -> None: """Set the event emitter for approval decisions and policy overrides.""" @@ -750,7 +747,7 @@ def handler(self) -> Any | None: return self._handler @property - def policy(self) -> ExecutionPolicy | None: + def policy(self) -> ExecutionPolicy: """The ExecutionPolicy this gate applies (read by ``governance_state()``, §6.6.5.5).""" return self._policy @@ -778,36 +775,31 @@ async def execute(self, ctx: PipelineContext) -> StepResult: getattr(ctx, "declared_annotations", None), ) - decision: PolicyDecision | None = None - if self._policy is not None: - # PROTOCOL_SPEC §7.9.6: policy resolution receives the call site. - # The arguments have NOT been schema-validated at this point — this - # gate is Step 5 and input validation is Step 7 (§12.8) — and the - # built-in pattern rules do not consult them, so the verdict of an - # existing policy is unchanged. A host-supplied policy can decide - # on them, and an implementation can carry them into the audit - # trail. The pipeline separates the resume credential at entry. - decision = self._policy.resolve( - ctx.module_id, - governance, - arguments=ctx.inputs, - context=ctx.context, - ) - # §6.9 row 4: a policy may ADD an approval requirement and MUST NOT - # remove one the ACL set. The ACL is a caller-scoped authorization - # layer; ExecutionPolicy is a module-scoped platform override, and - # letting the module-scoped one cancel the caller-scoped one is a - # privilege escalation — a policy rule written for `orders.*` would - # silently strip a requirement an ACL author attached to one - # untrusted caller. Union is the only safe composition, so the OR - # here is load-bearing and not a convenience. - needs_approval = decision.needs_approval or acl_requires_approval - effective_destructive = decision.destructive - if decision.overridden: - self._emit_policy_audit(decision, ctx.context) - else: - needs_approval = _requires_approval(governance) or acl_requires_approval - effective_destructive = _is_destructive(governance) + # PROTOCOL_SPEC §7.9.6: policy resolution receives the call site. + # The arguments have NOT been schema-validated at this point — this + # gate is Step 5 and input validation is Step 7 (§12.8) — and the + # built-in pattern rules do not consult them, so the verdict of an + # existing policy is unchanged. A host-supplied policy can decide + # on them, and an implementation can carry them into the audit + # trail. The pipeline separates the resume credential at entry. + decision = self._policy.resolve( + ctx.module_id, + governance, + arguments=ctx.inputs, + context=ctx.context, + ) + # §6.9 row 4: a policy may ADD an approval requirement and MUST NOT + # remove one the ACL set. The ACL is a caller-scoped authorization + # layer; ExecutionPolicy is a module-scoped platform override, and + # letting the module-scoped one cancel the caller-scoped one is a + # privilege escalation — a policy rule written for `orders.*` would + # silently strip a requirement an ACL author attached to one + # untrusted caller. Union is the only safe composition, so the OR + # here is load-bearing and not a convenience. + needs_approval = decision.needs_approval or acl_requires_approval + effective_destructive = decision.destructive + if decision.overridden: + self._emit_policy_audit(decision, ctx.context) if not needs_approval: if effective_destructive: @@ -822,7 +814,7 @@ async def execute(self, ctx: PipelineContext) -> StepResult: return StepResult(action="continue") if self._handler is None: - if self._policy is not None and self._policy.strict: + if self._policy.strict: result = ApprovalResult( status="rejected", reason=( @@ -835,8 +827,8 @@ async def execute(self, ctx: PipelineContext) -> StepResult: self._warn_once( f"no_handler:{ctx.module_id}", "Module '%s' requires approval but no ApprovalHandler is configured; " - "the approval gate is skipped per PROTOCOL_SPEC §7.4. Configure an " - "approval handler, or ExecutionPolicy(strict=True) to fail closed. (apcore#76)", + "the explicit non-strict policy allows the call to proceed. Configure an " + "approval handler to require approval regardless of the compatibility policy.", ctx.module_id, ) return StepResult(action="continue") diff --git a/python/src/apcore/client.py b/python/src/apcore/client.py index 93d87c0f..7ab3a26f 100644 --- a/python/src/apcore/client.py +++ b/python/src/apcore/client.py @@ -27,6 +27,7 @@ from apcore.errors import InvalidInputError, SysModulesDisabledError from apcore.decorator import module as decorator_module from apcore.events.emitter import ApCoreEvent, EventEmitter, EventSubscriber +from apcore.events.factory import SubscriberRegistry from apcore.executor import Executor from apcore.lifecycle import ( LifecycleError, @@ -65,6 +66,7 @@ def __init__( policy: ExecutionPolicy | None = None, *, fail_on_error: bool = False, + subscriber_registry: SubscriberRegistry | None = None, ) -> None: """Initialize the APCore client. @@ -82,6 +84,8 @@ def __init__( fail_on_error: Raise the first system-module registration failure. By default, startup continues and exposes failures through ``sys_modules_errors``. + subscriber_registry: Factories for this client's configured event + subscribers. Omitting this uses the built-in factories. """ self.config = config self._shutdown_lock = threading.Lock() @@ -179,6 +183,7 @@ def __init__( fail_on_error=fail_on_error, toggle_state=self.toggle_state, on_registration_error=self._sys_modules_errors.append, + subscriber_registry=subscriber_registry, ) except Exception as exc: if fail_on_error: diff --git a/python/src/apcore/config.py b/python/src/apcore/config.py index 28fdfa6c..633c41cf 100644 --- a/python/src/apcore/config.py +++ b/python/src/apcore/config.py @@ -18,8 +18,6 @@ from collections.abc import Sequence from typing import Any, Type, TypeVar -import yaml - from apcore.errors import ( ConfigBindError, ConfigEnvMapConflictError, @@ -1487,6 +1485,8 @@ def _load_document(cls, yaml_path: str, *, project_root: str, validate: bool) -> if not absolute_path.is_file(): raise ConfigNotFoundError(config_path=str(path)) + import yaml + with open(absolute_path, encoding="utf-8") as f: try: file_data = yaml.safe_load(f) @@ -1825,6 +1825,8 @@ def mount( path = Path(from_file) if not path.is_file(): raise ConfigMountError(message=f"Mount file not found: {from_file}") + import yaml + with open(path, encoding="utf-8") as f: try: loaded = yaml.safe_load(f) diff --git a/python/src/apcore/context.py b/python/src/apcore/context.py index 0595596c..168e5fe5 100644 --- a/python/src/apcore/context.py +++ b/python/src/apcore/context.py @@ -15,7 +15,6 @@ if TYPE_CHECKING: from contextlib import AsyncExitStack - from apcore.observability.context_logger import ContextLogger from apcore.trace_context import TraceParent @@ -276,17 +275,6 @@ def bind_executor(self, executor: Any) -> None: raise ContextBindingError("Context already bound to a different Executor instance") # else: same executor instance, noop. - def _bind_executor(self, executor: Any) -> None: - """Deprecated alias for :meth:`bind_executor`. Will be removed in a future major release.""" - import warnings - - warnings.warn( - "Context._bind_executor is deprecated; use Context.bind_executor.", - DeprecationWarning, - stacklevel=2, - ) - self.bind_executor(executor) - def serialize(self) -> dict[str, Any]: """Serialize Context to a JSON-encodable dict. @@ -384,43 +372,6 @@ def deserialize(cls, data: dict[str, Any]) -> Context: cancel_token=None, ) - @property - def logger(self) -> ContextLogger: - """DEPRECATED — use the host application's logger (apcore#121). - - Application and module code SHOULD log through the logger the host - application has already configured. To emit automatic apcore execution - events instead, install ``ObsLoggingMiddleware`` explicitly — that is a - different facility, not a drop-in replacement for ad-hoc logging. - - This property has no configuration door and cannot acquire one without - paying for it somewhere the framework should not: its logger is built - per access from a ``Context``, which carries no ``Config`` in any SDK, - and the only route that avoids threading one through ``Context``'s - pinned six-parameter contract is a process-global logger — which would - end the multi-instance isolation apcore currently gets for free. So the - output is fixed at stderr / ``info`` / JSON, bypassing whatever the host - has configured. Per PROTOCOL_SPEC §9.2.4's D-67 boundary, apcore does - not own the host's logging policy. - - Removed at v2.0. Returns a logger carrying this context's ``trace_id``, - ``module_id`` and ``caller_id`` until then. - """ - import warnings - - warnings.warn( - "Context.logger is deprecated and will be removed in version 2.0. " - "Application and module code SHOULD use the host application's logger; " - "its output is under the host's control, and this one's is not " - "(always stderr, info, JSON). To emit automatic apcore execution events, " - "install ObsLoggingMiddleware explicitly. See apcore#121.", - DeprecationWarning, - stacklevel=2, - ) - from apcore.observability.context_logger import ContextLogger - - return ContextLogger.from_context(self, name=self.caller_id or "unknown") - def child(self, target_module_id: str) -> Context[T]: """Create a child Context for calling a target module. diff --git a/python/src/apcore/discovery.py b/python/src/apcore/discovery.py new file mode 100644 index 00000000..893ad701 --- /dev/null +++ b/python/src/apcore/discovery.py @@ -0,0 +1,7 @@ +"""Explicit entry point for filesystem-backed module discovery and bindings.""" + +from apcore.bindings import BindingLoader +from apcore.registry.registry import Registry +from apcore.registry.scanner import scan_extensions, scan_multi_root + +__all__ = ["BindingLoader", "Registry", "scan_extensions", "scan_multi_root"] diff --git a/python/src/apcore/events/__init__.py b/python/src/apcore/events/__init__.py index 8839cdbe..9466e96d 100644 --- a/python/src/apcore/events/__init__.py +++ b/python/src/apcore/events/__init__.py @@ -1,16 +1,16 @@ """apcore events package. -Re-exports the global event bus and related types:: +Provides the event bus, subscriber factories, and delivery configuration:: from apcore.events import ApCoreEvent, EventSubscriber, EventEmitter - from apcore.events import register_subscriber_factory, create_subscriber_from_config + from apcore.events import SubscriberRegistry """ from apcore.events.circuit_breaker import CircuitBreakerWrapper, CircuitState from apcore.events.emitter import ApCoreEvent, EventEmitter, EventSubscriber +from apcore.events.factory import SubscriberRegistry, create_subscriber_from_config from apcore.events.retry import EventRetryConfig from apcore.events.subscribers import ( - A2ASubscriber, FileSubscriber, FilterSubscriber, StdoutSubscriber, @@ -18,47 +18,17 @@ ) -def register_subscriber_factory(type_name: str, factory): # type: ignore[no-untyped-def] - """Register a custom subscriber-type factory. - - Re-exported from :mod:`apcore.sys_modules.registration` for cross-language - parity with TypeScript (``registerSubscriberType``) and Rust - (``register_subscriber_type``). Lazy-imported to avoid a circular import - at package init time. - """ - from apcore.sys_modules.registration import ( - register_subscriber_factory as _impl, - ) - - return _impl(type_name, factory) - - -def create_subscriber_from_config(config: dict) -> EventSubscriber: # type: ignore[type-arg] - """Build an :class:`EventSubscriber` from a config dict. - - Re-exported from :mod:`apcore.sys_modules.registration` for cross-language - parity with TypeScript (``createSubscriberFromConfig``) and Rust - (``create_subscriber``). - """ - from apcore.sys_modules.registration import ( - create_subscriber_from_config as _impl, - ) - - return _impl(config) - - __all__ = [ "ApCoreEvent", "EventEmitter", "EventSubscriber", + "SubscriberRegistry", "EventRetryConfig", - "A2ASubscriber", "WebhookSubscriber", "FileSubscriber", "StdoutSubscriber", "FilterSubscriber", "CircuitBreakerWrapper", "CircuitState", - "register_subscriber_factory", "create_subscriber_from_config", ] diff --git a/python/src/apcore/events/factory.py b/python/src/apcore/events/factory.py new file mode 100644 index 00000000..0351e9b3 --- /dev/null +++ b/python/src/apcore/events/factory.py @@ -0,0 +1,118 @@ +"""Protocol-neutral subscriber assembly.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +from apcore.events.emitter import EventSubscriber +from apcore.events.retry import EventRetryConfig +from apcore.events.subscribers import ( + FileSubscriber, + FilterSubscriber, + StdoutSubscriber, + WebhookSubscriber, +) + +_Factory = Callable[[dict[str, Any]], EventSubscriber] + + +def _parse_retry_config(cfg: dict[str, Any]) -> EventRetryConfig | None: + """Build an :class:`EventRetryConfig` from a subscriber's nested ``retry:`` block. + + Implements the per-subscriber retry policy documented in + ``docs/features/event-system.md`` §"Per-Subscriber Retry Policy" (apcore#85). + The block is optional and may be partial — omitted keys fall back to the + spec defaults (``max_attempts=3``, ``initial_backoff_ms=100``, + ``max_backoff_ms=30000``, ``backoff_multiplier=2.0``). + + Args: + cfg: Raw subscriber config dict from ``sys_modules.events.subscribers``. + + Returns: + The parsed policy, or ``None`` when no ``retry:`` block is present, so + the subscriber falls back to its own default. + """ + nested = cfg.get("retry") + if not isinstance(nested, dict): + return None + default = EventRetryConfig() + return EventRetryConfig( + max_attempts=int(nested.get("max_attempts", default.max_attempts)), + initial_backoff_ms=int(nested.get("initial_backoff_ms", default.initial_backoff_ms)), + max_backoff_ms=int(nested.get("max_backoff_ms", default.max_backoff_ms)), + backoff_multiplier=float(nested.get("backoff_multiplier", default.backoff_multiplier)), + ) + + +def _default_webhook_factory(cfg: dict[str, Any]) -> EventSubscriber: + retry_cfg = _parse_retry_config(cfg) + # Deprecated: flat retry_count is the legacy webhook-only shorthand. It maps + # to EventRetryConfig.max_attempts + 1 (retry_count counted retries *after* + # the first attempt; max_attempts counts total attempts). The nested retry: + # block wins when both are present (apcore#85). + if retry_cfg is None and "retry_count" in cfg: + retry_cfg = EventRetryConfig(max_attempts=int(cfg["retry_count"]) + 1) + return WebhookSubscriber( + url=cfg["url"], + headers=cfg.get("headers"), + timeout_ms=cfg.get("timeout_ms", 5000), + retry=retry_cfg, + ) + + +def _default_file_factory(cfg: dict[str, Any]) -> EventSubscriber: + return FileSubscriber( + path=cfg["path"], + append=cfg.get("append", True), + output_format=cfg.get("format", "json"), + rotate_bytes=cfg.get("rotate_bytes"), + retry=_parse_retry_config(cfg), + ) + + +def _default_stdout_factory(cfg: dict[str, Any]) -> EventSubscriber: + return StdoutSubscriber( + output_format=cfg.get("format", "text"), + level_filter=cfg.get("level_filter"), + retry=_parse_retry_config(cfg), + ) + + +class SubscriberRegistry: + """Factories selected by one host when assembling its event subscribers.""" + + def __init__(self) -> None: + self._factories: dict[str, _Factory] = { + "webhook": _default_webhook_factory, + "file": _default_file_factory, + "stdout": _default_stdout_factory, + "filter": self._make_filter, + } + + def register(self, type_name: str, factory: _Factory) -> None: + """Add or replace a factory for the named configuration type.""" + self._factories[type_name] = factory + + def create(self, config: dict[str, Any]) -> EventSubscriber: + """Create a subscriber, resolving any nested delegates in this registry.""" + type_name = config.get("type", "") + factory = self._factories.get(type_name) + if factory is None: + registered = ", ".join(sorted(self._factories)) + raise ValueError(f"Unknown subscriber type: {type_name!r}. Registered types: [{registered}].") + return factory(config) + + def _make_filter(self, config: dict[str, Any]) -> EventSubscriber: + delegate_config = {**config.get("delegate_config", {}), "type": config["delegate_type"]} + return FilterSubscriber( + delegate=self.create(delegate_config), + include_events=config.get("include_events"), + exclude_events=config.get("exclude_events"), + retry=_parse_retry_config(config), + ) + + +def create_subscriber_from_config(config: dict[str, Any]) -> EventSubscriber: + """Build a subscriber using the protocol-neutral built-in factories.""" + return SubscriberRegistry().create(config) diff --git a/python/src/apcore/events/subscribers.py b/python/src/apcore/events/subscribers.py index 5fdafb1d..566a5f94 100644 --- a/python/src/apcore/events/subscribers.py +++ b/python/src/apcore/events/subscribers.py @@ -1,4 +1,4 @@ -"""Event subscribers for webhook, A2A, file, stdout, and filter delivery (PRD F9, Issue #36).""" +"""Event subscribers for webhook, file, stdout, and filter delivery (PRD F9, Issue #36).""" from __future__ import annotations @@ -7,11 +7,7 @@ import os import sys from dataclasses import asdict - -try: - import aiohttp # type: ignore[import-not-found] -except ImportError: - aiohttp = None # type: ignore[assignment] +from types import ModuleType from apcore.events.emitter import ApCoreEvent, EventSubscriber from apcore.events.retry import EventRetryConfig @@ -19,7 +15,6 @@ __all__ = [ "WebhookSubscriber", - "A2ASubscriber", "FileSubscriber", "StdoutSubscriber", "FilterSubscriber", @@ -30,6 +25,14 @@ logger = logging.getLogger(__name__) +def _load_aiohttp() -> ModuleType | None: + try: + import aiohttp # type: ignore[import-not-found] + except ImportError: + return None + return aiohttp + + class WebhookSubscriber: """Delivers events via HTTP POST to a webhook URL. @@ -67,6 +70,7 @@ async def on_event(self, event: ApCoreEvent) -> None: can act. 4xx responses are logged as warnings and treated as permanent failures (no retry). """ + aiohttp = _load_aiohttp() if aiohttp is None: raise ImportError("aiohttp is required for WebhookSubscriber. Install with: pip install apcore[events]") @@ -218,63 +222,3 @@ def _matches(self, event_type: str) -> bool: if self._exclude_events is not None: return not any(match_glob(pattern, event_type) for pattern in self._exclude_events) return True - - -class A2ASubscriber: - """Delivers events via the A2A protocol to the platform.""" - - subscriber_type = "a2a" - - def __init__( - self, - platform_url: str, - auth: str | dict[str, str] | None = None, - timeout_ms: int = 5000, - skill_id: str = "apevo.event_receiver", - *, - id: str | None = None, # noqa: A002 - retry: EventRetryConfig | None = None, - event_pattern: str = "*", - ) -> None: - from apcore.events.emitter import _next_subscriber_id - - self._platform_url = platform_url - self._auth = auth - self._timeout_ms = timeout_ms - self._skill_id = skill_id - self.subscriber_id: str = id if id is not None else _next_subscriber_id("a2a") - self.retry: EventRetryConfig = retry if retry is not None else EventRetryConfig() - self.event_pattern: str = event_pattern - - async def on_event(self, event: ApCoreEvent) -> None: - """Send the event to the A2A platform endpoint. - - Raises on 5xx responses and network errors so the emitter's retry loop - can act. 4xx responses are logged as warnings and treated as permanent - failures (no retry). - """ - payload = { - "skillId": self._skill_id, - "event": asdict(event), - } - headers: dict[str, str] = {"Content-Type": "application/json"} - if isinstance(self._auth, str): - headers["Authorization"] = f"Bearer {self._auth}" - elif isinstance(self._auth, dict): - headers.update(self._auth) - - if aiohttp is None: - raise ImportError("aiohttp is required for A2ASubscriber. Install with: pip install apcore[events]") - - timeout = aiohttp.ClientTimeout(total=self._timeout_ms / 1000.0) - async with aiohttp.ClientSession(timeout=timeout) as session: - async with session.post(self._platform_url, json=payload, headers=headers) as response: - if response.status >= 500: - raise RuntimeError(f"A2A delivery to {self._platform_url} failed with status {response.status}") - if response.status >= 400: - logger.warning( - "A2A delivery to %s returned %d for event %s (permanent failure — no retry)", - self._platform_url, - response.status, - event.event_type, - ) diff --git a/python/src/apcore/executor.py b/python/src/apcore/executor.py index f71ae200..a1d72040 100644 --- a/python/src/apcore/executor.py +++ b/python/src/apcore/executor.py @@ -7,19 +7,16 @@ from __future__ import annotations -import asyncio -import atexit import inspect import logging import threading import time -import weakref from collections.abc import AsyncGenerator, AsyncIterator -from concurrent.futures import Future from contextlib import AsyncExitStack, aclosing from copy import copy, deepcopy from typing import TYPE_CHECKING, Any, Callable +from apcore._sync_bridge import _SyncBridge from apcore.acl import ACL from apcore.approval import ApprovalHandler from apcore.builtin_steps import BuiltinContextCreation, BuiltinModuleLookup, _is_idempotent @@ -69,6 +66,7 @@ PipelineTrace, StrategyInfo, StrategyNotFoundError, + _any_match, ) from apcore.registry import MAX_MODULE_ID_LENGTH, MODULE_ID_PATTERN, Registry from apcore.streaming import StreamExecution, _StreamObservation @@ -160,16 +158,6 @@ def _validate_bridge_timeout(timeout_ms: int | None) -> None: raise InvalidInputError(message="Sync bridge timeout must be a non-negative integer in milliseconds") -def _close_if_alive(ref: "weakref.ref[Executor]") -> None: - """atexit callback: close() the Executor if its weakref is still live.""" - obj = ref() - if obj is not None: - try: - obj.close() - except Exception: # pragma: no cover — atexit best-effort - _logger.warning("atexit Executor.close() failed", exc_info=True) - - def _json_type_name(value: Any) -> str: """Return the JSON type name for *value*, matching Rust's ``json_type_name``. @@ -424,18 +412,7 @@ def __init__( message=f"Negative default_timeout: {self._default_timeout}", ) - # Cached event loop for sync call() to avoid asyncio.run() overhead. - # Callers that create many short-lived Executors should call - # close() (or use the `async with` context-manager form) so the loop - # is released deterministically rather than waiting for the GC finalizer. - self._sync_loop: asyncio.AbstractEventLoop | None = None - self._sync_loop_lock = threading.Lock() - self._sync_loop_in_use = False - - # Best-effort cleanup at interpreter shutdown for callers that never - # call close(). Uses a weakref so the atexit callback does not itself - # keep the Executor alive past normal refcount-driven GC. - atexit.register(_close_if_alive, weakref.ref(self)) + self._sync_bridge = _SyncBridge() @classmethod def from_registry( @@ -606,7 +583,7 @@ def set_policy(self, policy: ExecutionPolicy | None) -> None: of the running strategy. Args: - policy: The ExecutionPolicy to apply, or None to remove it. + policy: The ExecutionPolicy to apply, or None to restore the defaults. """ from apcore.builtin_steps import BuiltinApprovalGate @@ -637,18 +614,12 @@ def remove(self, middleware: Middleware) -> bool: return self._middleware_manager.remove(middleware) def close(self) -> None: - """Release the cached sync event loop, if any. + """Release synchronous call resources. - Safe to call multiple times. After ``close()``, a subsequent sync - ``call()`` will lazily create a fresh loop — this method is the - explicit teardown hook for short-lived Executors. An in-flight call - releases its loop when it finishes. + Safe to call multiple times. Later calls create new loops and workers + as needed. In-flight calls release their resources when they finish. """ - with self._sync_loop_lock: - loop = self._sync_loop - self._sync_loop = None - if not self._sync_loop_in_use and loop is not None: - loop.close() + self._sync_bridge.close() def __enter__(self) -> Executor: return self @@ -673,9 +644,9 @@ def call( ) -> dict[str, Any]: """Execute a module through the execution pipeline. - Sync wrapper around :meth:`call_async`. Routes through a cached event - loop when available. Concurrent sync callers and callers inside a - running loop use an independent thread bridge. + Sync wrapper around :meth:`call_async`. Each thread caches its own + loop for synchronous calls. A call made inside a running loop uses a + bounded worker pool instead. Args: module_id: The module to execute. @@ -689,7 +660,7 @@ def call( The module output dict, possibly modified by middleware. """ bridge_wait = self._sync_bridge_wait(context, timeout_ms) - return self._run_async_in_sync( + return self._sync_bridge.run( self.call_async(module_id, inputs, context, version_hint), module_id, bridge_wait, @@ -729,43 +700,6 @@ def _sync_bridge_wait( wait = remaining + _SYNC_BRIDGE_GRACE_SECONDS return wait if wait <= threading.TIMEOUT_MAX else None - def _run_async_in_sync(self, coro: Any, module_id: str, bridge_wait: float | None) -> Any: - """Execute a coroutine from sync context using a cached loop or thread bridge. - - Centralizes the loop-detection logic shared by ``call``, ``validate``, - and ``call_with_trace``. Inside an existing event loop, dispatches to a - background thread; otherwise uses (and creates if needed) the cached - ``_sync_loop``. - """ - try: - asyncio.get_running_loop() - inside_loop = True - except RuntimeError: - inside_loop = False - - if inside_loop: - return self._run_in_new_thread(coro, module_id, bridge_wait) - - # Reserve the cached loop before releasing the lock. Checking - # is_running() alone races with run_until_complete() on another thread. - with self._sync_loop_lock: - loop = None - if not self._sync_loop_in_use: - if self._sync_loop is None or self._sync_loop.is_closed(): - self._sync_loop = asyncio.new_event_loop() - loop = self._sync_loop - self._sync_loop_in_use = True - - if loop is None: - return self._run_in_new_thread(coro, module_id, bridge_wait) - try: - return loop.run_until_complete(coro) - finally: - with self._sync_loop_lock: - self._sync_loop_in_use = False - if self._sync_loop is not loop: - loop.close() - def validate( self, module_id: str, @@ -792,7 +726,7 @@ def validate( PreflightResult with per-check status. """ bridge_wait = self._sync_bridge_wait(context, timeout_ms) - return self._run_async_in_sync( + return self._sync_bridge.run( self.validate_async(module_id, inputs, context, version_hint=version_hint), module_id, bridge_wait, @@ -916,27 +850,25 @@ async def validate_async( requires_approval = annotations.requires_approval elif isinstance(annotations, dict): requires_approval = bool(annotations.get("requires_approval", False)) - if self._policy is not None: - # Policy overrides win over declared annotations (apcore#76), - # so preflight reports the same verdict the gate will enforce. - # The call site travels here too (PROTOCOL_SPEC §7.9.6), so a - # host-supplied policy reports in preflight the same verdict it - # will enforce at the gate. - # §7.9.6 rule 5 — strip the framework-owned approval token - # before resolution. `ExecutionPolicy.resolve` strips it too, - # which covers every door into the built-in rules; it cannot - # cover this one, because the surface the rule protects is a - # host policy that OVERRIDES `resolve` (the method's own - # docstring names that as how a host consults the call site), - # and such an override is entered before any strip inside the - # base implementation runs. The pipeline separates the incoming - # credential at entry, even when it skips Step 5. - requires_approval = self._policy.resolve( - module_id, - annotations, - arguments=strip_approval_token(pipe_ctx.inputs), - context=pipe_ctx.context, - ).needs_approval + from apcore.builtin_steps import BuiltinApprovalGate + + policies = [ + step.policy + for step in self._strategy.steps + if isinstance(step, BuiltinApprovalGate) + and (step.match_modules is None or _any_match(step.match_modules, module_id)) + ] + if not policies and self._policy is not None: + policies = [self._policy] + if policies: + # Evaluate the same policy providers as the invocation gate, + # including policies attached to a prebuilt strategy. A host's + # custom resolver must never see the resume credential. + arguments = strip_approval_token(pipe_ctx.inputs) + requires_approval = any( + policy.resolve(module_id, annotations, arguments=arguments, context=pipe_ctx.context).needs_approval + for policy in policies + ) # PROTOCOL_SPEC §7.9.5: report the GOVERNANCE-effective requirement — # the union of §6.9 rows 3-5 — and not merely the policy-effective one. @@ -1090,58 +1022,6 @@ def _translate_abort(self, abort: PipelineAbortError) -> ModuleError: # Fallback: return as ModuleError return ModuleError(code="PIPELINE_ABORT", message=explanation) - def _run_in_new_thread(self, coro: Any, module_id: str, timeout_s: float | None) -> Any: - """Wait for a worker loop independently of pipeline execution timeouts.""" - result: Future[Any] = Future() - expired = threading.Event() - worker: tuple[asyncio.AbstractEventLoop, asyncio.Task[Any]] | None = None - - def thread_target() -> None: - nonlocal worker - try: - loop = asyncio.new_event_loop() - except BaseException as exc: - coro.close() - result.set_exception(exc) - return - try: - task = loop.create_task(coro) - worker = loop, task - if expired.is_set(): - task.cancel() - result.set_result(loop.run_until_complete(task)) - except BaseException as exc: - result.set_exception(exc) - finally: - # Let cooperative work drain after publishing the outcome. - pending = asyncio.all_tasks(loop) - if pending: - loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True)) - loop.close() - - thread = threading.Thread(target=thread_target, daemon=True) - try: - thread.start() - except BaseException: - coro.close() - raise - try: - return result.result(timeout_s) - except TimeoutError: - if result.done() or timeout_s is None: - return result.result() - - expired.set() - if worker is not None: - loop, task = worker - try: - loop.call_soon_threadsafe(task.cancel) - except RuntimeError: - # The worker finished between the wait and the cancellation. - pass - _logger.warning("Sync bridge wait expired for module %s", module_id) - raise ModuleTimeoutError(module_id=module_id, timeout_ms=round(timeout_s * 1000), retryable=False) - async def call_async( self, module_id: str, @@ -1691,7 +1571,7 @@ def call_with_trace( A tuple of (result dict, PipelineTrace). """ bridge_wait = self._sync_bridge_wait(context, timeout_ms, strategy) - return self._run_async_in_sync( + return self._sync_bridge.run( self.call_async_with_trace(module_id, inputs, context, version_hint=version_hint, strategy=strategy), module_id, bridge_wait, @@ -1810,7 +1690,7 @@ def ungated_approval_modules(self) -> list[str]: step for step in self._strategy.steps if isinstance(step, BuiltinApprovalGate) - and (step.handler is not None or (step.policy is not None and step.policy.strict)) + and (step.handler is not None or step.policy.strict) ] ungated: list[str] = [] for module_id in self._registry.list(visibility=["public", "hidden"]): @@ -1818,7 +1698,7 @@ def ungated_approval_modules(self) -> list[str]: if annotations is None or not annotations.requires_approval: continue if not any( - gate.policy is None or gate.policy.resolve(module_id, annotations).needs_approval + gate.policy.resolve(module_id, annotations).needs_approval for gate in enforcing_gates ): ungated.append(module_id) @@ -1887,9 +1767,7 @@ def governance_state(self) -> GovernanceState: acl_configured = self._acl is not None if approval_gates: handler_configured = any(gate.handler is not None for gate in approval_gates) - policy_strict = any( - gate.policy is not None and bool(getattr(gate.policy, "strict", False)) for gate in approval_gates - ) + policy_strict = any(gate.policy.strict for gate in approval_gates) else: handler_configured = self._approval_handler is not None policy_strict = self._policy is not None and bool(getattr(self._policy, "strict", False)) diff --git a/python/src/apcore/full.py b/python/src/apcore/full.py new file mode 100644 index 00000000..9db0344c --- /dev/null +++ b/python/src/apcore/full.py @@ -0,0 +1,8 @@ +"""Full runtime assembly for applications using configuration and discovery.""" + +from apcore.acl import ACL +from apcore.client import APCore +from apcore.config import Config +from apcore.discovery import Registry + +__all__ = ["ACL", "APCore", "Config", "Registry"] diff --git a/python/src/apcore/observability/__init__.py b/python/src/apcore/observability/__init__.py index 801d5603..9c11f8ef 100644 --- a/python/src/apcore/observability/__init__.py +++ b/python/src/apcore/observability/__init__.py @@ -9,7 +9,7 @@ MetricsCollector, MetricsMiddleware, ErrorHistory, ErrorEntry, ObservabilityStore, InMemoryObservabilityStore, - PrometheusExporter, + render_prometheus_metrics, ) Recommended middleware registration order (outermost to innermost): @@ -34,7 +34,7 @@ MetricsMiddleware, estimate_p99_latency_ms, ) -from apcore.observability.prometheus_exporter import PrometheusExporter, render_prometheus_metrics +from apcore.observability.prometheus_exporter import render_prometheus_metrics from apcore.observability.storage import ( InMemoryStorageBackend, StorageBackend, @@ -82,7 +82,6 @@ "ObservabilityStore", "OTLPExporter", "PeriodicUsageExporter", - "PrometheusExporter", "render_prometheus_metrics", "StorageBackend", "RedactionConfig", diff --git a/python/src/apcore/observability/prometheus_exporter.py b/python/src/apcore/observability/prometheus_exporter.py index 5e168013..7a60a5f7 100644 --- a/python/src/apcore/observability/prometheus_exporter.py +++ b/python/src/apcore/observability/prometheus_exporter.py @@ -1,71 +1,14 @@ -"""Prometheus text-format exporter with /metrics, /healthz, and /readyz HTTP endpoints.""" +"""Render application metrics in Prometheus text format.""" from __future__ import annotations -import logging -import threading -import time -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from io import BufferedReader, RawIOBase from typing import TYPE_CHECKING if TYPE_CHECKING: - from socket import socket - - from _typeshed import WriteableBuffer - from apcore.observability.metrics import MetricsCollector from apcore.observability.usage import UsageCollector - _ServerRequest = socket | tuple[bytes, socket] - -_logger = logging.getLogger(__name__) -_MAX_CONCURRENT_CONNECTIONS = 64 -_REQUEST_READ_TIMEOUT = 10.0 -_RESPONSE_WRITE_TIMEOUT = 10.0 - - -class _RequestReader(RawIOBase): - """Read the complete HTTP request headers within one deadline.""" - - def __init__(self, connection: socket) -> None: - self._connection = connection - self._deadline = time.monotonic() + _REQUEST_READ_TIMEOUT - - def readable(self) -> bool: - return True - - def readinto(self, buffer: WriteableBuffer, /) -> int: - remaining = self._deadline - time.monotonic() - if remaining <= 0: - raise TimeoutError("Prometheus request headers timed out") - self._connection.settimeout(remaining) - try: - return self._connection.recv_into(buffer) - finally: - self._connection.settimeout(_RESPONSE_WRITE_TIMEOUT) - - -class _PrometheusHTTPServer(ThreadingHTTPServer): - def __init__(self, address: tuple[str, int], handler: type[BaseHTTPRequestHandler]) -> None: - self._slots = threading.BoundedSemaphore(_MAX_CONCURRENT_CONNECTIONS) - super().__init__(address, handler) - - def process_request(self, request: _ServerRequest, client_address: tuple[str, int]) -> None: - if not self._slots.acquire(blocking=False): - self.shutdown_request(request) - return - try: - super().process_request(request, client_address) - except BaseException: - self._slots.release() - raise - - def process_request_thread(self, request: _ServerRequest, client_address: tuple[str, int]) -> None: - try: - super().process_request_thread(request, client_address) - finally: - self._slots.release() +__all__ = ["render_prometheus_metrics"] def render_prometheus_metrics(collector: MetricsCollector, usage_collector: UsageCollector | None = None) -> str: @@ -74,115 +17,3 @@ def render_prometheus_metrics(collector: MetricsCollector, usage_collector: Usag if usage_collector is not None: output += usage_collector.export_prometheus() return output - - -class PrometheusExporter: - """Serves Prometheus text metrics and health endpoints over HTTP. - - Starts a background HTTP server on ``start()``. Serves: - GET /metrics (or configured path) — Prometheus text exposition format - GET /healthz — liveness probe, always 200 OK - GET /readyz — readiness probe, 200 OK after ``mark_ready()`` is called - - Args: - collector: The MetricsCollector to read metrics from. - usage_collector: Optional UsageCollector. When provided, its - ``apcore_usage_*`` metric families are appended to the /metrics - output (parity with the TS and Rust exporters). Defaults to None, - which preserves the previous MetricsCollector-only behavior. - """ - - def __init__(self, collector: MetricsCollector, usage_collector: UsageCollector | None = None) -> None: - self._collector = collector - self._usage_collector = usage_collector - self._server: _PrometheusHTTPServer | None = None - self._thread: threading.Thread | None = None - self._listener_lock = threading.Lock() - self._ready = False - self._ready_lock = threading.Lock() - - def export(self) -> str: - """Return current metrics in Prometheus text format. - - Appends the usage collector's ``apcore_usage_*`` families when a usage - collector was supplied at construction. - """ - return render_prometheus_metrics(self._collector, self._usage_collector) - - def mark_ready(self) -> None: - """Signal that the application is ready to serve traffic.""" - with self._ready_lock: - self._ready = True - - def start(self, port: int = 9090, path: str = "/metrics", *, host: str = "127.0.0.1") -> None: - """Start the HTTP server in a background daemon thread, bound to ``host``. - - Raises: - RuntimeError: If the server is already running. Call ``stop()`` first. - """ - exporter = self - - class _Handler(BaseHTTPRequestHandler): - def setup(self) -> None: - super().setup() - self.rfile.close() - self.rfile = BufferedReader(_RequestReader(self.connection)) - self.connection.settimeout(_RESPONSE_WRITE_TIMEOUT) - - def do_GET(self) -> None: # noqa: N802 - if self.path == path: - body = exporter.export().encode("utf-8") - self.send_response(200) - self.send_header("Content-Type", "text/plain; version=0.0.4; charset=utf-8") - self.send_header("Content-Length", str(len(body))) - self.end_headers() - self.wfile.write(body) - elif self.path == "/healthz": - self.send_response(200) - self.end_headers() - self.wfile.write(b"OK") - elif self.path == "/readyz": - with exporter._ready_lock: - ready = exporter._ready - if ready: - self.send_response(200) - self.end_headers() - self.wfile.write(b"OK") - else: - self.send_response(503) - self.end_headers() - self.wfile.write(b"Not ready") - else: - self.send_response(404) - self.end_headers() - - def log_message(self, fmt: str, *args: object) -> None: # type: ignore[override] - pass # suppress access logs - - with self._listener_lock: - if self._server is not None: - raise RuntimeError("PrometheusExporter is already running. Call stop() before start().") - server = _PrometheusHTTPServer((host, port), _Handler) - thread = threading.Thread(target=server.serve_forever, daemon=True) - try: - thread.start() - except RuntimeError: - server.server_close() - raise - self._server = server - self._thread = thread - _logger.info("PrometheusExporter listening at %s:%d path=%s", *server.server_address, path) - - def stop(self) -> None: - """Stop accepting new connections and release the listening socket.""" - with self._listener_lock: - if self._server is None or self._thread is None: - return - self._server.shutdown() - self._thread.join() - self._server.server_close() - self._server = None - self._thread = None - - -__all__ = ["PrometheusExporter", "render_prometheus_metrics"] diff --git a/python/src/apcore/observability/usage_exporter.py b/python/src/apcore/observability/usage_exporter.py index 6c19b3b9..b750e2a1 100644 --- a/python/src/apcore/observability/usage_exporter.py +++ b/python/src/apcore/observability/usage_exporter.py @@ -2,7 +2,7 @@ The original observability RFC (#45 §3) committed to a push-style exporter that delivers hourly :class:`UsageCollector` summaries to external sinks -(HTTP, Kafka, custom backends). The pull-style :class:`PrometheusExporter` +(HTTP, Kafka, custom backends). The pull-style :func:`render_prometheus_metrics` covers scrape-based collection; this module covers the complementary push path so operators can stream usage data into log pipelines or analytics systems without standing up a Prometheus scrape target. diff --git a/python/src/apcore/policy.py b/python/src/apcore/policy.py index 4fd64dce..15ace94b 100644 --- a/python/src/apcore/policy.py +++ b/python/src/apcore/policy.py @@ -137,8 +137,8 @@ def _require_bool(value: Any, key: str) -> bool: accident. §7.9.4 already makes ``from_dict`` fail loud on unknown keys; this extends the same discipline to the values. - ``None`` (and an absent key) mean "unset" and take the documented default of - ``False`` rather than raising — parity with apcore-typescript. + ``None`` (and an absent key) mean "unset" and take the fail-closed default of + ``True`` rather than raising — parity with apcore-typescript. Note ``bool`` is checked before ``int``: ``True`` is an ``int`` in Python, so an ``isinstance(value, int)`` test would accept ``1`` and ``0`` as flags. @@ -147,7 +147,7 @@ def _require_bool(value: Any, key: str) -> bool: ValueError: When *value* is neither None nor a bool. """ if value is None: - return False + return True if not isinstance(value, bool): raise ValueError( f"Policy key '{key}' must be a boolean, got {type(value).__name__} ({value!r}); " @@ -191,8 +191,8 @@ def __init__( self, rules: list[PolicyRule] | None = None, *, - gate_destructive: bool = False, - strict: bool = False, + gate_destructive: bool = True, + strict: bool = True, ) -> None: self._rules: tuple[PolicyRule, ...] = tuple(rules or ()) for rule in self._rules: diff --git a/python/src/apcore/registry/metadata.py b/python/src/apcore/registry/metadata.py index 64348f7f..756b384b 100644 --- a/python/src/apcore/registry/metadata.py +++ b/python/src/apcore/registry/metadata.py @@ -8,8 +8,6 @@ from pathlib import Path from typing import Any -import yaml - from apcore.errors import ConfigError, ConfigNotFoundError from apcore.module import ModuleAnnotations from apcore.registry.types import DependencyInfo @@ -33,6 +31,8 @@ def load_metadata(meta_path: Path) -> dict[str, Any]: if not meta_path.exists(): return {} + import yaml + content = meta_path.read_text(encoding="utf-8") try: parsed = yaml.safe_load(content) @@ -177,6 +177,8 @@ def load_id_map(id_map_path: str | os.PathLike[str]) -> dict[str, dict[str, Any] Raises ConfigNotFoundError if file does not exist (ID map is explicitly requested). """ + import yaml + try: with open(id_map_path, encoding="utf-8") as source: parsed = yaml.safe_load(source) diff --git a/python/src/apcore/registry/registry.py b/python/src/apcore/registry/registry.py index 86cd1fcb..35ad15b4 100644 --- a/python/src/apcore/registry/registry.py +++ b/python/src/apcore/registry/registry.py @@ -1851,7 +1851,6 @@ def list( prefix: str | None = None, *, visibility: list[str] | None = None, - include_hidden: bool | None = None, ) -> list[str]: """Return sorted list of unique registered module IDs, optionally filtered. @@ -1862,16 +1861,11 @@ def list( visibility: Filter by module visibility. Supported: ``["public", "hidden"]``. Defaults to ``["public"]``. Pass ``["public", "hidden"]`` to see all modules (protocol-spec §4.4 ``discoverable``). - include_hidden: Deprecated. Use ``visibility=["public", "hidden"]`` instead. """ - # protocol-spec §4.4 discoverable: the visibility list takes precedence over the legacy include_hidden bool. if visibility is not None: vis = set(visibility) show_public = "public" in vis show_hidden = "hidden" in vis - elif include_hidden is True: - show_public = True - show_hidden = True else: # Default per protocol-spec §4.4 discoverable: public only. show_public = True @@ -1937,7 +1931,7 @@ def module_ids(self) -> list[str]: """Sorted list of registered module IDs (excludes ``discoverable=False`` modules). Modules annotated ``discoverable=False`` (per the apcore RFC pilot) - are filtered out. Use :meth:`list` with ``include_hidden=True`` when + are filtered out. Use :meth:`list` with ``visibility=["public", "hidden"]`` when the full set is required. """ with self._lock: diff --git a/python/src/apcore/registry/schema_export.py b/python/src/apcore/registry/schema_export.py index ac56c8f0..dbd6dd44 100644 --- a/python/src/apcore/registry/schema_export.py +++ b/python/src/apcore/registry/schema_export.py @@ -7,13 +7,9 @@ import json from typing import TYPE_CHECKING, Any -import yaml - from apcore.errors import ModuleNotFoundError from apcore.module import ModuleAnnotations, ModuleExample -from apcore.schema.exporter import SchemaExporter from apcore.schema.strict import _strip_extensions, to_strict_schema -from apcore.schema.types import ExportProfile, SchemaDefinition if TYPE_CHECKING: from apcore.registry.registry import Registry @@ -58,7 +54,6 @@ def export_schema( format: str = "json", strict: bool = False, compact: bool = False, - profile: str | None = None, ) -> str: """Export a single module's schema as a JSON or YAML string. @@ -68,9 +63,6 @@ def export_schema( if schema_dict is None: raise ModuleNotFoundError(module_id=module_id) - if profile is not None: - return _export_with_profile(registry, module_id, schema_dict, profile, format) - result = copy.deepcopy(schema_dict) if strict: @@ -97,7 +89,6 @@ def export_all_schemas( format: str = "json", strict: bool = False, compact: bool = False, - profile: str | None = None, ) -> str: """Export all module schemas as a combined JSON or YAML string.""" all_schemas = get_all_schemas(registry) @@ -118,36 +109,6 @@ def export_all_schemas( # ----- Helpers ----- -def _export_with_profile( - registry: Registry, - module_id: str, - schema_dict: dict[str, Any], - profile: str, - format: str, -) -> str: - """Export using SchemaExporter with a specific profile.""" - schema_def = SchemaDefinition( - module_id=module_id, - description=schema_dict["description"], - input_schema=schema_dict["input_schema"], - output_schema=schema_dict["output_schema"], - definitions={}, - ) - module = registry.get(module_id) - annotations = getattr(module, "annotations", None) if module else None - examples = getattr(module, "examples", []) if module else [] - name = getattr(module, "name", None) if module else None - - exported = SchemaExporter().export( - schema_def, - profile=ExportProfile(profile), - annotations=annotations, - examples=examples, - name=name, - ) - return _serialize(exported, format) - - def _apply_compact(schema_dict: dict[str, Any]) -> None: """Apply compact mode transformations in place.""" # Truncate description @@ -185,5 +146,7 @@ def _truncate_description(description: str) -> str: def _serialize(data: Any, format: str) -> str: """Serialize data to JSON or YAML string.""" if format == "yaml": + import yaml + return yaml.dump(data, default_flow_style=False) return json.dumps(data, indent=2) diff --git a/python/src/apcore/schema/__init__.py b/python/src/apcore/schema/__init__.py index 3e18f1e4..76a4c36b 100644 --- a/python/src/apcore/schema/__init__.py +++ b/python/src/apcore/schema/__init__.py @@ -4,7 +4,7 @@ Example usage:: - from apcore.schema import SchemaLoader, SchemaValidator, ExportProfile + from apcore.schema import SchemaLoader, SchemaValidator, SchemaExporter from apcore.schema import to_strict_schema, merge_annotations """ @@ -25,7 +25,6 @@ from apcore.schema.ref_resolver import RefResolver from apcore.schema.strict import to_strict_schema from apcore.schema.types import ( - ExportProfile, LLMExtensions, ResolvedSchema, SchemaDefinition, @@ -37,7 +36,6 @@ __all__ = [ "SchemaStrategy", - "ExportProfile", "SchemaDefinition", "ResolvedSchema", "SchemaValidationResult", diff --git a/python/src/apcore/schema/exporter.py b/python/src/apcore/schema/exporter.py index 2ee1910b..94adb86a 100644 --- a/python/src/apcore/schema/exporter.py +++ b/python/src/apcore/schema/exporter.py @@ -1,101 +1,16 @@ -"""SchemaExporter — converts schemas to platform-specific export formats.""" +"""SchemaExporter — exports protocol-neutral module schemas.""" from __future__ import annotations -import copy from typing import Any -from apcore.module import ModuleAnnotations, ModuleExample -from apcore.schema.strict import ( - _apply_llm_descriptions, - _strip_extensions, - to_strict_schema, -) -from apcore.schema.types import ExportProfile, SchemaDefinition +from apcore.schema.types import SchemaDefinition __all__ = ["SchemaExporter"] class SchemaExporter: - """Stateless transformer that exports schemas in platform-specific formats.""" - - def export( - self, - schema_def: SchemaDefinition, - profile: ExportProfile, - annotations: ModuleAnnotations | None = None, - examples: list[ModuleExample] | None = None, - name: str | None = None, - ) -> dict[str, Any]: - """Export schema in the specified profile format.""" - if profile == ExportProfile.MCP: - return self.export_mcp(schema_def, annotations=annotations, name=name) - if profile == ExportProfile.OPENAI: - return self.export_openai(schema_def) - if profile == ExportProfile.ANTHROPIC: - return self.export_anthropic(schema_def, examples=examples) - return self.export_generic(schema_def) - - def export_mcp( - self, - schema_def: SchemaDefinition, - annotations: ModuleAnnotations | None = None, - name: str | None = None, - ) -> dict[str, Any]: - """Export in MCP format. Preserves x-* fields and uses dot-notation IDs.""" - return { - "name": name if name is not None else schema_def.module_id, - "description": schema_def.description, - "inputSchema": schema_def.input_schema, - "annotations": { - "readOnlyHint": annotations.readonly if annotations else False, - "destructiveHint": annotations.destructive if annotations else False, - "idempotentHint": annotations.idempotent if annotations else False, - "openWorldHint": annotations.open_world if annotations else True, - }, - "_meta": { - "cacheable": annotations.cacheable if annotations else False, - "cacheTtl": annotations.cache_ttl if annotations else 0, - "cacheKeyFields": annotations.cache_key_fields if annotations else None, - "paginated": annotations.paginated if annotations else False, - "paginationStyle": annotations.pagination_style if annotations else "cursor", - **({"requiresApproval": True} if annotations and annotations.requires_approval else {}), - **({"streaming": True} if annotations and annotations.streaming else {}), - }, - } - - def export_openai(self, schema_def: SchemaDefinition) -> dict[str, Any]: - """Export in OpenAI function calling format with strict mode.""" - schema = copy.deepcopy(schema_def.input_schema) - _apply_llm_descriptions(schema) - strict_schema = to_strict_schema(schema) - return { - "type": "function", - "function": { - "name": schema_def.module_id.replace(".", "_"), - "description": schema_def.description, - "parameters": strict_schema, - "strict": True, - }, - } - - def export_anthropic( - self, - schema_def: SchemaDefinition, - examples: list[ModuleExample] | None = None, - ) -> dict[str, Any]: - """Export in Anthropic tool use format. Strips extensions but no strict mode.""" - schema = copy.deepcopy(schema_def.input_schema) - _apply_llm_descriptions(schema) - _strip_extensions(schema, strip_defaults=False) - result: dict[str, Any] = { - "name": schema_def.module_id.replace(".", "_"), - "description": schema_def.description, - "input_schema": schema, - } - if examples: - result["input_examples"] = [ex.inputs for ex in examples] - return result + """Stateless exporter for protocol-neutral module schemas.""" def export_generic( self, diff --git a/python/src/apcore/schema/loader.py b/python/src/apcore/schema/loader.py index d449daed..e7d1aa7b 100644 --- a/python/src/apcore/schema/loader.py +++ b/python/src/apcore/schema/loader.py @@ -10,7 +10,6 @@ from pathlib import Path from typing import Annotated, Any, ClassVar, Literal, Union, cast -import yaml from jsonschema import Draft202012Validator from jsonschema.exceptions import SchemaError as JsonSchemaError from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator @@ -557,6 +556,8 @@ def load(self, module_id: str) -> SchemaDefinition: if not file_path.exists(): raise SchemaNotFoundError(schema_id=module_id) + import yaml + try: data = yaml.safe_load(file_path.read_text()) except yaml.YAMLError as e: diff --git a/python/src/apcore/schema/ref_resolver.py b/python/src/apcore/schema/ref_resolver.py index f2c8c0b6..1b8d3f1a 100644 --- a/python/src/apcore/schema/ref_resolver.py +++ b/python/src/apcore/schema/ref_resolver.py @@ -6,8 +6,6 @@ from pathlib import Path from typing import Any -import yaml - from apcore.errors import ( InvalidInputError, SchemaCircularRefError, @@ -308,6 +306,8 @@ def _load_file(self, file_path: Path) -> dict[str, Any]: self._file_cache[file_path] = {} return {} + import yaml + try: parsed = yaml.safe_load(content) except yaml.YAMLError as e: diff --git a/python/src/apcore/schema/strict.py b/python/src/apcore/schema/strict.py index ecf47e6c..221c348d 100644 --- a/python/src/apcore/schema/strict.py +++ b/python/src/apcore/schema/strict.py @@ -7,7 +7,7 @@ def to_strict_schema(schema: dict[str, Any]) -> dict[str, Any]: - """Convert a JSON Schema to OpenAI/Anthropic Strict Mode format. + """Convert a JSON Schema to strict mode. Deep-copies the input, strips extensions and defaults, then enforces strict mode rules (additionalProperties: false, all properties required, @@ -19,36 +19,6 @@ def to_strict_schema(schema: dict[str, Any]) -> dict[str, Any]: return result -def _apply_llm_descriptions(node: Any) -> None: - """Replace description with x-llm-description where present. - - Mutates the node in place. Called by exporters before to_strict_schema(). - """ - if not isinstance(node, dict): - return - - if "x-llm-description" in node and "description" in node: - node["description"] = node["x-llm-description"] - - # Recurse into nested structures - if "properties" in node and isinstance(node["properties"], dict): - for prop in node["properties"].values(): - _apply_llm_descriptions(prop) - if "items" in node and isinstance(node["items"], dict): - _apply_llm_descriptions(node["items"]) - if "prefixItems" in node and isinstance(node["prefixItems"], list): - for item in node["prefixItems"]: - _apply_llm_descriptions(item) - for keyword in ("oneOf", "anyOf", "allOf"): - if keyword in node and isinstance(node[keyword], list): - for sub in node[keyword]: - _apply_llm_descriptions(sub) - for defs_key in ("definitions", "$defs"): - if defs_key in node and isinstance(node[defs_key], dict): - for defn in node[defs_key].values(): - _apply_llm_descriptions(defn) - - def _strip_extensions(node: Any, *, strip_defaults: bool = True, _names: bool = False) -> None: """Remove x-* schema keywords, preserving named properties and data values. diff --git a/python/src/apcore/schema/types.py b/python/src/apcore/schema/types.py index 2bd78c5a..ff763e6e 100644 --- a/python/src/apcore/schema/types.py +++ b/python/src/apcore/schema/types.py @@ -13,7 +13,6 @@ __all__ = [ "SchemaStrategy", - "ExportProfile", "SchemaDefinition", "ResolvedSchema", "SchemaValidationErrorDetail", @@ -43,15 +42,6 @@ class SchemaStrategy(str, Enum): YAML_ONLY = "yaml_only" -class ExportProfile(str, Enum): - """Determines which export format to use.""" - - MCP = "mcp" - OPENAI = "openai" - ANTHROPIC = "anthropic" - GENERIC = "generic" - - @dataclass class SchemaDefinition: """Represents a parsed *.schema.yaml file before $ref resolution.""" diff --git a/python/src/apcore/sys_modules/control.py b/python/src/apcore/sys_modules/control.py index d9da0228..34827e37 100644 --- a/python/src/apcore/sys_modules/control.py +++ b/python/src/apcore/sys_modules/control.py @@ -374,6 +374,7 @@ class ReloadModule: annotations = ModuleAnnotations(requires_approval=True, destructive=False, idempotent=False, open_world=False) input_schema: dict[str, Any] = { "type": "object", + "additionalProperties": False, "properties": { "module_id": { "type": "string", @@ -383,19 +384,6 @@ class ReloadModule: "type": "string", "description": "Glob pattern for bulk reload (mutually exclusive with module_id)", }, - "reload_dependents": { - "type": "boolean", - "description": ( - "DEPRECATED (spec v1.51.0, D-121) — ignored, and removed at 2.0. " - "Declared in all three SDKs and implemented by none, so no caller " - "could ever rely on it. Use an explicit `path_filter` that also " - "matches the dependents. At 2.0 this field is REMOVED and, because " - "this schema sets additionalProperties: false, passing it becomes a " - "validation error rather than a silent no-op." - ), - "default": False, - "deprecated": True, - }, "reason": {"type": "string", "description": "Audit reason for the reload"}, "lifecycle": { "type": "object", @@ -476,44 +464,11 @@ def __init__( self._registry = registry self._emitter = event_emitter self._audit_store = audit_store - self._reload_dependents_warned = False - - # Once per INSTANCE, not per process. `reload` is called by hot-reload loops - # and watchers, so an advisory whose volume is proportional to traffic is one - # operators learn to filter out — the cadence reasoning D-89 settled. Per - # instance rather than per process for the reason D-90's notice is per token: - # a process-wide one-shot tells the first caller and leaves every later one - # to discover it in production. - def _warn_reload_dependents(self, inputs: dict[str, Any]) -> None: - """Warn once that ``reload_dependents`` is ignored and will be removed (D-121). - - The field was declared in all three SDKs' input schemas and read by - none — a spec MUST that no implementation satisfied, which is the - §9.1.3 "declared surface reaches no mechanism" shape applied to a module - input field. Three independent implementations skipping it is the - evidence the maintainer decision rests on. - - Deprecated rather than removed now, because the input schema sets - ``additionalProperties: false``: at 2.0 the same call stops being a - silent no-op and becomes a validation error, so a caller passing it - today needs a release in which they are told. - """ - if not inputs.get("reload_dependents"): - return - if self._reload_dependents_warned: - return - self._reload_dependents_warned = True - logger.warning( - "system.control.reload: 'reload_dependents' is ignored and will be removed at 2.0 " - "(spec D-121). No SDK has ever implemented it. Use a 'path_filter' that also matches " - "the dependents; after removal this field becomes a validation error, not a no-op." - ) def execute(self, inputs: dict[str, Any], context: Any) -> dict[str, Any]: """Reload one or more modules. Raises ModuleReloadConflictError if both module_id and path_filter are given. - ``reload_dependents`` is accepted and ignored — see :meth:`_warn_reload_dependents`. """ if "lifecycle" in inputs: try: @@ -526,7 +481,6 @@ def execute(self, inputs: dict[str, Any], context: Any) -> dict[str, Any]: return result(operation._join_blocking()) module_id: Any = inputs.get("module_id") path_filter: Any = inputs.get("path_filter") - self._warn_reload_dependents(inputs) reason = self._validate_reason(inputs) if module_id is not None and path_filter is not None: @@ -558,7 +512,6 @@ async def _execute_managed(self, inputs: dict[str, Any], context: Any) -> dict[s def _start_managed( self, inputs: dict[str, Any], context: Any ) -> tuple[LifecycleOperation, Callable[[LifecycleReport], dict[str, Any]]]: - self._warn_reload_dependents(inputs) reason = self._validate_reason(inputs) module_id, path_filter = inputs.get("module_id"), inputs.get("path_filter") if module_id is not None and path_filter is not None: diff --git a/python/src/apcore/sys_modules/health.py b/python/src/apcore/sys_modules/health.py index f1e8e8d6..84a6c232 100644 --- a/python/src/apcore/sys_modules/health.py +++ b/python/src/apcore/sys_modules/health.py @@ -75,7 +75,15 @@ class HealthSummaryModule: output_schema: dict[str, Any] = { "type": "object", "properties": { - "project": {"type": "object", "description": "Project information"}, + "project": { + "type": "object", + "description": "Project information", + "properties": { + "name": {"type": "string", "description": "Project name"}, + "version": {"type": "string", "description": "Configured project version"}, + }, + "required": ["name"], + }, "summary": { "type": "object", "description": "Aggregated health counts by status", @@ -114,7 +122,6 @@ def execute(self, inputs: dict[str, Any], context: Any) -> dict[str, Any]: degraded_threshold = _DEFAULT_DEGRADED_THRESHOLD include_healthy: bool = inputs.get("include_healthy", True) - project_name = self._get_project_name() module_ids = self._registry.list() modules_output: list[dict[str, Any]] = [] @@ -140,7 +147,7 @@ def execute(self, inputs: dict[str, Any], context: Any) -> dict[str, Any]: ) return { - "project": {"name": project_name}, + "project": self._get_project_details(), "summary": { "total_modules": len(module_ids), **counts, @@ -152,13 +159,15 @@ def execute(self, inputs: dict[str, Any], context: Any) -> dict[str, Any]: # Private helpers # ------------------------------------------------------------------ - def _get_project_name(self) -> str: - """Extract project name from config.""" - if self._config is not None: - name = self._config.get("project.name") - if name: - return str(name) - return "apcore" + def _get_project_details(self) -> dict[str, str]: + """Read the current project identity and any configured version.""" + if self._config is None: + return {"name": "apcore"} + project = {"name": str(self._config.get("project.name") or "apcore")} + version = self._config.get("project.version") + if isinstance(version, str): + project["version"] = version + return project def _get_call_counts(self, module_id: str) -> tuple[int, int]: """Return (total_calls, error_calls) for a module from metrics.""" diff --git a/python/src/apcore/sys_modules/overrides.py b/python/src/apcore/sys_modules/overrides.py index a6b2441c..fa86dac5 100644 --- a/python/src/apcore/sys_modules/overrides.py +++ b/python/src/apcore/sys_modules/overrides.py @@ -25,8 +25,6 @@ from typing import Any, Protocol, runtime_checkable from weakref import WeakValueDictionary -import yaml - logger = logging.getLogger(__name__) _update_locks: WeakValueDictionary[Path | int, LockType] = WeakValueDictionary() @@ -107,6 +105,8 @@ def _read_mapping(self) -> dict[str, Any]: raise OSError(f"Failed to read overrides file {self._path}: {exc}") from exc if not raw: return {} + import yaml + try: parsed: Any = yaml.safe_load(raw) except yaml.YAMLError as exc: @@ -123,6 +123,8 @@ def _read_mapping(self) -> dict[str, Any]: raise ValueError(f"Overrides file {self._path} root is not a mapping") def save(self, overrides: dict[str, Any]) -> None: + import yaml + directory = self._path.parent if str(self._path.parent) else Path(".") try: directory.mkdir(parents=True, exist_ok=True) diff --git a/python/src/apcore/sys_modules/registration.py b/python/src/apcore/sys_modules/registration.py index 0ed170a0..ad7dde3f 100644 --- a/python/src/apcore/sys_modules/registration.py +++ b/python/src/apcore/sys_modules/registration.py @@ -9,16 +9,12 @@ from apcore.config import Config -from apcore.errors import SysModuleRegistrationError +from apcore.errors import ConfigError, SysModuleRegistrationError from apcore.events.circuit_breaker import CircuitBreakerWrapper -from apcore.events.emitter import ApCoreEvent, EventEmitter, EventSubscriber -from apcore.events.retry import EventRetryConfig -from apcore.events.subscribers import ( - A2ASubscriber, - FileSubscriber, - FilterSubscriber, - StdoutSubscriber, - WebhookSubscriber, +from apcore.events.emitter import ApCoreEvent, EventEmitter +from apcore.events.factory import ( + SubscriberRegistry, + create_subscriber_from_config, ) from apcore.executor import Executor from apcore.middleware.error_history_middleware import ErrorHistoryMiddleware @@ -44,10 +40,6 @@ __all__ = [ "register_sys_modules", - "register_subscriber_type", - "unregister_subscriber_type", - "reset_subscriber_registry", - "register_subscriber_factory", "create_subscriber_from_config", "SysModulesContext", ] @@ -70,169 +62,6 @@ class SysModulesContext(TypedDict, total=False): audit_store: Any -# --------------------------------------------------------------------------- -# Subscriber type registry — extensible factory for EventSubscriber types -# --------------------------------------------------------------------------- - -#: Maps subscriber type name → factory function(config_dict) → EventSubscriber -_subscriber_factories: dict[str, Callable[[dict[str, Any]], EventSubscriber]] = {} - - -def _parse_retry_config(cfg: dict[str, Any]) -> EventRetryConfig | None: - """Build an :class:`EventRetryConfig` from a subscriber's nested ``retry:`` block. - - Implements the per-subscriber retry policy documented in - ``docs/features/event-system.md`` §"Per-Subscriber Retry Policy" (apcore#85). - The block is optional and may be partial — omitted keys fall back to the - spec defaults (``max_attempts=3``, ``initial_backoff_ms=100``, - ``max_backoff_ms=30000``, ``backoff_multiplier=2.0``). - - Args: - cfg: Raw subscriber config dict from ``sys_modules.events.subscribers``. - - Returns: - The parsed policy, or ``None`` when no ``retry:`` block is present, so - the subscriber falls back to its own default. - """ - nested = cfg.get("retry") - if not isinstance(nested, dict): - return None - default = EventRetryConfig() - return EventRetryConfig( - max_attempts=int(nested.get("max_attempts", default.max_attempts)), - initial_backoff_ms=int(nested.get("initial_backoff_ms", default.initial_backoff_ms)), - max_backoff_ms=int(nested.get("max_backoff_ms", default.max_backoff_ms)), - backoff_multiplier=float(nested.get("backoff_multiplier", default.backoff_multiplier)), - ) - - -def _default_webhook_factory(cfg: dict[str, Any]) -> EventSubscriber: - retry_cfg = _parse_retry_config(cfg) - # Deprecated: flat retry_count is the legacy webhook-only shorthand. It maps - # to EventRetryConfig.max_attempts + 1 (retry_count counted retries *after* - # the first attempt; max_attempts counts total attempts). The nested retry: - # block wins when both are present (apcore#85). - if retry_cfg is None and "retry_count" in cfg: - retry_cfg = EventRetryConfig(max_attempts=int(cfg["retry_count"]) + 1) - return WebhookSubscriber( - url=cfg["url"], - headers=cfg.get("headers"), - timeout_ms=cfg.get("timeout_ms", 5000), - retry=retry_cfg, - ) - - -def _default_a2a_factory(cfg: dict[str, Any]) -> EventSubscriber: - return A2ASubscriber( - platform_url=cfg["platform_url"], - auth=cfg.get("auth"), - timeout_ms=cfg.get("timeout_ms", 5000), - retry=_parse_retry_config(cfg), - ) - - -def _default_file_factory(cfg: dict[str, Any]) -> EventSubscriber: - return FileSubscriber( - path=cfg["path"], - append=cfg.get("append", True), - output_format=cfg.get("format", "json"), - rotate_bytes=cfg.get("rotate_bytes"), - retry=_parse_retry_config(cfg), - ) - - -def _default_stdout_factory(cfg: dict[str, Any]) -> EventSubscriber: - return StdoutSubscriber( - output_format=cfg.get("format", "text"), - level_filter=cfg.get("level_filter"), - retry=_parse_retry_config(cfg), - ) - - -def _default_filter_factory(cfg: dict[str, Any]) -> EventSubscriber: - delegate_cfg = {**cfg.get("delegate_config", {}), "type": cfg["delegate_type"]} - delegate = _create_subscriber(delegate_cfg) - return FilterSubscriber( - delegate=delegate, - include_events=cfg.get("include_events"), - exclude_events=cfg.get("exclude_events"), - retry=_parse_retry_config(cfg), - ) - - -# Built-in subscriber type registry -_BUILTIN_FACTORIES: dict[str, Callable[[dict[str, Any]], EventSubscriber]] = { - "webhook": _default_webhook_factory, - "a2a": _default_a2a_factory, - "file": _default_file_factory, - "stdout": _default_stdout_factory, - "filter": _default_filter_factory, -} - -# Register built-in types -_subscriber_factories.update(_BUILTIN_FACTORIES) - - -def register_subscriber_type( - type_name: str, - factory: Callable[[dict[str, Any]], EventSubscriber], -) -> None: - """Register a custom subscriber type factory.""" - _subscriber_factories[type_name] = factory - - -def unregister_subscriber_type(type_name: str) -> None: - """Remove a previously registered subscriber type.""" - del _subscriber_factories[type_name] - - -def reset_subscriber_registry() -> None: - """Reset the subscriber registry to built-in types only.""" - _subscriber_factories.clear() - _subscriber_factories.update(_BUILTIN_FACTORIES) - - -# --------------------------------------------------------------------------- -# Public SubscriberFactory API — parity with apcore-typescript -# (``createSubscriberFromConfig`` / ``registerSubscriberType``) and apcore-rust -# (``create_subscriber`` / ``register_subscriber_type``). Issue #36. -# --------------------------------------------------------------------------- - - -def register_subscriber_factory( - type_name: str, - factory: Callable[[dict[str, Any]], EventSubscriber], -) -> None: - """Register a custom subscriber-type factory. - - Public, cross-language counterpart to TypeScript's - ``registerSubscriberType`` / Rust's ``register_subscriber_type`` — the - normative name in event-system.md, which all three SDKs export. - - Args: - type_name: The ``type`` string used in subscriber config dicts. - factory: Callable that takes the config dict and returns an - :class:`EventSubscriber` instance. - """ - register_subscriber_type(type_name, factory) - - -def create_subscriber_from_config(config: dict[str, Any]) -> EventSubscriber: - """Instantiate an :class:`EventSubscriber` from a config dict. - - Public, cross-language counterpart to TypeScript's - ``createSubscriberFromConfig`` / Rust's ``create_subscriber``. - - Looks up the factory registered for ``config['type']`` and invokes it - with the full config. Built-in types (``webhook``, ``a2a``, ``file``, - ``stdout``, ``filter``) are auto-registered on import. - - Raises: - ValueError: If ``config['type']`` is not in the factory registry. - """ - return _create_subscriber(config) - - # --------------------------------------------------------------------------- # Namespace-mode helpers — §9.15.3 # --------------------------------------------------------------------------- @@ -341,6 +170,7 @@ def register_sys_modules( toggle_state: ToggleState | None = None, *, on_registration_error: Callable[[SysModuleRegistrationError], None] | None = None, + subscriber_registry: SubscriberRegistry | None = None, ) -> dict[str, Any]: """Auto-register all sys.* modules and middleware based on config. @@ -354,6 +184,8 @@ def register_sys_modules( failures are logged at ERROR level and execution continues. on_registration_error: Called for each module registration failure recovered in lenient mode. + subscriber_registry: Optional factories for this host. Omitting this + argument uses the built-in factories. audit_store: Optional audit store for control module audit trails. toggle_state: Optional per-instance :class:`ToggleState` (#71). When provided, ``ToggleFeatureModule`` writes to this instance (the @@ -403,6 +235,12 @@ def register_sys_modules( # namespace() returns a snapshot. Apply the effective settings at registration. sys_cfg = _resolve_sys_cfg(config) + retention_hours = _cfg_get(sys_cfg, config, "usage.retention_hours", 168) + if type(retention_hours) is not int or retention_hours < 1: + raise ConfigError(message="sys_modules.usage.retention_hours must be a positive integer") + if _cfg_get(sys_cfg, config, "usage.bucketing_strategy", "hourly") != "hourly": + raise ConfigError(message="sys_modules.usage.bucketing_strategy must be 'hourly'") + error_history = _create_error_history(config, sys_cfg) result["error_history"] = error_history @@ -411,7 +249,7 @@ def register_sys_modules( result["error_history_middleware"] = eh_middleware # Usage tracking - usage_collector = UsageCollector() + usage_collector = UsageCollector(retention_hours=retention_hours) result["usage_collector"] = usage_collector usage_middleware = UsageMiddleware(usage_collector) executor.use(usage_middleware) @@ -444,6 +282,7 @@ def register_sys_modules( audit_store=audit_store, register_module=register_module, toggle_state=toggle_state, + subscriber_registry=subscriber_registry, ) except BaseException: emitter = result.get("event_emitter") @@ -567,6 +406,7 @@ def _setup_events( overrides_store: OverridesStore | None = None, audit_store: AuditStore | None = None, toggle_state: ToggleState | None = None, + subscriber_registry: SubscriberRegistry | None = None, ) -> None: """Set up event emitter, subscribers, PlatformNotifyMiddleware, control modules, and registry bridge.""" event_emitter = EventEmitter() @@ -613,7 +453,7 @@ def _setup_events( if overrides_store is not None: _load_overrides_from_store(config, overrides_store, toggle_state=effective_toggle_state) - _instantiate_subscribers(config, sys_cfg, event_emitter) + _instantiate_subscribers(config, sys_cfg, event_emitter, subscriber_registry) registry.set_event_emitter(event_emitter) _bridge_registry_events(registry, event_emitter) @@ -680,12 +520,18 @@ def _register_control_modules( return effective_toggle_state -def _instantiate_subscribers(config: Config, sys_cfg: dict[str, Any] | None, event_emitter: EventEmitter) -> None: +def _instantiate_subscribers( + config: Config, + sys_cfg: dict[str, Any] | None, + event_emitter: EventEmitter, + subscriber_registry: SubscriberRegistry | None, +) -> None: """Create and subscribe EventSubscribers from config, each wrapped in a circuit breaker.""" subscribers_config = _cfg_get(sys_cfg, config, "events.subscribers", []) + subscribers = subscriber_registry if subscriber_registry is not None else SubscriberRegistry() for sub_cfg in subscribers_config: try: - subscriber = _create_subscriber(sub_cfg) + subscriber = subscribers.create(sub_cfg) cb_cfg: dict[str, Any] = sub_cfg.get("circuit_breaker") or {} wrapped = CircuitBreakerWrapper( subscriber=subscriber, @@ -703,20 +549,6 @@ def _instantiate_subscribers(config: Config, sys_cfg: dict[str, Any] | None, eve ) -def _create_subscriber(sub_cfg: dict[str, Any]) -> EventSubscriber: - """Factory for EventSubscriber from a config dict.""" - sub_type = sub_cfg.get("type", "") - factory = _subscriber_factories.get(sub_type) - if factory is None: - registered = ", ".join(sorted(_subscriber_factories.keys())) - raise ValueError( - f"Unknown subscriber type: {sub_type!r}. " - f"Registered types: [{registered}]. " - f"Use register_subscriber_type() to add custom types." - ) - return factory(sub_cfg) - - def _bridge_registry_events(registry: Registry, emitter: EventEmitter) -> None: """Bridge registry register/unregister events to the EventEmitter. diff --git a/python/tests/conformance/test_core_profile_governance.py b/python/tests/conformance/test_core_profile_governance.py new file mode 100644 index 00000000..e58ef3e0 --- /dev/null +++ b/python/tests/conformance/test_core_profile_governance.py @@ -0,0 +1,64 @@ +"""Drive default Core Profile approval through the public client API.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from apcore.acl import ACL, ACLRule +from apcore.client import APCore +from apcore.context import Context +from apcore.errors import ModuleError +from apcore.executor import Executor +from apcore.module import ModuleAnnotations +from apcore.policy import ExecutionPolicy +from apcore.registry import Registry +from conformance.canonical_fixtures import case_ids, load_fixture + +FIXTURE = "core_profile_governance.json" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("case", load_fixture(FIXTURE)["test_cases"], ids=case_ids(FIXTURE)) +async def test_approval_defaults_follow_preflight(case: dict[str, Any]) -> None: + module_id = "example.operation" + source = case["input"]["approval_source"] + policy_data = case["input"].get("execution_policy") + if source == "policy_rule": + policy_data = {"rules": [{"pattern": module_id, "requires_approval": True}]} + policy = ExecutionPolicy.from_dict(policy_data) if policy_data is not None else None + if case["input"]["client"] == "injected_executor": + client = APCore(executor=Executor(Registry(), policy=policy)) + else: + client = APCore(policy=policy) + + if source == "acl": + client.executor.set_acl(ACL([ACLRule(["@external"], [module_id], "allow", approval="required")])) + + calls = 0 + + @client.module( + id=module_id, + annotations=ModuleAnnotations(requires_approval=source == "annotation", destructive=source == "destructive"), + ) + async def operation(context: Context) -> int: + nonlocal calls + calls += 1 + return calls + + expected = case["expected"] + try: + preflight = await client.validate_async(module_id) + assert preflight.valid + assert preflight.requires_approval is expected["requires_approval"] + assert calls == 0 + if expected["error_code"] is None: + assert await client.call_async(module_id) == {"result": 1} + else: + with pytest.raises(ModuleError) as caught: + await client.call_async(module_id) + assert caught.value.code == expected["error_code"] + assert calls == expected["executions"] + finally: + client.close() diff --git a/python/tests/conformance/test_governance_state.py b/python/tests/conformance/test_governance_state.py index 6f2a2e30..084c6d95 100644 --- a/python/tests/conformance/test_governance_state.py +++ b/python/tests/conformance/test_governance_state.py @@ -77,8 +77,7 @@ def _build(setup: dict[str, Any]) -> Executor: executor.set_acl(ACL(default_effect="deny")) if setup["approval_handler_attached"]: executor.set_approval_handler(_NeverCalledHandler()) - if setup["policy_strict"]: - executor.set_policy(ExecutionPolicy(strict=True)) + executor.set_policy(ExecutionPolicy(strict=setup["policy_strict"])) return executor diff --git a/python/tests/conformance/test_issue123_contracts.py b/python/tests/conformance/test_issue123_contracts.py index 70936c8e..a1fd2e92 100644 --- a/python/tests/conformance/test_issue123_contracts.py +++ b/python/tests/conformance/test_issue123_contracts.py @@ -31,10 +31,8 @@ from apcore.context import Context, Identity from apcore.errors import ModuleError from apcore.executor import Executor -from apcore.module import Change, ModuleAnnotations, PreviewResult -from apcore.schema.exporter import SchemaExporter +from apcore.module import Change, PreviewResult from apcore.schema.loader import SchemaLoader -from apcore.schema.types import ExportProfile, SchemaDefinition from .canonical_fixtures import load_fixture @@ -42,7 +40,6 @@ ENV = load_fixture("env_prefix_dispatch.json") EPHEMERAL = load_fixture("ephemeral_modules.json") ERROR = load_fixture("error_details_shape.json") -EXPORT = load_fixture("export_profiles.json") NATIVE = load_fixture("json_input_native_types.json") PREFLIGHT = load_fixture("preflight_check_reporting.json") TIMEOUT = load_fixture("timeout_cancellation.json") @@ -237,50 +234,6 @@ def test_error_details_shape(case: dict[str, Any]) -> None: assert name not in details -def _pointer(document: Any, pointer: str) -> Any: - value = document - for segment in pointer.split("/")[1:]: - key = segment.replace("~1", "/").replace("~0", "~") - value = value[int(key)] if isinstance(value, list) else value[key] - return value - - -def _assert_no_x_keywords(value: Any, property_names: bool = False) -> None: - if isinstance(value, dict): - for key, child in value.items(): - assert property_names or not key.startswith("x-"), f"Extension keyword survived: {key}" - _assert_no_x_keywords(child, key == "properties" and not property_names) - elif isinstance(value, list): - for child in value: - _assert_no_x_keywords(child) - - -@pytest.mark.parametrize("case", EXPORT["test_cases"], ids=lambda case: case["id"]) -def test_export_profiles(case: dict[str, Any]) -> None: - """D-140, protocol §4.17: real profile exporter and keyword/property distinction.""" - expected = _expect_keys(case, {"paths", "absent_paths", "no_x_keywords_under"}) - contract = EXPORT["module_contract"] - registry = Registry() - module = _module(contract) - module.annotations = ModuleAnnotations(**case["input"]["annotations"]) - if module.annotations.streaming: - - async def stream(inputs: dict[str, Any], context: Context) -> Any: - yield {"sent": True} - - module.stream = stream - registry.register(contract["module_id"], module) - definition = SchemaDefinition(**contract) - result = SchemaExporter().export(definition, ExportProfile(case["input"]["profile"]), module.annotations) - for pointer, value in expected["paths"].items(): - assert _pointer(result, pointer) == value - for pointer in expected.get("absent_paths", []): - with pytest.raises((KeyError, IndexError)): - _pointer(result, pointer) - if "no_x_keywords_under" in expected: - _assert_no_x_keywords(_pointer(result, expected["no_x_keywords_under"])) - - class Level(str, Enum): LOW = "low" HIGH = "high" @@ -528,9 +481,8 @@ def execute(inputs: dict[str, Any], context: Context) -> dict[str, bool]: assert captured["token"].is_cancelled assert not completed.is_set() assert completed.wait(timeout=1) - # Let the cached loop consume the discarded worker future before closing. - assert executor._sync_loop is not None - executor._sync_loop.run_until_complete(asyncio.sleep(0)) + # Exercise a second public entry point over the caller's loop after timeout. + executor.validate("slow.blocking", {"count": 1}) executor.close() @@ -632,8 +584,7 @@ def test_d149_raw_json_schema_errors_share_the_native_wire_shape(case: dict[str, def test_subscriber_circuit_breaker_configuration_reaches_standard_bootstrap() -> None: """Issue #123 and protocol event system: honor every circuit_breaker setting.""" - from apcore.events.emitter import ApCoreEvent - from apcore.sys_modules.registration import register_subscriber_type, unregister_subscriber_type + from apcore.events import ApCoreEvent, SubscriberRegistry class SlowSubscriber: subscriber_id = "issue123-configured" @@ -649,8 +600,10 @@ async def on_event(self, event: ApCoreEvent) -> None: await asyncio.sleep(0.3) subscriber = SlowSubscriber() - register_subscriber_type("issue123-probe", lambda config: subscriber) + subscribers = SubscriberRegistry() + subscribers.register("issue123-probe", lambda config: subscriber) client = APCore( + subscriber_registry=subscribers, config=Config( { "sys_modules": { @@ -698,7 +651,6 @@ async def on_event(self, event: ApCoreEvent) -> None: assert len([item for item in recorder.events if item.event_type == "apcore.subscriber.circuit_closed"]) == 1 finally: client.close() - unregister_subscriber_type("issue123-probe") def test_d151_declaration_matches_verified_fixture_scope_and_package() -> None: @@ -716,9 +668,9 @@ def test_d151_declaration_matches_verified_fixture_scope_and_package() -> None: conformance = declaration["conformance"] assert conformance["level"] == 0 results = conformance["fixture_results"] - assert results["fixtures"] == len(results["fixture_names"]) == len(set(results["fixture_names"])) == 9 + assert results["fixtures"] == len(results["fixture_names"]) == len(set(results["fixture_names"])) == 8 cases = sum(len(load_fixture(name + ".json")["test_cases"]) for name in results["fixture_names"]) - assert results["cases"] == results["passed"] == cases == 79 + assert results["cases"] == results["passed"] == cases == 74 assert results["failed"] == results["skipped"] == 0 assert (root / results["report"]).is_file() assert len(results["reports"]) == 2 diff --git a/python/tests/conformance/test_reload_path_filter.py b/python/tests/conformance/test_reload_path_filter.py index 665a689c..d11948f4 100644 --- a/python/tests/conformance/test_reload_path_filter.py +++ b/python/tests/conformance/test_reload_path_filter.py @@ -31,7 +31,7 @@ from jsonschema import Draft202012Validator from apcore import AutoApproveHandler, Executor -from apcore.errors import ModuleReloadConflictError +from apcore.errors import ModuleError, ModuleReloadConflictError, SchemaValidationError from apcore.events import EventEmitter from apcore.registry import Registry from apcore.sys_modules.audit import InMemoryAuditStore @@ -108,12 +108,15 @@ def _fake_rediscover(module_id: str) -> _DummyModule: assert ( error is not None ), f"[{cid}] expected error_code {expected['error_code']!r} but execute() returned {result!r}" - assert isinstance( - error, ModuleReloadConflictError - ), f"[{cid}] expected ModuleReloadConflictError, got {type(error).__name__}: {error}" - assert ( - error.code == expected["error_code"] - ), f"[{cid}] error code mismatch: got {error.code!r}, expected {expected['error_code']!r}" + error_types = { + "MODULE_RELOAD_CONFLICT": ModuleReloadConflictError, + "SCHEMA_VALIDATION_ERROR": SchemaValidationError, + } + expected_type = error_types[expected["error_code"]] + assert isinstance(error, ModuleError) and isinstance(error, expected_type) + assert error.code == expected["error_code"] + assert not rediscovered + assert not audit_store.query() return assert error is None, f"[{cid}] execute() raised unexpectedly: {type(error).__name__}: {error}" diff --git a/python/tests/events/test_event_delivery_semantics.py b/python/tests/events/test_event_delivery_semantics.py index 0971a872..42f9f734 100644 --- a/python/tests/events/test_event_delivery_semantics.py +++ b/python/tests/events/test_event_delivery_semantics.py @@ -9,7 +9,7 @@ from apcore.events.emitter import ApCoreEvent, EventEmitter, _DLQ_EVENT_TYPE from apcore.events.circuit_breaker import CircuitBreakerWrapper from apcore.events.retry import EventRetryConfig -from apcore.events.subscribers import A2ASubscriber, FileSubscriber, StdoutSubscriber +from apcore.events.subscribers import FileSubscriber, StdoutSubscriber def _make_event(name: str = "apcore.test.event", payload: dict | None = None) -> ApCoreEvent: @@ -315,17 +315,6 @@ def test_event_pattern_wildcard_skips_dlq_events() -> None: assert len(dlq_received) == 0 -def test_a2a_subscriber_id_and_skill_id() -> None: - """A2ASubscriber supports explicit id and skill_id constructor params.""" - sub = A2ASubscriber( - platform_url="https://example.com", - skill_id="myapp.event_receiver", - id="remote-monitor-1", - ) - assert sub.subscriber_id == "remote-monitor-1" - assert sub._skill_id == "myapp.event_receiver" - - def test_file_subscriber_has_retry_and_event_pattern() -> None: sub = FileSubscriber( path="/tmp/test.jsonl", diff --git a/python/tests/events/test_event_management_hardening.py b/python/tests/events/test_event_management_hardening.py index 756ce6eb..4fdf05e7 100644 --- a/python/tests/events/test_event_management_hardening.py +++ b/python/tests/events/test_event_management_hardening.py @@ -94,22 +94,13 @@ def _make_mock_emitter() -> MagicMock: class TestSubscriberFactoryRegisteredType: - """A custom subscriber type registered via register_subscriber_type is + """A custom subscriber type registered in a host registry is instantiated when referenced by name in configuration.""" - @pytest.fixture(autouse=True) - def _reset_registry(self) -> Any: - from apcore.sys_modules.registration import reset_subscriber_registry - - reset_subscriber_registry() - yield - reset_subscriber_registry() - def test_custom_slack_type_instantiated(self) -> None: - from apcore.sys_modules.registration import ( - _create_subscriber, - register_subscriber_type, - ) + from apcore.events import SubscriberRegistry + + registry = SubscriberRegistry() case = _case("subscriber_factory_registered_type") params, expected = case["input"], case["expected"] @@ -123,10 +114,10 @@ def test_custom_slack_type_instantiated(self) -> None: sub.on_event = AsyncMock() subscribers[type_name] = sub factories[type_name] = MagicMock(return_value=sub) - register_subscriber_type(type_name, factories[type_name]) + registry.register(type_name, factories[type_name]) sub_cfg: dict[str, Any] = dict(params["subscriber_config"]) - subscriber = _create_subscriber(sub_cfg) + subscriber = registry.create(sub_cfg) assert (subscriber is not None) is expected["subscriber_created"], ( f"[{case['id']}] fixture declares subscriber_created=" @@ -153,12 +144,8 @@ def _assert_builtin_subscriber_case(case_id: str) -> None: chosen itself, which is true of an SDK whose built-in registry is empty for every OTHER type the fixture might declare. """ + from apcore.events import SubscriberRegistry from apcore.events.subscribers import FileSubscriber, StdoutSubscriber - from apcore.sys_modules.registration import ( - _BUILTIN_FACTORIES, - _create_subscriber, - reset_subscriber_registry, - ) classes: dict[str, type] = {"stdout": StdoutSubscriber, "file": FileSubscriber} @@ -167,18 +154,20 @@ def _assert_builtin_subscriber_case(case_id: str) -> None: sub_cfg: dict[str, Any] = dict(params["subscriber_config"]) expected_class = dispatch_or_fail(FIXTURE, case_id, expected["subscriber_type"], classes, "subscriber type") - # No register_subscriber_type call anywhere in this test: the registry is - # reset to built-ins only, which is what "requires_registration: false" - # asserts. - reset_subscriber_registry() - requires_registration = sub_cfg["type"] not in _BUILTIN_FACTORIES + # The fresh registry has only its built-in factories. + try: + subscriber = SubscriberRegistry().create(sub_cfg) + except ValueError as exc: + if "Unknown subscriber type" not in str(exc): + raise + subscriber = None + requires_registration = subscriber is None assert requires_registration is expected["requires_registration"], ( f"[{case_id}] fixture declares requires_registration=" f"{expected['requires_registration']}; {sub_cfg['type']!r} " f"{'is not' if requires_registration else 'is'} a built-in type" ) - subscriber = _create_subscriber(sub_cfg) assert (subscriber is not None) is expected["subscriber_created"], ( f"[{case_id}] fixture declares subscriber_created=" f"{expected['subscriber_created']}, got {subscriber!r}" ) diff --git a/python/tests/events/test_subscriber_retry_config.py b/python/tests/events/test_subscriber_retry_config.py index 4b40edc3..dd305618 100644 --- a/python/tests/events/test_subscriber_retry_config.py +++ b/python/tests/events/test_subscriber_retry_config.py @@ -17,22 +17,16 @@ import asyncio from typing import Any -import pytest from apcore.events.emitter import ApCoreEvent, EventEmitter from apcore.events.retry import EventRetryConfig from apcore.events.subscribers import ( - A2ASubscriber, FileSubscriber, FilterSubscriber, StdoutSubscriber, WebhookSubscriber, ) -from apcore.sys_modules.registration import ( - create_subscriber_from_config, - register_subscriber_type, - reset_subscriber_registry, -) +from apcore.events import SubscriberRegistry, create_subscriber_from_config # A policy in which every single field differs from EventRetryConfig() defaults. NON_DEFAULT_RETRY: dict[str, Any] = { @@ -52,13 +46,6 @@ def _assert_non_default_policy(retry: EventRetryConfig) -> None: assert retry.backoff_multiplier == 3.0 != default.backoff_multiplier -@pytest.fixture(autouse=True) -def _clean_registry() -> Any: - reset_subscriber_registry() - yield - reset_subscriber_registry() - - # --------------------------------------------------------------------------- # One case per built-in subscriber type # --------------------------------------------------------------------------- @@ -76,17 +63,6 @@ def test_webhook_reads_nested_retry_block(self) -> None: assert isinstance(sub, WebhookSubscriber) _assert_non_default_policy(sub.retry) - def test_a2a_reads_nested_retry_block(self) -> None: - sub = create_subscriber_from_config( - { - "type": "a2a", - "platform_url": "https://platform.example.com", - "retry": NON_DEFAULT_RETRY, - } - ) - assert isinstance(sub, A2ASubscriber) - _assert_non_default_policy(sub.retry) - def test_file_reads_nested_retry_block(self, tmp_path: Any) -> None: sub = create_subscriber_from_config( { @@ -233,7 +209,7 @@ async def _failing_on_event(_event: ApCoreEvent) -> None: def test_registered_custom_type_can_use_shared_parser(self) -> None: """Third-party factories opt in via the same nested block shape.""" - from apcore.sys_modules.registration import _parse_retry_config + from apcore.events.factory import _parse_retry_config class _CustomSink: subscriber_type = "custom_sink" @@ -246,8 +222,9 @@ def __init__(self, retry: EventRetryConfig | None) -> None: async def on_event(self, event: ApCoreEvent) -> None: await asyncio.sleep(0) - register_subscriber_type("custom_sink", lambda cfg: _CustomSink(_parse_retry_config(cfg))) - sub = create_subscriber_from_config({"type": "custom_sink", "retry": NON_DEFAULT_RETRY}) + registry = SubscriberRegistry() + registry.register("custom_sink", lambda cfg: _CustomSink(_parse_retry_config(cfg))) + sub = registry.create({"type": "custom_sink", "retry": NON_DEFAULT_RETRY}) _assert_non_default_policy(sub.retry) diff --git a/python/tests/events/test_subscribers.py b/python/tests/events/test_subscribers.py index 3d05e27a..e7b2980c 100644 --- a/python/tests/events/test_subscribers.py +++ b/python/tests/events/test_subscribers.py @@ -1,4 +1,4 @@ -"""Tests for WebhookSubscriber and A2ASubscriber.""" +"""Tests for WebhookSubscriber and its event contracts.""" from __future__ import annotations @@ -41,7 +41,8 @@ async def test_webhook_subscriber_sends_post_request(self) -> None: subscriber = WebhookSubscriber(url="https://example.com/webhook") event = _make_event() - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: + with patch("apcore.events.subscribers._load_aiohttp") as load_aiohttp: + mock_aiohttp = load_aiohttp.return_value mock_response = AsyncMock() mock_response.status = 200 mock_response.__aenter__ = AsyncMock(return_value=mock_response) @@ -76,7 +77,8 @@ async def test_webhook_subscriber_includes_custom_headers(self) -> None: ) event = _make_event() - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: + with patch("apcore.events.subscribers._load_aiohttp") as load_aiohttp: + mock_aiohttp = load_aiohttp.return_value mock_response = AsyncMock() mock_response.status = 200 mock_response.__aenter__ = AsyncMock(return_value=mock_response) @@ -106,7 +108,8 @@ async def test_webhook_subscriber_raises_on_5xx(self) -> None: subscriber = WebhookSubscriber(url="https://example.com/webhook") event = _make_event() - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: + with patch("apcore.events.subscribers._load_aiohttp") as load_aiohttp: + mock_aiohttp = load_aiohttp.return_value resp = AsyncMock() resp.status = 500 resp.__aenter__ = AsyncMock(return_value=resp) @@ -136,7 +139,8 @@ async def test_webhook_subscriber_raises_on_connection_error(self) -> None: subscriber = WebhookSubscriber(url="https://example.com/webhook") event = _make_event() - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: + with patch("apcore.events.subscribers._load_aiohttp") as load_aiohttp: + mock_aiohttp = load_aiohttp.return_value mock_session = AsyncMock() mock_session.post = MagicMock(side_effect=OSError("conn refused")) mock_session.__aenter__ = AsyncMock(return_value=mock_session) @@ -157,7 +161,8 @@ async def test_webhook_subscriber_enforces_timeout(self) -> None: subscriber = WebhookSubscriber(url="https://example.com/webhook", timeout_ms=100) event = _make_event() - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: + with patch("apcore.events.subscribers._load_aiohttp") as load_aiohttp: + mock_aiohttp = load_aiohttp.return_value mock_aiohttp.ClientTimeout = MagicMock() mock_session = AsyncMock() @@ -183,7 +188,8 @@ async def test_webhook_subscriber_does_not_retry_on_4xx(self) -> None: subscriber = WebhookSubscriber(url="https://example.com/webhook") event = _make_event() - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: + with patch("apcore.events.subscribers._load_aiohttp") as load_aiohttp: + mock_aiohttp = load_aiohttp.return_value mock_response = AsyncMock() mock_response.status = 400 mock_response.__aenter__ = AsyncMock(return_value=mock_response) @@ -211,7 +217,8 @@ async def test_webhook_subscriber_serializes_event_to_json(self) -> None: subscriber = WebhookSubscriber(url="https://example.com/webhook") event = _make_event() - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: + with patch("apcore.events.subscribers._load_aiohttp") as load_aiohttp: + mock_aiohttp = load_aiohttp.return_value mock_response = AsyncMock() mock_response.status = 200 mock_response.__aenter__ = AsyncMock(return_value=mock_response) @@ -237,99 +244,6 @@ async def test_webhook_subscriber_serializes_event_to_json(self) -> None: assert body["data"] == {"key": "value"} -# --------------------------------------------------------------------------- -# A2ASubscriber tests -# --------------------------------------------------------------------------- - - -class TestA2ASubscriberSendsViaClient: - @pytest.mark.asyncio - async def test_a2a_subscriber_sends_via_client(self) -> None: - from apcore.events.subscribers import A2ASubscriber - - subscriber = A2ASubscriber( - platform_url="https://platform.example.com", - auth="bearer-token-123", - ) - event = _make_event() - - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: - mock_response = AsyncMock() - mock_response.status = 200 - mock_response.__aenter__ = AsyncMock(return_value=mock_response) - mock_response.__aexit__ = AsyncMock(return_value=False) - - mock_session = AsyncMock() - mock_session.post = MagicMock(return_value=mock_response) - mock_session.__aenter__ = AsyncMock(return_value=mock_session) - mock_session.__aexit__ = AsyncMock(return_value=False) - - mock_aiohttp.ClientSession = MagicMock(return_value=mock_session) - - await subscriber.on_event(event) - - call_kwargs = mock_session.post.call_args - body = call_kwargs.kwargs.get("json") or call_kwargs[1].get("json") - assert body["skillId"] == "apevo.event_receiver" - - -class TestA2ASubscriberIncludesEventInPayload: - @pytest.mark.asyncio - async def test_a2a_subscriber_includes_event_in_payload(self) -> None: - from apcore.events.subscribers import A2ASubscriber - - subscriber = A2ASubscriber( - platform_url="https://platform.example.com", - ) - event = _make_event() - - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: - mock_response = AsyncMock() - mock_response.status = 200 - mock_response.__aenter__ = AsyncMock(return_value=mock_response) - mock_response.__aexit__ = AsyncMock(return_value=False) - - mock_session = AsyncMock() - mock_session.post = MagicMock(return_value=mock_response) - mock_session.__aenter__ = AsyncMock(return_value=mock_session) - mock_session.__aexit__ = AsyncMock(return_value=False) - - mock_aiohttp.ClientSession = MagicMock(return_value=mock_session) - - await subscriber.on_event(event) - - call_kwargs = mock_session.post.call_args - body = call_kwargs.kwargs.get("json") or call_kwargs[1].get("json") - payload_event = body["event"] - assert payload_event["event_type"] == "test.event" - assert payload_event["module_id"] == "mod.a" - assert payload_event["data"] == {"key": "value"} - - -class TestA2ASubscriberHandlesSendFailure: - @pytest.mark.asyncio - async def test_a2a_subscriber_handles_send_failure(self) -> None: - """Per apcore #61, A2A now raises on failure so the emitter can retry.""" - from apcore.events.subscribers import A2ASubscriber - - subscriber = A2ASubscriber( - platform_url="https://platform.example.com", - ) - event = _make_event() - - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: - mock_session = AsyncMock() - mock_session.post = MagicMock(side_effect=OSError("connection failed")) - mock_session.__aenter__ = AsyncMock(return_value=mock_session) - mock_session.__aexit__ = AsyncMock(return_value=False) - - mock_aiohttp.ClientSession = MagicMock(return_value=mock_session) - - # A2A now raises on failure (emitter handles retry/DLQ) - with pytest.raises(OSError, match="connection failed"): - await subscriber.on_event(event) - - # --------------------------------------------------------------------------- # Protocol conformance tests # --------------------------------------------------------------------------- @@ -398,7 +312,8 @@ async def test_4xx_is_not_retried_through_emitter(self) -> None: emitter.subscribe(dlq_recorder) emitter.subscribe(subscriber) - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: + with patch("apcore.events.subscribers._load_aiohttp") as load_aiohttp: + mock_aiohttp = load_aiohttp.return_value mock_session = _build_aiohttp_mock(mock_aiohttp, status=400) emitter.emit(_make_event()) @@ -429,7 +344,8 @@ async def test_5xx_is_retried_to_exhaustion_through_emitter(self) -> None: emitter.subscribe(dlq_recorder) emitter.subscribe(subscriber) - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: + with patch("apcore.events.subscribers._load_aiohttp") as load_aiohttp: + mock_aiohttp = load_aiohttp.return_value mock_session = _build_aiohttp_mock(mock_aiohttp, status=503) emitter.emit(_make_event()) @@ -445,80 +361,14 @@ async def test_5xx_is_retried_to_exhaustion_through_emitter(self) -> None: assert dlq.data["subscriber_id"] == "webhook-5xx" assert dlq.data["attempt_count"] == 3 - @pytest.mark.asyncio - async def test_a2a_4xx_is_not_retried_through_emitter(self) -> None: - """A2A HTTP 400 with max_attempts=3 → endpoint called once, no DLQ.""" - from apcore.events.emitter import EventEmitter - from apcore.events.retry import EventRetryConfig - from apcore.events.subscribers import A2ASubscriber - - subscriber = A2ASubscriber( - platform_url="https://platform.example.com", - retry=EventRetryConfig(max_attempts=3, initial_backoff_ms=1, max_backoff_ms=5), - ) - emitter = EventEmitter() - dlq_recorder = _DLQRecorder() - emitter.subscribe(dlq_recorder) - emitter.subscribe(subscriber) - - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: - mock_session = _build_aiohttp_mock(mock_aiohttp, status=400) - - emitter.emit(_make_event()) - emitter.flush(timeout=5.0) - emitter.shutdown() - - # 4xx is a permanent client error: a single HTTP call, no retries. - assert mock_session.post.call_count == 1 - # 4xx is logged-permanent (does not raise into the emitter), so no - # DLQ event is emitted — matches src/apcore/events/subscribers.py - # and event-system.md §"Behavior on 4xx / 5xx Responses". - assert len(dlq_recorder.received) == 0 - - @pytest.mark.asyncio - async def test_a2a_5xx_is_retried_to_exhaustion_through_emitter(self) -> None: - """A2A HTTP 503 with max_attempts=3 → endpoint called 3 times, then DLQ.""" - from apcore.events.emitter import _DLQ_EVENT_TYPE, EventEmitter - from apcore.events.retry import EventRetryConfig - from apcore.events.subscribers import A2ASubscriber - - subscriber = A2ASubscriber( - platform_url="https://platform.example.com", - id="a2a-5xx", - retry=EventRetryConfig(max_attempts=3, initial_backoff_ms=1, max_backoff_ms=5), - ) - emitter = EventEmitter() - dlq_recorder = _DLQRecorder() - emitter.subscribe(dlq_recorder) - emitter.subscribe(subscriber) - - with patch("apcore.events.subscribers.aiohttp") as mock_aiohttp: - mock_session = _build_aiohttp_mock(mock_aiohttp, status=503) - - emitter.emit(_make_event()) - emitter.flush(timeout=5.0) - emitter.shutdown() - - # 5xx is retried to exhaustion: one HTTP call per attempt. - assert mock_session.post.call_count == 3 - # On exhaustion the emitter emits a delivery_failed DLQ event. - assert len(dlq_recorder.received) == 1 - dlq = dlq_recorder.received[0] - assert dlq.event_type == _DLQ_EVENT_TYPE - assert dlq.data["subscriber_id"] == "a2a-5xx" - assert dlq.data["subscriber_type"] == "a2a" - assert dlq.data["attempt_count"] == 3 - class TestSubscriberConformsToProtocol: def test_subscriber_conforms_to_protocol(self) -> None: - from apcore.events.subscribers import A2ASubscriber, WebhookSubscriber + from apcore.events.subscribers import WebhookSubscriber webhook = WebhookSubscriber(url="https://example.com/webhook") - a2a = A2ASubscriber(platform_url="https://platform.example.com") assert isinstance(webhook, EventSubscriber) - assert isinstance(a2a, EventSubscriber) class TestSubscriberInstantiationFailureLogged: diff --git a/python/tests/observability/test_observability_hardening.py b/python/tests/observability/test_observability_hardening.py index 4635cbe6..abed2ec8 100644 --- a/python/tests/observability/test_observability_hardening.py +++ b/python/tests/observability/test_observability_hardening.py @@ -634,13 +634,12 @@ def test_prometheus_text_format_conventions(self) -> None: assert "# TYPE apcore_module_calls_total counter" in output def test_prometheus_exporter_export_method(self) -> None: - """PrometheusExporter.export() delegates to MetricsCollector.export_prometheus().""" - from apcore.observability.prometheus_exporter import PrometheusExporter + """The renderer delegates to MetricsCollector.export_prometheus().""" + from apcore.observability.prometheus_exporter import render_prometheus_metrics collector = MetricsCollector() collector.increment_calls("mod.a", "success") - exporter = PrometheusExporter(collector=collector) - output = exporter.export() + output = render_prometheus_metrics(collector) assert "apcore_module_calls_total" in output diff --git a/python/tests/observability/test_observability_package.py b/python/tests/observability/test_observability_package.py index 85c95deb..b17d3a18 100644 --- a/python/tests/observability/test_observability_package.py +++ b/python/tests/observability/test_observability_package.py @@ -96,7 +96,7 @@ def test_all_contains_all_public_names(self): "InMemoryObservabilityStore", "ObservabilityStore", "MetricPoint", - "PrometheusExporter", + "render_prometheus_metrics", "render_prometheus_metrics", "RedactionConfig", "normalize_message", diff --git a/python/tests/observability/test_prometheus_usage_metrics.py b/python/tests/observability/test_prometheus_usage_metrics.py index 4391081a..66beda1e 100644 --- a/python/tests/observability/test_prometheus_usage_metrics.py +++ b/python/tests/observability/test_prometheus_usage_metrics.py @@ -1,87 +1,20 @@ -"""Regression test for A-D-16: PrometheusExporter must append usage metrics. - -Cross-language parity: TS prometheus-exporter.ts and Rust prometheus_exporter.rs -both append the ``apcore_usage_*`` metric families to their /metrics output when -a usage collector is present. The Python exporter previously exposed only the -MetricsCollector output and left UsageCollector.export_prometheus() unwired. - -Back-compat: when no usage_collector is supplied, the output must be unchanged -(MetricsCollector output only). -""" +"""Render metrics and usage as one Prometheus exposition.""" from __future__ import annotations -import threading -from concurrent.futures import ThreadPoolExecutor -from contextlib import closing from datetime import datetime, timedelta, timezone -from http.client import HTTPConnection import pytest from apcore.observability import render_prometheus_metrics from apcore.observability import usage as usage_module from apcore.observability.metrics import MetricsCollector -from apcore.observability.prometheus_exporter import PrometheusExporter from apcore.observability.usage import UsageCollector -def _get(port: int, path: str) -> tuple[int, bytes]: - with closing(HTTPConnection("127.0.0.1", port, timeout=2)) as connection: - connection.request("GET", path) - response = connection.getresponse() - return response.status, response.read() - - -def test_prometheus_listener_binds_to_loopback_and_can_restart() -> None: - exporter = PrometheusExporter(MetricsCollector()) - exporter.start(port=0) - try: - assert exporter._server is not None - host, port = exporter._server.server_address - assert host == "127.0.0.1" - assert _get(port, "/readyz")[0] == 503 - finally: - exporter.stop() - - exporter.start(port, host="127.0.0.1") - try: - exporter.mark_ready() - assert _get(port, "/readyz") == (200, b"OK") - finally: - exporter.stop() - - -def test_health_probe_progresses_while_metrics_are_rendered(monkeypatch: pytest.MonkeyPatch) -> None: - exporter = PrometheusExporter(MetricsCollector()) - rendering = threading.Event() - release_render = threading.Event() - - def render() -> str: - rendering.set() - assert release_render.wait(timeout=5) - return "sample_metric 1\n" - - monkeypatch.setattr(exporter, "export", render) - exporter.start(port=0) - try: - assert exporter._server is not None - _, port = exporter._server.server_address - with ThreadPoolExecutor(max_workers=1) as pool: - metrics = pool.submit(_get, port, "/metrics") - try: - assert rendering.wait(timeout=2) - assert _get(port, "/healthz") == (200, b"OK") - finally: - release_render.set() - assert metrics.result(timeout=2) == (200, b"sample_metric 1\n") - finally: - exporter.stop() - - @pytest.mark.parametrize("populated_metrics", [False, True]) @pytest.mark.parametrize("populated_usage", [None, False, True]) -def test_render_prometheus_metrics_matches_legacy_export(populated_metrics: bool, populated_usage: bool | None) -> None: +def test_render_prometheus_metrics_combines_collectors(populated_metrics: bool, populated_usage: bool | None) -> None: collector = MetricsCollector() if populated_metrics: collector.increment_calls("math.add", "success") @@ -93,7 +26,6 @@ def test_render_prometheus_metrics_matches_legacy_export(populated_metrics: bool fragments = [collector.export_prometheus(), usage.export_prometheus() if usage is not None else ""] expected = "".join(fragments) assert render_prometheus_metrics(collector, usage) == expected - assert PrometheusExporter(collector, usage).export() == expected assert render_prometheus_metrics(collector) == collector.export_prometheus() @@ -110,10 +42,9 @@ def now(cls, tz: timezone | None = None) -> datetime: metrics.increment("demo_counter_total", {}) usage = UsageCollector() usage.record("demo.one", "client", 12.0, True) - exporter = PrometheusExporter(metrics, usage) - before = exporter.export() + before = render_prometheus_metrics(metrics, usage) instant += timedelta(hours=25) - after = exporter.export() + after = render_prometheus_metrics(metrics, usage) for family in ("apcore_usage_calls_24h", "apcore_usage_calls_total"): sample = f'{family}{{module_id="demo.one",status="success"}}' @@ -132,8 +63,7 @@ def test_usage_metrics_appended_when_collector_present(self) -> None: usage = UsageCollector() usage.record(module_id="m.a", caller_id="caller", latency_ms=12.0, success=True) - exporter = PrometheusExporter(collector, usage_collector=usage) - output = exporter.export() + output = render_prometheus_metrics(collector, usage) # MetricsCollector families remain present. assert "apcore_module_calls_total" in output @@ -146,14 +76,7 @@ def test_no_usage_metrics_without_collector(self) -> None: collector = MetricsCollector() collector.increment("apcore_module_calls_total", {"module_id": "m.a", "status": "success"}) - exporter = PrometheusExporter(collector) - output = exporter.export() + output = render_prometheus_metrics(collector) assert "apcore_module_calls_total" in output assert "apcore_usage_" not in output - - def test_default_usage_collector_is_none(self) -> None: - """Back-compat: the positional-only signature still works.""" - exporter = PrometheusExporter(MetricsCollector()) - # No exception, no usage output. - assert "apcore_usage_" not in exporter.export() diff --git a/python/tests/registry/test_ephemeral_modules.py b/python/tests/registry/test_ephemeral_modules.py index dc83ef20..4e724367 100644 --- a/python/tests/registry/test_ephemeral_modules.py +++ b/python/tests/registry/test_ephemeral_modules.py @@ -212,11 +212,11 @@ def test_list_excludes_hidden_modules(self) -> None: assert "v.visible" in ids assert "h.hidden" not in ids - def test_list_include_hidden_returns_all(self) -> None: + def test_list_explicit_visibility_returns_all(self) -> None: registry = Registry() registry.register("v.visible", _DiscoverableVisible()) registry.register("h.hidden", _DiscoverableHidden()) - ids = registry.list(include_hidden=True) + ids = registry.list(visibility=["public", "hidden"]) assert "v.visible" in ids assert "h.hidden" in ids @@ -268,7 +268,7 @@ def test_yaml_metadata_can_set_discoverable(self) -> None: metadata={"annotations": {"discoverable": False}}, ) assert "v.optedout" not in registry.list() - assert "v.optedout" in registry.list(include_hidden=True) + assert "v.optedout" in registry.list(visibility=["public", "hidden"]) # =========================================================================== diff --git a/python/tests/registry/test_schema_export.py b/python/tests/registry/test_schema_export.py index 5d08eb14..2115c71e 100644 --- a/python/tests/registry/test_schema_export.py +++ b/python/tests/registry/test_schema_export.py @@ -200,16 +200,6 @@ def test_nonexistent_raises(self) -> None: with pytest.raises(ModuleNotFoundError): export_schema(reg, "missing") - def test_profile_export(self) -> None: - """export_schema with profile delegates to SchemaExporter.""" - reg = _make_registry() - result = export_schema(reg, "test.annotated", format="json", profile="mcp") - parsed = json.loads(result) - # MCP format has 'name' and 'inputSchema' keys - assert "name" in parsed - assert "inputSchema" in parsed - - # --------------------------------------------------------------------------- # get_all_schemas() / export_all_schemas() tests # --------------------------------------------------------------------------- diff --git a/python/tests/schema/test_edge_cases.py b/python/tests/schema/test_edge_cases.py index 1af5e1dc..c5c742a0 100644 --- a/python/tests/schema/test_edge_cases.py +++ b/python/tests/schema/test_edge_cases.py @@ -242,7 +242,6 @@ class TestPublicApi: def test_all_names_importable(self) -> None: """All 14 public API names are importable from apcore.schema.""" from apcore.schema import ( - ExportProfile, LLMExtensions, RefResolver, ResolvedSchema, @@ -262,7 +261,6 @@ def test_all_names_importable(self) -> None: # Just verify they're all not None assert all( [ - ExportProfile, LLMExtensions, RefResolver, ResolvedSchema, diff --git a/python/tests/schema/test_exporter.py b/python/tests/schema/test_exporter.py index 25a74423..661a6628 100644 --- a/python/tests/schema/test_exporter.py +++ b/python/tests/schema/test_exporter.py @@ -4,9 +4,8 @@ from typing import Any -from apcore.module import ModuleAnnotations, ModuleExample from apcore.schema.exporter import SchemaExporter -from apcore.schema.types import ExportProfile, SchemaDefinition +from apcore.schema.types import SchemaDefinition def _make_schema_def( @@ -37,14 +36,6 @@ def _make_schema_def( ) -def _make_annotations(**kwargs: Any) -> ModuleAnnotations: - return ModuleAnnotations(**kwargs) - - -def _make_example(title: str = "Example 1", inputs: dict[str, Any] | None = None) -> ModuleExample: - return ModuleExample(title=title, inputs=inputs or {"to": "user@example.com"}) - - # ===== export_generic() ===== @@ -70,216 +61,3 @@ def test_all_keys_present(self) -> None: "output_schema", "definitions", } - - -# ===== export_mcp() ===== - - -class TestExportMcp: - def test_preserves_x_fields(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_mcp(sd) - assert "x-llm-description" in result["inputSchema"]["properties"]["to"] - - def test_id_uses_dots(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_mcp(sd) - assert result["name"] == "executor.email.send" - - def test_annotations_mapped(self) -> None: - sd = _make_schema_def() - ann = _make_annotations(readonly=True, destructive=True, idempotent=True, open_world=False) - exporter = SchemaExporter() - result = exporter.export_mcp(sd, annotations=ann) - assert result["annotations"]["readOnlyHint"] is True - assert result["annotations"]["destructiveHint"] is True - assert result["annotations"]["idempotentHint"] is True - assert result["annotations"]["openWorldHint"] is False - - def test_default_annotations(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_mcp(sd) - assert result["annotations"]["readOnlyHint"] is False - assert result["annotations"]["destructiveHint"] is False - assert result["annotations"]["idempotentHint"] is False - assert result["annotations"]["openWorldHint"] is True - assert "streaming" not in result["annotations"] - assert "streaming" not in result["_meta"] - - def test_streaming_annotation(self) -> None: - sd = _make_schema_def() - ann = _make_annotations(streaming=True) - exporter = SchemaExporter() - result = exporter.export_mcp(sd, annotations=ann) - assert result["_meta"]["streaming"] is True - assert "streaming" not in result["annotations"] - - def test_custom_name(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_mcp(sd, name="custom_tool") - assert result["name"] == "custom_tool" - - def test_meta_defaults(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_mcp(sd) - meta = result["_meta"] - assert meta["cacheable"] is False - assert meta["cacheTtl"] == 0 - assert meta["cacheKeyFields"] is None - assert meta["paginated"] is False - assert meta["paginationStyle"] == "cursor" - - def test_meta_with_annotations(self) -> None: - sd = _make_schema_def() - ann = _make_annotations( - cacheable=True, - cache_ttl=600, - cache_key_fields=["id", "name"], - paginated=True, - pagination_style="offset", - ) - exporter = SchemaExporter() - result = exporter.export_mcp(sd, annotations=ann) - meta = result["_meta"] - assert meta["cacheable"] is True - assert meta["cacheTtl"] == 600 - assert meta["cacheKeyFields"] == ("id", "name") - assert meta["paginated"] is True - assert meta["paginationStyle"] == "offset" - - -# ===== export_openai() ===== - - -class TestExportOpenai: - def test_strict_mode_applied(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_openai(sd) - assert result["function"]["parameters"]["additionalProperties"] is False - - def test_llm_description_replaces(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_openai(sd) - assert result["function"]["parameters"]["properties"]["to"]["description"] == "Full recipient email" - - def test_x_fields_stripped(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_openai(sd) - assert "x-llm-description" not in result["function"]["parameters"]["properties"]["to"] - - def test_defaults_stripped(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_openai(sd) - assert "default" not in result["function"]["parameters"]["properties"].get("cc", {}) - - def test_id_dots_to_underscores(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_openai(sd) - assert result["function"]["name"] == "executor_email_send" - - def test_strict_true(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_openai(sd) - assert result["function"]["strict"] is True - - def test_function_wrapper(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_openai(sd) - assert result["type"] == "function" - assert "function" in result - - -# ===== export_anthropic() ===== - - -class TestExportAnthropic: - def test_x_fields_stripped_no_strict(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_anthropic(sd) - props = result["input_schema"]["properties"] - assert "x-llm-description" not in props["to"] - # Strict mode NOT applied — additionalProperties not forced - assert result["input_schema"].get("additionalProperties") is None - - def test_llm_description_replaces(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_anthropic(sd) - assert result["input_schema"]["properties"]["to"]["description"] == "Full recipient email" - - def test_id_dots_to_underscores(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_anthropic(sd) - assert result["name"] == "executor_email_send" - - def test_examples_mapped(self) -> None: - sd = _make_schema_def() - ex1 = _make_example("Ex1", {"to": "a@b.com"}) - ex2 = _make_example("Ex2", {"to": "c@d.com"}) - exporter = SchemaExporter() - result = exporter.export_anthropic(sd, examples=[ex1, ex2]) - assert result["input_examples"] == [{"to": "a@b.com"}, {"to": "c@d.com"}] - - def test_no_examples(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_anthropic(sd) - assert "input_examples" not in result - - def test_uses_input_schema_key(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_anthropic(sd) - assert "input_schema" in result - assert "inputSchema" not in result - - def test_preserves_default_values(self) -> None: - """export_anthropic() preserves default values in the output schema.""" - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export_anthropic(sd) - # The default schema has cc with default=[] - assert result["input_schema"]["properties"]["cc"]["default"] == [] - - -# ===== export() dispatch ===== - - -class TestExportDispatch: - def test_generic(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export(sd, ExportProfile.GENERIC) - assert "module_id" in result - - def test_mcp(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export(sd, ExportProfile.MCP) - assert "inputSchema" in result - - def test_openai(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export(sd, ExportProfile.OPENAI) - assert result["type"] == "function" - - def test_anthropic(self) -> None: - sd = _make_schema_def() - exporter = SchemaExporter() - result = exporter.export(sd, ExportProfile.ANTHROPIC) - assert "input_schema" in result diff --git a/python/tests/schema/test_strict.py b/python/tests/schema/test_strict.py index a5970531..3340178b 100644 --- a/python/tests/schema/test_strict.py +++ b/python/tests/schema/test_strict.py @@ -6,7 +6,6 @@ from typing import Any from apcore.schema.strict import ( - _apply_llm_descriptions, _strip_extensions, to_strict_schema, ) @@ -260,38 +259,6 @@ def test_prefix_items_entries_are_hardened(self) -> None: assert first["required"] == ["z"] -# === _apply_llm_descriptions() === - - -class TestApplyLlmDescriptions: - def test_replaces_description(self) -> None: - node: dict[str, Any] = { - "description": "short", - "x-llm-description": "long detailed", - } - _apply_llm_descriptions(node) - assert node["description"] == "long detailed" - assert "x-llm-description" in node # stripping happens separately - - def test_preserves_description_without_llm(self) -> None: - node: dict[str, Any] = {"description": "short"} - _apply_llm_descriptions(node) - assert node["description"] == "short" - - def test_recursive_into_properties(self) -> None: - node: dict[str, Any] = { - "type": "object", - "properties": { - "a": {"description": "old", "x-llm-description": "new"}, - }, - } - _apply_llm_descriptions(node) - assert node["properties"]["a"]["description"] == "new" - - def test_no_llm_description_unchanged(self) -> None: - node: dict[str, Any] = {"description": "keep me", "type": "string"} - _apply_llm_descriptions(node) - assert node["description"] == "keep me" # === _strip_extensions() === diff --git a/python/tests/schema/test_types.py b/python/tests/schema/test_types.py index a99c89c2..8744af74 100644 --- a/python/tests/schema/test_types.py +++ b/python/tests/schema/test_types.py @@ -7,7 +7,6 @@ from apcore.errors import SchemaValidationError from apcore.schema.types import ( - ExportProfile, LLMExtensions, ResolvedSchema, SchemaDefinition, @@ -32,24 +31,6 @@ def test_string_comparison(self) -> None: assert isinstance(SchemaStrategy.YAML_FIRST, str) -class TestExportProfile: - def test_mcp_value(self) -> None: - assert ExportProfile.MCP == "mcp" - - def test_openai_value(self) -> None: - assert ExportProfile.OPENAI == "openai" - - def test_anthropic_value(self) -> None: - assert ExportProfile.ANTHROPIC == "anthropic" - - def test_generic_value(self) -> None: - assert ExportProfile.GENERIC == "generic" - - def test_string_comparison(self) -> None: - assert ExportProfile.MCP == "mcp" - assert isinstance(ExportProfile.MCP, str) - - class TestSchemaDefinition: def test_required_fields(self) -> None: sd = SchemaDefinition( diff --git a/python/tests/sys_modules/test_control.py b/python/tests/sys_modules/test_control.py index cc9b1804..2b869f8b 100644 --- a/python/tests/sys_modules/test_control.py +++ b/python/tests/sys_modules/test_control.py @@ -12,6 +12,7 @@ import pytest +from apcore.approval import AutoApproveHandler from apcore.client import APCore from apcore.config import Config from apcore.errors import InvalidInputError, ModuleDisabledError, ModuleError, ModuleNotFoundError, ReloadFailedError @@ -139,6 +140,7 @@ async def test_qualified_timeout_update_reaches_executor(self) -> None: **{"sys_modules.enabled": True, "sys_modules.events.enabled": True, "sys_modules.control.enabled": True} ) client = APCore(config=config) + client.executor.set_approval_handler(AutoApproveHandler()) release = asyncio.Event() class WaitForSignal: @@ -748,6 +750,8 @@ def test_reload_through_the_registered_sys_module(self, tmp_path: Path) -> None: registry=registry, ) + client.executor.set_approval_handler(AutoApproveHandler()) + result = client.call( "system.control.reload_module", {"module_id": "greeter", "reason": "issue-33"}, diff --git a/python/tests/sys_modules/test_overrides_store.py b/python/tests/sys_modules/test_overrides_store.py index 8468ce3c..238038e0 100644 --- a/python/tests/sys_modules/test_overrides_store.py +++ b/python/tests/sys_modules/test_overrides_store.py @@ -26,6 +26,7 @@ import pytest import yaml +from apcore.approval import AutoApproveHandler from apcore import APCore from apcore.sys_modules import overrides as overrides_module @@ -187,7 +188,7 @@ def test_load_falls_back_to_json_when_the_yaml_loader_raises( def _raise_yaml(*args: object, **kwargs: object) -> object: raise yaml.YAMLError("synthetic") - monkeypatch.setattr(overrides_module.yaml, "safe_load", _raise_yaml) + monkeypatch.setattr(yaml, "safe_load", _raise_yaml) assert FileOverridesStore(path).load() == {"a.b": 1} def test_load_returns_empty_and_warns_when_neither_yaml_nor_json( @@ -337,6 +338,7 @@ def test_control_preserves_existing_file_when_load_fails( _enable_sys_modules(config) config.set("sys_modules.control.overrides_path", str(path)) client = APCore(config=config) + client.executor.set_approval_handler(AutoApproveHandler()) try: result = client.call( "system.control.update_config", @@ -368,7 +370,7 @@ def load(self) -> dict[str, Any]: config = Config.from_defaults() _enable_sys_modules(config) registry = Registry() - executor = Executor(registry=registry) + executor = Executor(registry=registry, approval_handler=AutoApproveHandler()) register_sys_modules(registry, executor, config, overrides_store=store) store.active = True with ThreadPoolExecutor(max_workers=2) as pool: diff --git a/python/tests/sys_modules/test_registration.py b/python/tests/sys_modules/test_registration.py index b4bc8424..398b521f 100644 --- a/python/tests/sys_modules/test_registration.py +++ b/python/tests/sys_modules/test_registration.py @@ -3,12 +3,14 @@ from __future__ import annotations import logging +from datetime import datetime, timedelta, timezone from typing import Any from unittest.mock import MagicMock import pytest from apcore.config import Config +from apcore.errors import ConfigError from apcore.events.emitter import EventEmitter from apcore.executor import Executor from apcore.middleware.error_history_middleware import ErrorHistoryMiddleware @@ -17,13 +19,8 @@ from apcore.observability.metrics import MetricsCollector from apcore.registry.registry import Registry from apcore.events.emitter import ApCoreEvent -from apcore.sys_modules.registration import ( - _subscriber_factories, - register_subscriber_type, - register_sys_modules, - reset_subscriber_registry, - unregister_subscriber_type, -) +from apcore.events import SubscriberRegistry, create_subscriber_from_config +from apcore.sys_modules.registration import register_sys_modules def _make_config(overrides: dict[str, Any] | None = None) -> Config: @@ -370,6 +367,7 @@ def test_register_sys_modules_returns_context(self) -> None: ) assert "error_history" in result + assert "error_history_middleware" in result assert "event_emitter" in result assert "platform_notify_middleware" in result @@ -391,57 +389,9 @@ def test_apcore_client_calls_register_sys_modules(self) -> None: assert isinstance(client._sys_modules_context, dict) -class TestA2ASubscriber: - def test_register_sys_modules_a2a_subscriber(self) -> None: - """A2A subscriber created from config.""" - config = _make_config( - { - "sys_modules": { - "events": { - "enabled": True, - "subscribers": [ - { - "type": "a2a", - "platform_url": "https://platform.example.com/a2a", - "auth": "my-token", - }, - ], - }, - }, - } - ) - registry, executor, metrics = _make_deps() - - result = register_sys_modules( - registry=registry, - executor=executor, - config=config, - metrics_collector=metrics, - ) - - emitter = result["event_emitter"] - assert len(emitter._subscribers) == 1 - from apcore.events.circuit_breaker import CircuitBreakerWrapper - - wrapper = emitter._subscribers[0] - assert isinstance(wrapper, CircuitBreakerWrapper) - from apcore.events.subscribers import A2ASubscriber - - sub = wrapper._subscriber - assert isinstance(sub, A2ASubscriber) - assert sub._platform_url == "https://platform.example.com/a2a" - assert sub._auth == "my-token" - - class TestCustomSubscriberRegistry: """Tests for the extensible subscriber type registry.""" - @pytest.fixture(autouse=True) - def _isolate_subscriber_registry(self) -> Any: - """Reset subscriber registry to built-in defaults after each test.""" - yield - reset_subscriber_registry() - def test_register_custom_subscriber_type(self) -> None: """Register a custom subscriber type and use it from config.""" @@ -452,7 +402,8 @@ def __init__(self, channel: str) -> None: async def on_event(self, event: ApCoreEvent) -> None: pass - register_subscriber_type("slack", lambda cfg: SlackSubscriber(channel=cfg["channel"])) + subscribers = SubscriberRegistry() + subscribers.register("slack", lambda cfg: SlackSubscriber(channel=cfg["channel"])) config = _make_config( { "sys_modules": { @@ -472,6 +423,7 @@ async def on_event(self, event: ApCoreEvent) -> None: executor=executor, config=config, metrics_collector=metrics, + subscriber_registry=subscribers, ) emitter = result["event_emitter"] @@ -484,17 +436,6 @@ async def on_event(self, event: ApCoreEvent) -> None: assert isinstance(sub, SlackSubscriber) assert sub.channel == "#alerts" - def test_unregister_subscriber_type(self) -> None: - """Unregister a subscriber type; verify it is no longer available.""" - register_subscriber_type("temp", lambda cfg: MagicMock()) - unregister_subscriber_type("temp") - assert "temp" not in _subscriber_factories - - def test_unregister_nonexistent_type_raises(self) -> None: - """Unregistering a non-existent type raises KeyError.""" - with pytest.raises(KeyError): - unregister_subscriber_type("nonexistent_type_xyz") - def test_override_builtin_subscriber_type(self) -> None: """Override the built-in 'webhook' type with a custom factory.""" @@ -506,7 +447,8 @@ def __init__(self, url: str) -> None: async def on_event(self, event: ApCoreEvent) -> None: pass - register_subscriber_type("webhook", lambda cfg: CustomWebhook(url=cfg["url"])) + subscribers = SubscriberRegistry() + subscribers.register("webhook", lambda cfg: CustomWebhook(url=cfg["url"])) config = _make_config( { "sys_modules": { @@ -526,6 +468,7 @@ async def on_event(self, event: ApCoreEvent) -> None: executor=executor, config=config, metrics_collector=metrics, + subscriber_registry=subscribers, ) from apcore.events.circuit_breaker import CircuitBreakerWrapper @@ -563,20 +506,10 @@ def test_unknown_type_error_lists_registered_types(self, caplog: pytest.LogCaptu assert any("Failed to instantiate subscriber" in msg for msg in caplog.messages) def test_builtin_types_registered_by_default(self) -> None: - """Verify 'webhook' and 'a2a' are registered by default.""" - assert "webhook" in _subscriber_factories - assert "a2a" in _subscriber_factories - - def test_reset_subscriber_registry(self) -> None: - """reset_subscriber_registry restores only built-in types.""" - register_subscriber_type("custom", lambda cfg: MagicMock()) - assert "custom" in _subscriber_factories - - reset_subscriber_registry() - - assert "custom" not in _subscriber_factories - assert "webhook" in _subscriber_factories - assert "a2a" in _subscriber_factories + """Verify the neutral webhook built-in and explicit A2A ownership.""" + assert create_subscriber_from_config({"type": "webhook", "url": "https://example.com"}) is not None + with pytest.raises(ValueError, match="Unknown subscriber type"): + create_subscriber_from_config({"type": "a2a"}) class TestMetricsCollectorNone: @@ -592,3 +525,29 @@ def test_register_sys_modules_with_metrics_collector_none(self) -> None: assert registry.has("system.health.module") assert registry.has("system.manifest.module") assert "error_history" in result + + +def test_configured_project_version_and_usage_retention_are_observable() -> None: + config = Config( + { + "project": {"name": "demo", "version": "2.1.0"}, + "sys_modules": {"enabled": True, "usage": {"retention_hours": 2, "bucketing_strategy": "hourly"}}, + } + ) + registry, executor, metrics = _make_deps() + with executor: + context = register_sys_modules(registry, executor, config, metrics_collector=metrics) + usage = context["usage_collector"] + now = datetime.now(timezone.utc) + usage.record("demo.module", "caller", 1.0, True, (now - timedelta(hours=5)).isoformat()) + usage.record("demo.module", "caller", 1.0, True, now.isoformat()) + assert executor.call("system.usage.summary")["total_calls"] == 1 + assert executor.call("system.health.summary")["project"] == {"name": "demo", "version": "2.1.0"} + + +def test_unsupported_bucketing_configuration_fails_before_registering_system_modules() -> None: + config = Config({"sys_modules": {"enabled": True, "usage": {"bucketing_strategy": "daily"}}}) + registry, executor, metrics = _make_deps() + with pytest.raises(ConfigError, match="sys_modules.usage.bucketing_strategy"): + register_sys_modules(registry, executor, config, metrics_collector=metrics) + assert registry.list() == [] diff --git a/python/tests/sys_modules/test_reload_dependents_deprecation.py b/python/tests/sys_modules/test_reload_dependents_deprecation.py index 2d2b6463..0530929d 100644 --- a/python/tests/sys_modules/test_reload_dependents_deprecation.py +++ b/python/tests/sys_modules/test_reload_dependents_deprecation.py @@ -1,86 +1,15 @@ -"""D-121 — `reload_dependents` is deprecated for removal. - -Declared in all three SDKs' input schemas and read by none: a spec MUST ("also -reload modules that depend on matched modules") that no implementation -satisfied. That is the §9.1.3 "declared surface reaches no mechanism" shape the -spec forbids for configuration keys, here applied to a module INPUT FIELD, and -three independent implementations skipping it is the evidence the maintainer -decision rests on — deprecate now, remove at 2.0, do NOT implement. - -The field is deprecated rather than removed today because the input schema sets -``additionalProperties: false``: at 2.0 the same call stops being a silent no-op -and becomes a VALIDATION ERROR, so a caller passing it needs a release in which -they are told. -""" - -from __future__ import annotations - -import logging +"""The reload module validates the supported input schema.""" +import jsonschema import pytest from apcore.sys_modules.control import ReloadModule -def _warnings(caplog: pytest.LogCaptureFixture) -> list[str]: - return [r.message for r in caplog.records if "reload_dependents" in r.getMessage()] - - -def _module() -> ReloadModule: - return ReloadModule(None, None) # type: ignore[arg-type] - - -class TestReloadDependentsDeprecation: - def test_passing_it_warns(self, caplog: pytest.LogCaptureFixture) -> None: - with caplog.at_level(logging.WARNING): - _module()._warn_reload_dependents({"reload_dependents": True, "reason": "x"}) - assert len(_warnings(caplog)) == 1 - - def test_the_warning_names_the_replacement_and_the_removal(self, caplog: pytest.LogCaptureFixture) -> None: - """A deprecation notice that does not say what to do instead, or when the - field stops being ignored, leaves the caller to discover both.""" - with caplog.at_level(logging.WARNING): - _module()._warn_reload_dependents({"reload_dependents": True, "reason": "x"}) - message = _warnings(caplog)[0] - assert "path_filter" in message - assert "2.0" in message - assert "validation error" in message - - def test_it_warns_once_per_instance(self, caplog: pytest.LogCaptureFixture) -> None: - """``reload`` is called by hot-reload loops and watchers, so an advisory - whose volume is proportional to traffic is one operators learn to filter - out — the cadence D-89 settled.""" - module = _module() - with caplog.at_level(logging.WARNING): - for _ in range(5): - module._warn_reload_dependents({"reload_dependents": True, "reason": "x"}) - assert len(_warnings(caplog)) == 1 - - def test_the_cadence_is_per_instance_not_per_process(self, caplog: pytest.LogCaptureFixture) -> None: - """A process-wide one-shot tells the FIRST caller and leaves every later - one to discover it in production — the reason D-90's notice is per token - and D-89's dedupe is per registry instance.""" - with caplog.at_level(logging.WARNING): - _module()._warn_reload_dependents({"reload_dependents": True, "reason": "x"}) - _module()._warn_reload_dependents({"reload_dependents": True, "reason": "x"}) - assert len(_warnings(caplog)) == 2 - - @pytest.mark.parametrize("inputs", [{"reason": "x"}, {"reload_dependents": False, "reason": "x"}]) - def test_control_omitting_it_or_passing_false_says_nothing( - self, inputs: dict[str, object], caplog: pytest.LogCaptureFixture - ) -> None: - """Without this, "it warns" is also satisfied by warning on every reload, - which is noise for the ordinary call the method exists for.""" - with caplog.at_level(logging.WARNING): - _module()._warn_reload_dependents(inputs) - assert _warnings(caplog) == [] - - def test_the_schema_marks_it_deprecated_and_says_what_replaces_it(self) -> None: - """The notice has to be readable without triggering it: a host reading - the input schema — which is what `describe`/`get_definition` hand an - agent — must see the deprecation without having to call with the field. - """ - field = ReloadModule.input_schema["properties"]["reload_dependents"] - assert field.get("deprecated") is True - assert "path_filter" in field["description"] - assert "2.0" in field["description"] +def test_reload_dependents_is_not_a_supported_property() -> None: + jsonschema.validate({"module_id": "example.module", "reason": "reload"}, ReloadModule.input_schema) + with pytest.raises(jsonschema.ValidationError, match="reload_dependents"): + jsonschema.validate( + {"module_id": "example.module", "reason": "reload", "reload_dependents": True}, + ReloadModule.input_schema, + ) diff --git a/python/tests/test_apcore_client_spec.py b/python/tests/test_apcore_client_spec.py index 07209331..698b9302 100644 --- a/python/tests/test_apcore_client_spec.py +++ b/python/tests/test_apcore_client_spec.py @@ -28,6 +28,7 @@ import pytest +from apcore.approval import AutoApproveHandler from apcore.client import APCore, _CallbackSubscriber from apcore.config import Config from apcore.context import Context @@ -652,6 +653,7 @@ def test_disable_input_reason_default() -> None: module disabled (enabled=False). reason defaults when omitted. """ client = APCore(config=_sys_config()) + client.executor.set_approval_handler(AutoApproveHandler()) @client.module(id="risky.module", description="A risky module") def risky() -> dict: @@ -670,6 +672,7 @@ def test_disable_property_idempotent_true() -> None: disabled (enabled stays False). """ client = APCore(config=_sys_config()) + client.executor.set_approval_handler(AutoApproveHandler()) @client.module(id="risky.dup", description="risky") def risky() -> dict: @@ -705,6 +708,7 @@ def test_enable_input_reason_default() -> None: enable() returns a result dict reporting the module enabled (enabled=True). """ client = APCore(config=_sys_config()) + client.executor.set_approval_handler(AutoApproveHandler()) @client.module(id="risky.enable", description="risky") def risky() -> dict: @@ -724,6 +728,7 @@ def test_enable_property_idempotent_true() -> None: True). """ client = APCore(config=_sys_config()) + client.executor.set_approval_handler(AutoApproveHandler()) @client.module(id="risky.reenable", description="risky") def risky() -> dict: diff --git a/python/tests/test_approval_executor.py b/python/tests/test_approval_executor.py index 6d9313c7..308a1ce8 100644 --- a/python/tests/test_approval_executor.py +++ b/python/tests/test_approval_executor.py @@ -22,6 +22,7 @@ from apcore.executor import Executor from apcore.module import ModuleAnnotations from apcore.pipeline import PipelineState +from apcore.policy import ExecutionPolicy from apcore.registry import Registry @@ -212,8 +213,8 @@ def registry() -> Registry: class TestApprovalGateSync: def test_gate_skipped_no_handler(self, registry: Registry) -> None: - """Gate is skipped when no approval_handler is configured.""" - executor = Executor(registry=registry) + """An explicit non-strict policy can continue without a handler.""" + executor = Executor(registry=registry, policy=ExecutionPolicy(strict=False)) result = executor.call("test.approval_required") assert result["status"] == "executed" @@ -282,9 +283,11 @@ def test_dict_annotations_approved(self, registry: Registry) -> None: def test_set_approval_handler(self, registry: Registry) -> None: """set_approval_handler() updates the handler.""" executor = Executor(registry=registry) - # No handler → executes - result = executor.call("test.approval_required") - assert result["status"] == "executed" + with pytest.raises(ApprovalDeniedError): + executor.call("test.approval_required") + + executor.set_approval_handler(AutoApproveHandler()) + assert executor.call("test.approval_required")["status"] == "executed" # Set deny handler → raises executor.set_approval_handler(AlwaysDenyHandler()) @@ -438,7 +441,7 @@ async def broken_handler(request: ApprovalRequest) -> ApprovalResult: class TestApprovalGateAsync: @pytest.mark.asyncio async def test_gate_skipped_no_handler(self, registry: Registry) -> None: - executor = Executor(registry=registry) + executor = Executor(registry=registry, policy=ExecutionPolicy(strict=False)) result = await executor.call_async("test.approval_required") assert result["status"] == "executed" @@ -591,7 +594,7 @@ async def test_audit_log_emitted_async(self, registry: Registry, caplog: pytest. def test_no_audit_log_when_gate_skipped(self, registry: Registry, caplog: pytest.LogCaptureFixture) -> None: """No audit log when gate is skipped (no handler or no requires_approval).""" - executor = Executor(registry=registry) + executor = Executor(registry=registry, policy=ExecutionPolicy(strict=False)) with caplog.at_level(logging.INFO, logger="apcore.builtin_steps"): executor.call("test.approval_required") diff --git a/python/tests/test_builtin_steps.py b/python/tests/test_builtin_steps.py index bbf7789d..58d0725c 100644 --- a/python/tests/test_builtin_steps.py +++ b/python/tests/test_builtin_steps.py @@ -809,12 +809,13 @@ async def test_stripped_when_the_module_is_not_gated(self) -> None: async def test_stripped_when_gated_but_no_handler_is_configured(self) -> None: from apcore.module import ModuleAnnotations + from apcore.policy import ExecutionPolicy ctx = self._ctx( {"x": 1, "_approval_token": "tok"}, annotations=ModuleAnnotations(requires_approval=True), ) - result = await BuiltinApprovalGate(handler=None).execute(ctx) + result = await BuiltinApprovalGate(policy=ExecutionPolicy(strict=False)).execute(ctx) assert result.action == "continue" assert "_approval_token" not in ctx.inputs diff --git a/python/tests/test_call_chain_published_signature.py b/python/tests/test_call_chain_published_signature.py index 68a2f97f..9001dd2d 100644 --- a/python/tests/test_call_chain_published_signature.py +++ b/python/tests/test_call_chain_published_signature.py @@ -29,9 +29,9 @@ def test_the_published_signature_is_reachable_from_the_package_root() -> None: import apcore - assert "guard_call_chain" in apcore.__all__ - assert "DEFAULT_MAX_CALL_DEPTH" in apcore.__all__ - assert "DEFAULT_MAX_MODULE_REPEAT" in apcore.__all__ + assert hasattr(apcore, "guard_call_chain") + assert hasattr(apcore, "DEFAULT_MAX_CALL_DEPTH") + assert hasattr(apcore, "DEFAULT_MAX_MODULE_REPEAT") from apcore import guard_call_chain diff --git a/python/tests/test_circuit_breaker_middleware.py b/python/tests/test_circuit_breaker_middleware.py index 97d77770..09ecea0b 100644 --- a/python/tests/test_circuit_breaker_middleware.py +++ b/python/tests/test_circuit_breaker_middleware.py @@ -87,7 +87,7 @@ def test_circuit_breaker_state_exported_from_top_level() -> None: ) assert apcore.CircuitBreakerState is MiddlewareState - assert "CircuitBreakerState" in apcore.__all__ + assert hasattr(apcore, "CircuitBreakerState") def test_circuit_breaker_state_has_expected_members() -> None: diff --git a/python/tests/test_client.py b/python/tests/test_client.py index 0a0f964b..1858db9f 100644 --- a/python/tests/test_client.py +++ b/python/tests/test_client.py @@ -814,6 +814,7 @@ class TestEnableDisable: def _make_client_with_module(self) -> APCore: """Create a client with sys_modules enabled and a test module registered.""" client = APCore(config=_sys_config()) + client.executor.set_approval_handler(AutoApproveHandler()) @client.module(id="math.add") def add(a: int, b: int) -> int: @@ -837,6 +838,7 @@ def test_enable_returns_success(self) -> None: def test_disable_nonexistent_raises(self) -> None: client = APCore(config=_sys_config()) + client.executor.set_approval_handler(AutoApproveHandler()) with pytest.raises(ModuleNotFoundError): client.disable("nonexistent.module") diff --git a/python/tests/test_conformance.py b/python/tests/test_conformance.py index 4450ef94..bff16974 100644 --- a/python/tests/test_conformance.py +++ b/python/tests/test_conformance.py @@ -1251,10 +1251,11 @@ def test_annotations_extra_round_trip(case: dict[str, Any]) -> None: import asyncio # noqa: E402 -from apcore.approval import ApprovalResult # noqa: E402 +from apcore.approval import ApprovalResult, AutoApproveHandler # noqa: E402 from apcore.builtin_steps import BuiltinApprovalGate # noqa: E402 from apcore.errors import ApprovalDeniedError, ApprovalPendingError, ApprovalTimeoutError # noqa: E402 from apcore.pipeline import PipelineContext # noqa: E402 +from apcore.policy import ExecutionPolicy # noqa: E402 _approval_data = _load("approval_gate") @@ -1351,7 +1352,9 @@ def test_approval_gate(case: dict[str, Any]) -> None: handler_type = _ScopedFixtureApprovalHandler if resume.get("scoped_handler") else _FixtureApprovalHandler handler = handler_type(case["approval_result"]) - gate = BuiltinApprovalGate(handler=handler if case["approval_handler_configured"] else None) + policy_data = case.get("execution_policy") + policy = ExecutionPolicy.from_dict(policy_data) if policy_data is not None else None + gate = BuiltinApprovalGate(handler=handler if case["approval_handler_configured"] else None, policy=policy) module = _FakeModule(requires_approval=_declared_requires_approval(case)) ctx_obj = Context.create() @@ -2510,6 +2513,7 @@ def _make_toggle_instance(module_ids: list[str]) -> APCore: # Fresh Config per instance so each APCore owns an independent ToggleState. config = Config(data={"sys_modules": {"enabled": True, "events": {"enabled": True}}}) client = APCore(config=config) + client.executor.set_approval_handler(AutoApproveHandler()) _register_noop_modules(client, module_ids) return client diff --git a/python/tests/test_context_logger_deprecation.py b/python/tests/test_context_logger_deprecation.py index 12789a88..9b3ed945 100644 --- a/python/tests/test_context_logger_deprecation.py +++ b/python/tests/test_context_logger_deprecation.py @@ -1,78 +1,7 @@ -"""`Context.logger` is deprecated (apcore#121), removed at v2.0. - -The decision is D-67's boundary applied to an API surface rather than a -configuration key: apcore does not own the host's logging policy, and this -accessor's output is fixed at stderr / `info` / JSON no matter what the host has -configured. Wiring it instead was rejected on a cost that is not effort — the -logger is built from a `Context`, which carries no `Config` in any SDK, so the -only route avoiding `Context.create`'s pinned signature is a process-global -logger, which would end the multi-instance isolation apcore gets for free. - -`ObsLoggingMiddleware` is deliberately NOT named as the migration target here: -it emits apcore's execution events, which is a different facility. -""" - -from __future__ import annotations - -import warnings - -import pytest +"""Applications own contextual logging.""" from apcore.context import Context -from apcore.observability.context_logger import ContextLogger - - -def test_accessing_the_logger_warns() -> None: - context = Context(trace_id="t-1", caller_id="api.probe") - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - context.logger - notices = [w for w in caught if issubclass(w.category, DeprecationWarning)] - assert len(notices) == 1 - message = str(notices[0].message) - assert "removed in version 2.0" in message - assert "host application's logger" in message - assert "apcore#121" in message - - -def test_it_still_works_through_the_1_x_line() -> None: - """A deprecation is a notice, not a removal — §13.2's two-minor floor. - - The accessor keeps returning a logger carrying this context's correlation - fields until v2.0, so a project that has not migrated yet still runs. - """ - context = Context(trace_id="t-1", caller_id="api.probe") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - logger = context.logger - assert isinstance(logger, ContextLogger) - assert logger._trace_id == "t-1" - assert logger._caller_id == "api.probe" - - -def test_no_apcore_code_path_reaches_it() -> None: - """The premise of deprecating rather than wiring: nothing internal uses it. - - Written as a test rather than left as a claim in the issue, because it is - what makes removal at v2.0 safe for the framework itself. A future caller - inside `src/` fails here and has to argue for itself. - """ - import pathlib - - src = pathlib.Path(__file__).resolve().parent.parent / "src" / "apcore" - hits = [ - f"{path.relative_to(src)}:{n}" - for path in src.rglob("*.py") - for n, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1) - if ("context.logger" in line or "ctx.logger" in line) and "def logger" not in line - ] - assert hits == [], f"apcore's own code now reaches Context.logger: {hits}" - -@pytest.mark.filterwarnings("error::DeprecationWarning") -def test_nothing_in_the_import_path_touches_it() -> None: - """Importing and building a client must not trip the notice itself.""" - from apcore import APCore - from apcore.config import Config - APCore(config=Config({"version": "1.0", "project": {"name": "p"}})) +def test_context_has_no_deprecated_logger_property() -> None: + assert not hasattr(Context.create(), "logger") diff --git a/python/tests/test_context_serialization.py b/python/tests/test_context_serialization.py index 76ecb071..5c06f403 100644 --- a/python/tests/test_context_serialization.py +++ b/python/tests/test_context_serialization.py @@ -115,7 +115,7 @@ def test_deserialize_executor_is_none(self) -> None: # Under the unified Context.create() signature (Issue #66), executor # is no longer a constructor input; binding happens via the private # helper. - ctx._bind_executor("some-executor") + ctx.bind_executor("some-executor") serialized = ctx.serialize() restored = Context.deserialize(serialized) assert restored.executor is None diff --git a/python/tests/test_deep_chain_v150.py b/python/tests/test_deep_chain_v150.py index 341cb563..5181a304 100644 --- a/python/tests/test_deep_chain_v150.py +++ b/python/tests/test_deep_chain_v150.py @@ -12,6 +12,7 @@ import pytest +from apcore.approval import AutoApproveHandler from apcore import APCore, Config from apcore.executor import Executor from apcore.registry import Registry @@ -79,7 +80,7 @@ def test_supplied_registry_is_ignored_when_executor_is_given(self): def test_sys_modules_are_registered_where_the_executor_looks(self): config = Config({"sys_modules": {"enabled": True, "events": {"enabled": True}}}) my_registry = Registry() - client = APCore(executor=Executor(registry=my_registry), config=config) + client = APCore(executor=Executor(registry=my_registry, approval_handler=AutoApproveHandler()), config=config) client.register("x.y", _make_module("x.y")) result = client.disable("x.y") @@ -713,7 +714,7 @@ def test_it_is_exported_from_the_package_root(self): import apcore assert hasattr(apcore, "TaskStoreError") - assert "TaskStoreError" in apcore.__all__ + assert hasattr(apcore, "TaskStoreError") def test_it_carries_the_registry_code(self): from apcore.errors import ErrorCodes, TaskStoreError diff --git a/python/tests/test_event_naming_and_identity.py b/python/tests/test_event_naming_and_identity.py index 6ee0db7f..2ef38e49 100644 --- a/python/tests/test_event_naming_and_identity.py +++ b/python/tests/test_event_naming_and_identity.py @@ -193,11 +193,8 @@ def test_latency_threshold_emits_canonical_only(self) -> None: class TestPublicSubscriberFactoryAPI: - def test_register_subscriber_factory_and_create_from_config(self) -> None: - from apcore.events import ( - create_subscriber_from_config, - register_subscriber_factory, - ) + def test_instance_factory_registers_and_creates_from_config(self) -> None: + from apcore.events import SubscriberRegistry class CustomSub: def __init__(self, value: str) -> None: @@ -209,16 +206,11 @@ async def on_event(self, event: ApCoreEvent) -> None: def factory(cfg: dict) -> EventSubscriber: return CustomSub(value=cfg["value"]) - register_subscriber_factory("__test_custom__", factory) - try: - sub = create_subscriber_from_config({"type": "__test_custom__", "value": "hello"}) - assert isinstance(sub, CustomSub) - assert sub.value == "hello" - finally: - # Clean up the custom factory so other tests are not affected - from apcore.sys_modules.registration import unregister_subscriber_type - - unregister_subscriber_type("__test_custom__") + registry = SubscriberRegistry() + registry.register("__test_custom__", factory) + sub = registry.create({"type": "__test_custom__", "value": "hello"}) + assert isinstance(sub, CustomSub) + assert sub.value == "hello" def test_create_subscriber_from_config_supports_builtin_types(self) -> None: from apcore.events import create_subscriber_from_config @@ -236,7 +228,7 @@ def test_create_subscriber_from_config_unknown_type_raises(self) -> None: def test_public_factory_api_exported_from_apcore_events(self) -> None: import apcore.events as events_pkg - assert hasattr(events_pkg, "register_subscriber_factory") + assert hasattr(events_pkg, "SubscriberRegistry") assert hasattr(events_pkg, "create_subscriber_from_config") diff --git a/python/tests/test_event_system_spec.py b/python/tests/test_event_system_spec.py index a63e69f7..ad9f1e70 100644 --- a/python/tests/test_event_system_spec.py +++ b/python/tests/test_event_system_spec.py @@ -10,7 +10,7 @@ - ``EventEmitter.emit`` takes a single ``ApCoreEvent`` (not ``event_type`` / ``payload``) and raises no errors (fire-and-forget). The spec's ``input.event_type.not_empty`` rule is not enforced by this SDK. -- ``WebhookSubscriber.deliver`` / ``A2ASubscriber.deliver`` are named +- ``WebhookSubscriber.deliver`` are named ``on_event`` in this SDK. The emitter owns retry and dead-letter delivery. - The circuit-breaker contract names ``SubscriberCircuitBreaker.on_failure`` with signature ``(subscriber_id, error) -> CircuitState``. This SDK ships @@ -29,7 +29,7 @@ from apcore.events.circuit_breaker import CircuitBreakerWrapper, CircuitState from apcore.events.emitter import ApCoreEvent, EventEmitter -from apcore.events.subscribers import A2ASubscriber, WebhookSubscriber +from apcore.events.subscribers import WebhookSubscriber # --------------------------------------------------------------------------- @@ -348,7 +348,7 @@ def test_webhook_deliver_input_event_required() -> None: sub = WebhookSubscriber(url="https://example.com/hook") event = _make_event(event_type="apcore.health.recovered") mock_aiohttp, session = _mock_aiohttp(status=200) - with patch("apcore.events.subscribers.aiohttp", mock_aiohttp): + with patch("apcore.events.subscribers._load_aiohttp", return_value=mock_aiohttp): asyncio.run(sub.on_event(event)) session.post.assert_called_once() posted = session.post.call_args.kwargs["json"] @@ -363,7 +363,7 @@ def test_webhook_deliver_property_async_true() -> None: sub = WebhookSubscriber(url="https://example.com/hook") assert asyncio.iscoroutinefunction(sub.on_event) mock_aiohttp, _ = _mock_aiohttp(status=200) - with patch("apcore.events.subscribers.aiohttp", mock_aiohttp): + with patch("apcore.events.subscribers._load_aiohttp", return_value=mock_aiohttp): coro = sub.on_event(_make_event()) assert asyncio.iscoroutine(coro) assert asyncio.run(coro) is None @@ -379,7 +379,7 @@ def test_webhook_deliver_property_thread_safe() -> None: mock_aiohttp, session = _mock_aiohttp(status=200) async def run_all() -> None: - with patch("apcore.events.subscribers.aiohttp", mock_aiohttp): + with patch("apcore.events.subscribers._load_aiohttp", return_value=mock_aiohttp): await asyncio.gather(*[sub.on_event(_make_event(data={"i": i})) for i in range(8)]) asyncio.run(run_all()) @@ -393,7 +393,7 @@ def test_webhook_deliver_property_pure_false() -> None: """ sub = WebhookSubscriber(url="https://example.com/hook") mock_aiohttp, session = _mock_aiohttp(status=200) - with patch("apcore.events.subscribers.aiohttp", mock_aiohttp): + with patch("apcore.events.subscribers._load_aiohttp", return_value=mock_aiohttp): asyncio.run(sub.on_event(_make_event())) session.post.assert_called_once() # outbound side effect occurred @@ -408,13 +408,13 @@ def test_webhook_deliver_side_effect_1_retry_on_5xx() -> None: sub = WebhookSubscriber(url="https://example.com/hook") mock_5xx, _ = _mock_aiohttp(status=503) - with patch("apcore.events.subscribers.aiohttp", mock_5xx): + with patch("apcore.events.subscribers._load_aiohttp", return_value=mock_5xx): with pytest.raises(RuntimeError): asyncio.run(sub.on_event(event)) sub2 = WebhookSubscriber(url="https://example.com/hook") mock_4xx, _ = _mock_aiohttp(status=404) - with patch("apcore.events.subscribers.aiohttp", mock_4xx): + with patch("apcore.events.subscribers._load_aiohttp", return_value=mock_4xx): # 4xx is a permanent failure: logged, not raised. assert asyncio.run(sub2.on_event(event)) is None @@ -790,133 +790,3 @@ def test_flush_property_idempotent_true() -> None: finally: emitter.shutdown(timeout=1.0) assert count_after_first == count_after_second == 1 - - -# =========================================================================== -# Contract: A2ASubscriber.deliver -# =========================================================================== - - -def test_a2a_deliver_input_event_required() -> None: - """event_system.deliver.input.event.required_a2a - - A2A delivery (on_event) POSTs a {skillId, event} wrapper carrying the - serialized event. - """ - sub = A2ASubscriber(platform_url="https://platform.example.com") - event = _make_event(event_type="apcore.health.recovered") - mock_aiohttp, session = _mock_aiohttp(status=200) - with patch("apcore.events.subscribers.aiohttp", mock_aiohttp): - asyncio.run(sub.on_event(event)) - session.post.assert_called_once() - body = session.post.call_args.kwargs["json"] - assert body["skillId"] == "apevo.event_receiver" - assert body["event"]["event_type"] == "apcore.health.recovered" - - -def test_a2a_deliver_error_import_error_without_aiohttp() -> None: - """event_system.deliver.error.ImportError_a2a - - ImportError is raised synchronously (before network I/O) if aiohttp is not - installed, with the documented install hint. - """ - sub = A2ASubscriber(platform_url="https://platform.example.com") - with patch("apcore.events.subscribers.aiohttp", None): - with pytest.raises(ImportError, match=r"aiohttp is required.*apcore\[events\]"): - asyncio.run(sub.on_event(_make_event())) - - -def test_a2a_deliver_property_async_true() -> None: - """event_system.deliver.property.async_a2a - - A2A delivery is awaitable and resolves to None. - """ - sub = A2ASubscriber(platform_url="https://platform.example.com") - assert asyncio.iscoroutinefunction(sub.on_event) - mock_aiohttp, _ = _mock_aiohttp(status=200) - with patch("apcore.events.subscribers.aiohttp", mock_aiohttp): - coro = sub.on_event(_make_event()) - assert asyncio.iscoroutine(coro) - assert asyncio.run(coro) is None - - -def test_a2a_deliver_property_thread_safe() -> None: - """event_system.deliver.property.thread_safe_a2a - - >=8 concurrent A2A deliveries with distinct events all resolve; each issues - its own POST. - """ - sub = A2ASubscriber(platform_url="https://platform.example.com") - mock_aiohttp, session = _mock_aiohttp(status=200) - - async def run_all() -> None: - with patch("apcore.events.subscribers.aiohttp", mock_aiohttp): - await asyncio.gather(*[sub.on_event(_make_event(data={"i": i})) for i in range(8)]) - - asyncio.run(run_all()) - assert session.post.call_count == 8 - - -def test_a2a_deliver_property_pure_false() -> None: - """event_system.deliver.property.pure_a2a - - Delivery is NOT pure: it performs an outbound HTTP POST to the platform URL. - """ - sub = A2ASubscriber(platform_url="https://platform.example.com") - mock_aiohttp, session = _mock_aiohttp(status=200) - with patch("apcore.events.subscribers.aiohttp", mock_aiohttp): - asyncio.run(sub.on_event(_make_event())) - assert session.post.call_args.args[0] == "https://platform.example.com" - - -def test_a2a_deliver_side_effect_1_auth_bearer_header() -> None: - """event_system.deliver.side_effect.1.auth_modes_a2a - - Observable auth policy: a str auth -> 'Authorization: Bearer '; - a dict auth -> keys merged into headers; None -> no Authorization header. - """ - event = _make_event() - - # str auth -> Bearer - sub_str = A2ASubscriber(platform_url="https://p.example.com", auth="tok123") - mock_str, session_str = _mock_aiohttp(status=200) - with patch("apcore.events.subscribers.aiohttp", mock_str): - asyncio.run(sub_str.on_event(event)) - headers_str = session_str.post.call_args.kwargs["headers"] - assert headers_str["Authorization"] == "Bearer tok123" - - # dict auth -> merged - sub_dict = A2ASubscriber(platform_url="https://p.example.com", auth={"X-Api-Key": "k"}) - mock_dict, session_dict = _mock_aiohttp(status=200) - with patch("apcore.events.subscribers.aiohttp", mock_dict): - asyncio.run(sub_dict.on_event(event)) - headers_dict = session_dict.post.call_args.kwargs["headers"] - assert headers_dict["X-Api-Key"] == "k" - - # None auth -> no Authorization - sub_none = A2ASubscriber(platform_url="https://p.example.com", auth=None) - mock_none, session_none = _mock_aiohttp(status=200) - with patch("apcore.events.subscribers.aiohttp", mock_none): - asyncio.run(sub_none.on_event(event)) - headers_none = session_none.post.call_args.kwargs["headers"] - assert "Authorization" not in headers_none - - -def test_a2a_deliver_side_effect_2_retry_on_5xx() -> None: - """event_system.deliver.side_effect.2.retry_on_5xx_a2a - - Observable HTTP-status policy for A2A: 5xx raises (emitter retries); - 4xx does not raise (no retry). - """ - event = _make_event() - - sub_5xx = A2ASubscriber(platform_url="https://p.example.com") - mock_5xx, _ = _mock_aiohttp(status=502) - with patch("apcore.events.subscribers.aiohttp", mock_5xx): - with pytest.raises(RuntimeError): - asyncio.run(sub_5xx.on_event(event)) - - sub_4xx = A2ASubscriber(platform_url="https://p.example.com") - mock_4xx, _ = _mock_aiohttp(status=403) - with patch("apcore.events.subscribers.aiohttp", mock_4xx): - assert asyncio.run(sub_4xx.on_event(event)) is None diff --git a/python/tests/test_executor.py b/python/tests/test_executor.py index 69d3172f..cd8527b4 100644 --- a/python/tests/test_executor.py +++ b/python/tests/test_executor.py @@ -545,7 +545,7 @@ def test_validate_with_foreign_bound_context_does_not_raise(self) -> None: ex_b = _make_executor(module=MockModule()) ctx = Context.create() - ctx._bind_executor(ex_b) # bind to a different executor + ctx.bind_executor(ex_b) # bind to a different executor result = ex_a.validate("test.module", {"name": "Alice", "age": 30}, context=ctx) assert result.valid is False diff --git a/python/tests/test_executor_async.py b/python/tests/test_executor_async.py index 35b86fb2..8d0b6b01 100644 --- a/python/tests/test_executor_async.py +++ b/python/tests/test_executor_async.py @@ -6,7 +6,7 @@ import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path -from threading import Event, current_thread +from threading import Barrier, Event, current_thread from typing import Any import pytest @@ -14,7 +14,7 @@ from apcore.builtin_steps import build_standard_strategy from apcore.config import Config from apcore.context import Context -from apcore.errors import ModuleTimeoutError +from apcore.errors import ModuleError, ModuleTimeoutError from apcore.executor import Executor from apcore.middleware import Middleware from apcore.registry import Registry @@ -136,7 +136,7 @@ class TestCallSyncWithAsyncModule: """Tests for sync call() bridging to async modules.""" def test_bridges_async_no_running_loop(self) -> None: - """call() with async module uses asyncio.run when no loop running.""" + """call() with async module works without a running loop.""" ex = _make_executor(module=AsyncModule()) result = ex.call("test.module", {"name": "Dave"}) assert result == {"greeting": "Hello, Dave"} @@ -157,47 +157,116 @@ async def inner(): finally: loop.close() - def test_concurrent_callers_cannot_both_start_the_cached_loop(self, monkeypatch: pytest.MonkeyPatch) -> None: - first_at_run = Event() - second_executing = Event() - release_second = Event() + def test_concurrent_callers_own_and_reuse_distinct_loops(self) -> None: + entered = Barrier(2, timeout=5) + observations: dict[str, tuple[asyncio.AbstractEventLoop, str]] = {} - class CoordinatedModule(AsyncModule): + class LoopRecorder(AsyncModule): async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: - if inputs.get("name") == "second": - second_executing.set() - assert release_second.wait(5) + observations[inputs["name"]] = asyncio.get_running_loop(), current_thread().name + if inputs["name"].endswith("first"): + entered.wait() return await super().execute(inputs, context) - with _make_executor(module=CoordinatedModule()) as ex: - ex.call("test.module", {}) - loop = ex._sync_loop - assert loop is not None - run = loop.run_until_complete + def call_twice(prefix: str) -> str: + owner = current_thread().name + ex.call("test.module", {"name": f"{prefix}-first"}) + ex.call("test.module", {"name": f"{prefix}-again"}) + return owner + + with _make_executor(module=LoopRecorder()) as ex, ThreadPoolExecutor(2) as callers: + calls = {prefix: callers.submit(call_twice, prefix) for prefix in ("one", "two")} + for prefix, result in calls.items(): + owner = result.result(timeout=5) + first, executing_thread = observations[f"{prefix}-first"] + assert executing_thread == owner + assert observations[f"{prefix}-again"] == (first, owner) + assert observations["one-first"][0] is not observations["two-first"][0] + + def test_close_retires_an_active_thread_loop_and_allows_reuse(self) -> None: + entered = Event() + release = Event() + loops: list[asyncio.AbstractEventLoop] = [] + + class PausingModule(AsyncModule): + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + loops.append(asyncio.get_running_loop()) + if inputs.get("name") == "pause": + entered.set() + assert release.wait(5) + return await super().execute(inputs, context) - def pause_first(coro: Any) -> Any: - if current_thread().name.startswith("first-caller"): - first_at_run.set() - assert second_executing.wait(5) - try: - return run(coro) - except RuntimeError: - coro.close() - raise - - monkeypatch.setattr(loop, "run_until_complete", pause_first) - with ( - ThreadPoolExecutor(1, thread_name_prefix="first-caller") as first, - ThreadPoolExecutor(1) as second, - ): - first_result = first.submit(ex.call, "test.module", {"name": "first"}) + with _make_executor(module=PausingModule()) as ex, ThreadPoolExecutor(1) as caller: + first = caller.submit(ex.call, "test.module", {"name": "pause"}) + try: + assert entered.wait(5) + ex.close() + assert not loops[0].is_closed() + finally: + release.set() + assert first.result(timeout=5) == {"greeting": "Hello, pause"} + assert loops[0].is_closed() + assert caller.submit(ex.call, "test.module").result(timeout=5) == {"greeting": "Hello, World"} + assert loops[1] is not loops[0] + ex.close() + assert loops[1].is_closed() + + def test_nested_loop_bridge_bounds_admission_across_close(self) -> None: + entered = Barrier(5, timeout=5) + release = Event() + observed: list[str] = [] + + class PausingModule(AsyncModule): + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + name = inputs["name"] + observed.append(name) + if name.startswith("active"): + entered.wait() + assert release.wait(5) + return await super().execute(inputs, context) + + def run_inside_loop(name: str, timeout_ms: int = 0) -> dict[str, Any]: + async def invoke() -> dict[str, Any]: + return ex.call("test.module", {"name": name}, timeout_ms=timeout_ms) + + return asyncio.run(invoke()) + + with _make_executor(module=PausingModule()) as ex, ThreadPoolExecutor(4) as callers: + calls = [callers.submit(run_inside_loop, f"active{i}") for i in range(4)] + try: + entered.wait() + ex.close() + with pytest.raises(ModuleTimeoutError) as caught: + run_inside_loop("expired", timeout_ms=40) + assert caught.value.details["timeout_ms"] == 40 + finally: + release.set() + assert [call.result(timeout=5)["greeting"] for call in calls] == [f"Hello, active{i}" for i in range(4)] + assert run_inside_loop("fresh") == {"greeting": "Hello, fresh"} + assert "expired" not in observed + + def test_reentrant_bridge_does_not_wait_for_its_own_pool_when_saturated(self) -> None: + entered = Barrier(4, timeout=5) + + class NestingModule(AsyncModule): + async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + entered.wait() try: - assert first_at_run.wait(5) - second_result = second.submit(ex.call, "test.module", {"name": "second"}) - assert first_result.result(timeout=5) == {"greeting": "Hello, first"} - finally: - release_second.set() - assert second_result.result(timeout=5) == {"greeting": "Hello, second"} + return ex.call("test.inner", timeout_ms=0) + except ModuleError as exc: + assert "Sync bridge is busy" in str(exc) + return {"greeting": "Pool full"} + + def run_inside_loop() -> dict[str, Any]: + async def invoke() -> dict[str, Any]: + return ex.call("test.module", timeout_ms=1000) + + return asyncio.run(invoke()) + + with _make_executor(module=NestingModule()) as ex, ThreadPoolExecutor(4) as callers: + ex.registry.register("test.inner", AsyncModule()) + calls = [callers.submit(run_inside_loop) for _ in range(4)] + assert "Pool full" in [call.result(timeout=5)["greeting"] for call in calls] def test_shared_executor_handles_repeated_sync_calls_from_worker_threads(self) -> None: with _make_executor(module=AsyncModule()) as ex, ThreadPoolExecutor(8) as workers: diff --git a/python/tests/test_full_assembly.py b/python/tests/test_full_assembly.py new file mode 100644 index 00000000..a76d2ae1 --- /dev/null +++ b/python/tests/test_full_assembly.py @@ -0,0 +1,117 @@ +"""Check the full assembly from the same public entry point as application code.""" + +import subprocess +import sys +from pathlib import Path +from textwrap import dedent + +from apcore import APCore as CoreClient +from apcore.discovery import Registry as DiscoveryRegistry +from apcore.full import APCore, Config, Registry + + +def test_root_runs_in_memory_without_importing_optional_dependencies() -> None: + subprocess.run( + [ + sys.executable, + "-c", + dedent( + """ + import asyncio + import sys + from importlib.abc import MetaPathFinder + + class BlockOptionalImports(MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname == 'http.server' or fullname.split('.')[0] in { + 'yaml', 'watchdog', 'aiohttp', 'opentelemetry' + }: + raise AssertionError(f'Kernel imported optional dependency {fullname}') + + sys.meta_path.insert(0, BlockOptionalImports()) + from apcore import APCore + + app = APCore() + + @app.module(id='example.add') + def add(left: int, right: int) -> int: + return left + right + + async def exercise(): + assert (await app.executor.validate_async('example.add', {'left': 2, 'right': 3})).valid + assert await app.call_async('example.add', {'left': 2, 'right': 3}) == {'result': 5} + + asyncio.run(exercise()) + app.close() + """ + ), + ], + check=True, + ) + + +def test_full_entry_assembles_configured_discovery(tmp_path: Path) -> None: + extensions = tmp_path / "extensions" + extensions.mkdir() + config_file = tmp_path / "apcore.yaml" + config_file.write_text( + "version: 1.0.0\nproject: {name: full-assembly}\nextensions: {root: ./extensions}\n", + encoding="utf-8", + ) + config = Config.load(str(config_file)) + client = APCore(config=config) + try: + assert isinstance(client, CoreClient) + assert isinstance(client.registry, Registry) + assert isinstance(client.registry, DiscoveryRegistry) + assert client.discover() == 0 + assert client.config is config + assert client.executor.governance_state().policy_strict + finally: + client.close() + + +def test_clients_resolve_filtered_subscribers_from_their_own_factories() -> None: + from apcore.events import ApCoreEvent, SubscriberRegistry + + received: list[list[str]] = [[], []] + + class Sink: + subscriber_id = "test-sink" + event_pattern = "*" + + def __init__(self, destination: list[str]) -> None: + self.destination = destination + + async def on_event(self, event: ApCoreEvent) -> None: + self.destination.append(event.event_type) + + def build_client(destination: list[str]) -> CoreClient: + subscribers = SubscriberRegistry() + subscribers.register("local_sink", lambda _: Sink(destination)) + config = Config( + { + "sys_modules": { + "enabled": True, + "control": {"enabled": False}, + "events": { + "enabled": True, + "subscribers": [ + {"type": "filter", "delegate_type": "local_sink", "include_events": ["test.*"]} + ], + }, + }, + } + ) + return APCore(config=config, subscriber_registry=subscribers) + + clients = [build_client(destination) for destination in received] + try: + for index, client in enumerate(clients): + assert client.events is not None + client.events.emit(ApCoreEvent(f"test.event_{index}", None, "2026-01-01T00:00:00Z", "info", {})) + client.events.flush(timeout=5) + assert received == [["test.event_0"], ["test.event_1"]] + finally: + for client in clients: + client.close() diff --git a/python/tests/test_governance_state.py b/python/tests/test_governance_state.py index c744f9b9..7e25cc7a 100644 --- a/python/tests/test_governance_state.py +++ b/python/tests/test_governance_state.py @@ -50,7 +50,9 @@ def test_read_modules_only_is_not_a_control_surface(self) -> None: assert state.unprotected_control_surface is False def test_control_modules_present_with_no_gates(self) -> None: - state = _client(SYS_ON).executor.governance_state() + client = _client(SYS_ON) + client.executor.set_policy(ExecutionPolicy(strict=False)) + state = client.executor.governance_state() assert state.control_modules_registered is True assert state.read_modules_registered is True assert state.unprotected_control_surface is True diff --git a/python/tests/test_observability_spec.py b/python/tests/test_observability_spec.py index e9c7f13f..9199ee0b 100644 --- a/python/tests/test_observability_spec.py +++ b/python/tests/test_observability_spec.py @@ -8,7 +8,7 @@ 2. ``MetricsEmitter.record`` — MISSING SYMBOL in apcore-python (no ``MetricsEmitter`` class; the SDK exposes ``MetricsCollector`` instead). Documented as skips. - 3. ``PrometheusExporter.export``— PRESENT and fully exercised. + 3. ``render_prometheus_metrics``— PRESENT and fully exercised. Each test's docstring carries the verbatim clause id formatted ``observability...`` so cross-language diffs line up @@ -25,7 +25,7 @@ import pytest from apcore.observability.metrics import MetricsCollector -from apcore.observability.prometheus_exporter import PrometheusExporter +from apcore.observability import render_prometheus_metrics # --------------------------------------------------------------------------- # Missing-symbol detection (keeps the whole file importable / runnable). @@ -175,19 +175,15 @@ def test_metrics_emitter_record_property_pure_is_false() -> None: # =========================================================================== -# Contract 3: PrometheusExporter.export (PRESENT — fully exercised) -# -# Source note: in apcore-python the `collector` from the contract's ### Inputs -# is supplied at construction (`PrometheusExporter(collector=...)`), and -# `export()` takes no arguments and returns the Prometheus text string. +# Contract 3: render_prometheus_metrics # =========================================================================== -def _exporter_with_one_counter() -> PrometheusExporter: +def _collector_with_one_counter() -> MetricsCollector: """Build an exporter over a collector carrying a single known counter.""" collector = MetricsCollector() collector.increment_calls("math.add", "success") - return PrometheusExporter(collector=collector) + return collector def test_prometheus_export_input_collector_required() -> None: @@ -200,13 +196,12 @@ def test_prometheus_export_input_collector_required() -> None: """ # Negative: the required `collector` arg cannot be omitted. with pytest.raises(TypeError): - PrometheusExporter() # type: ignore[call-arg] + render_prometheus_metrics() # type: ignore[call-arg] # Positive: a supplied collector's data is what `export()` renders. collector = MetricsCollector() collector.increment_calls("math.add", "success") - exporter = PrometheusExporter(collector=collector) - text = exporter.export() + text = render_prometheus_metrics(collector) assert "apcore_module_calls_total" in text assert 'module_id="math.add"' in text assert 'status="success"' in text @@ -219,8 +214,8 @@ def test_prometheus_export_error_none_does_not_propagate() -> None: propagate to callers. Exporting over an empty collector must return a string (empty exposition) without raising. """ - exporter = PrometheusExporter(collector=MetricsCollector()) - text = exporter.export() + collector = MetricsCollector() + text = render_prometheus_metrics(collector) assert isinstance(text, str) @@ -231,8 +226,8 @@ def test_prometheus_export_returns_prometheus_text() -> None: Output must be a UTF-8-encodable string and, for populated collectors, carry the canonical HELP/TYPE comment lines. """ - exporter = _exporter_with_one_counter() - text = exporter.export() + collector = _collector_with_one_counter() + text = render_prometheus_metrics(collector) assert isinstance(text, str) # Round-trips through UTF-8 without loss. assert text.encode("utf-8").decode("utf-8") == text @@ -247,8 +242,8 @@ def test_prometheus_export_property_async_is_false() -> None: Spec ### Properties: async: false. `export()` MUST be a plain synchronous call returning a concrete str (not a coroutine / awaitable). """ - exporter = _exporter_with_one_counter() - result = exporter.export() + collector = _collector_with_one_counter() + result = render_prometheus_metrics(collector) assert isinstance(result, str) assert not asyncio.iscoroutine(result) assert not asyncio.isfuture(result) @@ -261,11 +256,11 @@ def test_prometheus_export_property_thread_safe() -> None: over a shared exporter via asyncio.gather; assert no exception is raised and every result is a consistent, identical snapshot string. """ - exporter = _exporter_with_one_counter() + collector = _collector_with_one_counter() async def do_export() -> str: await asyncio.sleep(0) - return exporter.export() + return render_prometheus_metrics(collector) async def run() -> list[str]: return await asyncio.gather(*[do_export() for _ in range(12)]) @@ -288,10 +283,9 @@ def test_prometheus_export_property_pure_reads_live_state() -> None: """ collector = MetricsCollector() collector.increment_calls("math.add", "success") - exporter = PrometheusExporter(collector=collector) before = collector.snapshot() - first = exporter.export() + first = render_prometheus_metrics(collector) after = collector.snapshot() # export() is a query: it does not mutate collector state. assert before == after @@ -299,7 +293,7 @@ def test_prometheus_export_property_pure_reads_live_state() -> None: # Live-state coupling: a new module appears on the next export. collector.increment_calls("math.sub", "success") - second = exporter.export() + second = render_prometheus_metrics(collector) assert 'module_id="math.sub"' in second assert 'module_id="math.sub"' not in first @@ -311,8 +305,8 @@ def test_prometheus_export_property_idempotent() -> None: (unchanged) collector state MUST produce identical output and leave the observable collector state identical. """ - exporter = _exporter_with_one_counter() - first = exporter.export() - second = exporter.export() + collector = _collector_with_one_counter() + first = render_prometheus_metrics(collector) + second = render_prometheus_metrics(collector) assert first == second assert first != "" diff --git a/python/tests/test_policy.py b/python/tests/test_policy.py index 43b4f680..4c20622c 100644 --- a/python/tests/test_policy.py +++ b/python/tests/test_policy.py @@ -16,6 +16,7 @@ from apcore import ExecutionPolicy, PolicyDecision, PolicyRule from apcore.approval import AlwaysDenyHandler, ApprovalRequest, ApprovalResult, AutoApproveHandler +from apcore.builtin_steps import build_standard_strategy from apcore.context import Context from apcore.errors import ApprovalDeniedError from apcore.executor import Executor @@ -95,6 +96,19 @@ def registry() -> Registry: return reg +@pytest.mark.parametrize("strict", [True, False]) +def test_prebuilt_strategy_retains_its_policy_for_preflight_and_execution(registry: Registry, strict: bool) -> None: + strategy = build_standard_strategy(registry=registry, policy=ExecutionPolicy(strict=strict, gate_destructive=True)) + with Executor(registry, strategy=strategy) as executor: + assert executor.validate("orders.delete_order").requires_approval + assert executor.governance_state().policy_strict is strict + if strict: + with pytest.raises(ApprovalDeniedError): + executor.call("orders.delete_order") + else: + assert executor.call("orders.delete_order") == {"status": "executed"} + + # --------------------------------------------------------------------------- # PolicyRule validation # --------------------------------------------------------------------------- @@ -151,8 +165,8 @@ def test_full_document(self) -> None: def test_empty_document(self) -> None: policy = ExecutionPolicy.from_dict({}) assert policy.rules == () - assert policy.gate_destructive is False - assert policy.strict is False + assert policy.gate_destructive is True + assert policy.strict is True def test_non_mapping_rejected(self) -> None: with pytest.raises(ValueError, match="mapping"): @@ -320,8 +334,8 @@ def test_strict_policy_without_gated_modules_executes(self, registry: Registry) assert result["status"] == "executed" def test_no_handler_warns_once_and_skips(self, registry: Registry, caplog: pytest.LogCaptureFixture) -> None: - """Fail-loud default: requires_approval without a handler skips per spec but warns once.""" - executor = Executor(registry=registry) + """Explicit compatibility warns once before continuing without a handler.""" + executor = Executor(registry=registry, policy=ExecutionPolicy(strict=False)) with caplog.at_level(logging.WARNING, logger="apcore.builtin_steps"): result = executor.call("admin.reset") assert result["status"] == "executed" @@ -333,7 +347,7 @@ def test_no_handler_warns_once_and_skips(self, registry: Registry, caplog: pytes assert "admin.reset" in warnings[0].getMessage() def test_destructive_ungated_warns_once(self, registry: Registry, caplog: pytest.LogCaptureFixture) -> None: - executor = Executor(registry=registry) + executor = Executor(registry=registry, policy=ExecutionPolicy(gate_destructive=False)) with caplog.at_level(logging.WARNING, logger="apcore.builtin_steps"): executor.call("orders.delete_order") executor.call("orders.delete_order") @@ -376,7 +390,9 @@ def test_no_audit_when_policy_does_not_override(self, registry: Registry, caplog assert [r for r in caplog.records if "Policy override" in r.message] == [] def test_set_policy_at_runtime(self, registry: Registry) -> None: - executor = Executor(registry=registry, approval_handler=AlwaysDenyHandler()) + executor = Executor( + registry=registry, approval_handler=AlwaysDenyHandler(), policy=ExecutionPolicy(gate_destructive=False) + ) assert executor.call("orders.delete_order")["status"] == "executed" executor.set_policy(ExecutionPolicy([PolicyRule("orders.delete_*", requires_approval=True)])) @@ -384,7 +400,8 @@ def test_set_policy_at_runtime(self, registry: Registry) -> None: executor.call("orders.delete_order") executor.set_policy(None) - assert executor.call("orders.delete_order")["status"] == "executed" + with pytest.raises(ApprovalDeniedError): + executor.call("orders.delete_order") def test_policy_gated_request_upholds_annotations_contract(self, registry: Registry) -> None: """ApprovalRequest.annotations must keep the 'requires_approval is guaranteed @@ -518,7 +535,7 @@ def test_no_decision_event_when_gate_skipped_without_handler(self, registry: Reg """Non-strict skip (spec §7.4) emits no decision event — parity with the 'no audit log when gate skipped' contract.""" emitter = CollectingEmitter() - executor = Executor(registry=registry, event_emitter=emitter) + executor = Executor(registry=registry, event_emitter=emitter, policy=ExecutionPolicy(strict=False)) executor.call("admin.reset") assert emitter.of_type("apcore.approval.decision") == [] @@ -629,10 +646,8 @@ def test_real_booleans_still_pass(self, key: str) -> None: @pytest.mark.parametrize("key", ["gate_destructive", "strict"]) def test_absent_and_null_mean_the_documented_default(self, key: str) -> None: - # Parity with apcore-typescript `_requireBoolean`: undefined/null are - # "unset" and take the documented default of False, not an error. - assert getattr(ExecutionPolicy.from_dict({}), key) is False - assert getattr(ExecutionPolicy.from_dict({key: None}), key) is False + assert getattr(ExecutionPolicy.from_dict({}), key) is True + assert getattr(ExecutionPolicy.from_dict({key: None}), key) is True # --------------------------------------------------------------------------- diff --git a/python/tests/test_public_api.py b/python/tests/test_public_api.py index 92f4506c..1cdd6c59 100644 --- a/python/tests/test_public_api.py +++ b/python/tests/test_public_api.py @@ -137,16 +137,12 @@ def test_module_id_errors_importable(self): """A-001: ModuleIdConflictError, InvalidSegmentError, and IdTooLongError are exported by the TS/Rust SDKs and the errors submodule; they must also be importable from the top-level apcore - package and present in apcore.__all__.""" - import apcore + package.""" from apcore import IdTooLongError, InvalidSegmentError, ModuleIdConflictError assert ModuleIdConflictError is not None assert InvalidSegmentError is not None assert IdTooLongError is not None - assert "ModuleIdConflictError" in apcore.__all__ - assert "InvalidSegmentError" in apcore.__all__ - assert "IdTooLongError" in apcore.__all__ def test_call_frequency_exceeded_error_importable(self): from apcore import CallFrequencyExceededError @@ -350,8 +346,11 @@ def test_module_not_found_error_is_not_builtin(self): # -- SpanExporter is now exported -- - def test_span_exporter_in_top_level(self): - assert "SpanExporter" in apcore.__all__ + def test_span_exporter_is_available_from_observability(self): + from apcore.observability import SpanExporter + + assert "SpanExporter" not in apcore.__all__ + assert apcore.SpanExporter is SpanExporter # -- Version -- @@ -383,16 +382,6 @@ def test_pipeline_preset_builders_importable_from_package_root(self): ): assert callable(fn) - def test_pipeline_preset_builders_in_all(self): - for name in ( - "build_standard_strategy", - "build_internal_strategy", - "build_testing_strategy", - "build_performance_strategy", - "build_minimal_strategy", - ): - assert name in apcore.__all__, f"{name} missing from apcore.__all__" - # -- ID conflict detection (D1-004) -- # Regression: detect_id_conflicts, ConflictResult were defined in # apcore.registry.conflicts but not re-exported from the package root. @@ -403,10 +392,6 @@ def test_detect_id_conflicts_importable_from_package_root(self): assert callable(detect_id_conflicts) assert ConflictResult is not None - def test_detect_id_conflicts_in_all(self): - assert "detect_id_conflicts" in apcore.__all__, "detect_id_conflicts missing from apcore.__all__" - assert "ConflictResult" in apcore.__all__, "ConflictResult missing from apcore.__all__" - # -- Registry module-id constants (issue #30) -- # Regression: MAX_MODULE_ID_LENGTH, RESERVED_WORDS, REGISTRY_EVENTS, # EPHEMERAL_NAMESPACE_PREFIX, DEFAULT_MODULE_VERSION and MODULE_ID_PATTERN @@ -428,7 +413,6 @@ def test_registry_constants_importable_from_package_root(self): for name in self._REGISTRY_CONSTANTS: assert hasattr(apcore_mod, name), f"{name} not importable from apcore" - assert name in apcore_mod.__all__, f"{name} missing from apcore.__all__" def test_registry_constants_importable_from_registry_package(self): import apcore.registry as reg @@ -461,355 +445,49 @@ class TestPublicAPIAll: """Verify __all__ is comprehensive and matches actual exports.""" EXPECTED_NAMES = { - # Core - "CancelToken", - "ExecutionCancelledError", - "Context", - "ContextFactory", - "ContextKey", - "GovernanceProjection", - "Identity", - "Registry", - "Executor", + "ACL", + "ACLRule", "APCore", - "DrainAbortedContext", - "DrainContext", - "close", - "call", - "call_async", - "stream", - "validate", - "register", - "describe", - "use", - "use_before", - "use_after", - "remove", - "discover", - "list_modules", - # Lifecycle operations - "LifecycleError", - "LifecycleModuleReport", - "LifecycleOperation", - "LifecycleReport", - "ReloadOptions", - "ShutdownOptions", - "UnregisterOptions", - # Approval + "ApprovalDeniedError", "ApprovalHandler", + "ApprovalPendingError", "ApprovalRequest", "ApprovalResult", - "AlwaysDenyHandler", "AutoApproveHandler", - "CallbackApprovalHandler", - "ScopedApprovalHandler", - # Module types - "Change", - "DEFAULT_ANNOTATIONS", + "CancelToken", + "Context", + "ErrorCodes", + "ExecutionPolicy", + "ExecutionStrategy", + "Executor", + "Identity", + "Middleware", "Module", "ModuleAnnotations", - "ModuleExample", - "ValidationResult", - "PreflightCheckResult", + "ModuleError", + "PipelineEngine", "PreflightResult", "PreviewResult", - # Registry types - "ModuleDescriptor", - "DiscoveredModule", - "DependencyInfo", - # ID conflict detection - "ConflictResult", - "ConflictSeverity", - "ConflictType", - "detect_id_conflicts", - # Registry protocols - "Discoverer", - "ModuleValidator", - # Multi-class discovery - "class_name_to_segment", - "discover_multi_class", - # Registry module-id constants (issue #30 — parity with TS / Rust root) - "DEFAULT_MODULE_VERSION", - "EPHEMERAL_NAMESPACE_PREFIX", - "MAX_MODULE_ID_LENGTH", - "MODULE_ID_PATTERN", - "REGISTRY_EVENTS", - "RESERVED_WORDS", - # Config - "Config", - "RESERVED_NAMESPACES", - "discover_config_file", - # Errors - "ErrorCodes", - "ModuleError", - "ACLDeniedError", - "ACLRuleError", - "ApprovalError", - "ApprovalDeniedError", - "ApprovalTimeoutError", - "ApprovalPendingError", - "BindingCallableNotFoundError", - "BindingFileInvalidError", - "BindingInvalidTargetError", - "BindingModuleNotFoundError", - "BindingNotCallableError", - "BindingSchemaInferenceFailedError", - "BindingSchemaMissingError", - "BindingSchemaModeConflictError", - "BindingStrictSchemaIncompatibleError", - "CallDepthExceededError", - "CallFrequencyExceededError", - "CircuitBreakerOpenError", - "CircuitOpenError", - "CircularCallError", - "CircularDependencyError", - "ConfigError", - "ConfigNotFoundError", - "ContextBindingError", - "DependencyNotFoundError", - "DependencyVersionMismatchError", - "TaskLimitExceededError", - "TaskStoreError", - "VersionConstraintError", - "FuncMissingReturnTypeError", - "FuncMissingTypeHintError", - "IdTooLongError", - "InternalError", - "InvalidInputError", - "InvalidParentIdError", - "InvalidSegmentError", - "ModuleExecuteError", - "ModuleIdConflictError", - "ModuleLoadError", - "ModuleNotFoundError", - "ModuleTimeoutError", - "SchemaCircularRefError", - "SchemaMaxDepthExceededError", - "SchemaNotFoundError", - "SchemaParseError", - "SchemaValidationError", - # ACL - "ACL", - "ACLRule", - "AccessDecision", - "AuditEntry", - "ConditionOutcome", - "RuleValidationFinding", - # Execution-time governance policy (apcore#76 RFC pilot) - "ExecutionPolicy", - "PolicyDecision", - "PolicyRule", - # Middleware - "Middleware", - "RetrySignal", - "MiddlewareManager", - "BeforeMiddleware", - "AfterMiddleware", - "LoggingMiddleware", - "MiddlewareChainError", - "RetryConfig", - "RetryMiddleware", - "CircuitBreakerMiddleware", - "CircuitBreakerState", - # Decorators - "module", - "FunctionModule", - # Extensions - "ExtensionManager", - "ExtensionPoint", - # Async tasks - "AsyncTaskManager", - "TaskStatus", - "TaskInfo", - "TaskStore", - "InMemoryTaskStore", - "AsyncRetryConfig", - "RetryPolicy", - "BackoffStrategy", - # Bindings - "BindingLoader", - # Schema - "SchemaLoader", - "SchemaValidator", + "Registry", + "ReloadOptions", "SchemaExporter", - "RefResolver", - "to_strict_schema", - # Utilities - "match_pattern", - "guard_call_chain", - "normalize_to_canonical_id", - "canonicalize_name", - "CanonicalNameResult", - "CanonicalNameError", - "calculate_specificity", - "propagate_error", - "redact_sensitive", - "REDACTED_VALUE", - # Errors (new) - "ErrorCodeCollisionError", - "ErrorCodeRegistry", - # Version - "VersionIncompatibleError", - "negotiate_version", - # Observability - "TracingMiddleware", - "ContextLogger", - "ObsLoggingMiddleware", - "MetricsMiddleware", - "MetricsCollector", - "Span", - "SpanExporter", - "StdoutExporter", - "InMemoryExporter", - "create_span", - "OTLPExporter", - # Trace Context - "TraceContext", - "TraceParent", - # Events - "EventEmitter", - "EventSubscriber", - "EventRetryConfig", - "ApCoreEvent", - "WebhookSubscriber", - "A2ASubscriber", - "FileSubscriber", - "StdoutSubscriber", - "FilterSubscriber", - "register_subscriber_factory", - "create_subscriber_from_config", - "on", - "off", - # Toggle - "disable", - "enable", - # Schema enums - "SchemaStrategy", - "ExportProfile", - # Additional errors - "ModuleDisabledError", - "ModuleReloadConflictError", - "ReloadFailedError", - "SysModuleRegistrationError", - "SysModulesDisabledError", - "StreamingInterfaceError", - # Streaming Protocol (apcore #62) + "SchemaValidator", + "ScopedApprovalHandler", + "ShutdownOptions", "StreamCompletion", - "StreamCompletionReason", "StreamExecution", "StreamingModule", - "StreamStepOutcome", - # Observability (added in 0.11.0, exported in 0.12.0) - "ErrorEntry", - "ErrorHistory", - "ErrorHistoryMiddleware", - "StorageBackend", - "InMemoryStorageBackend", - "UsageCollector", - "UsageExporter", - "UsageMiddleware", - "NoopUsageExporter", - "PeriodicUsageExporter", - "PlatformNotifyMiddleware", - # System Modules - "register_sys_modules", - # Pipeline - "Step", - "BaseStep", - "StepResult", - "PipelineContext", - "PipelineEngine", - "PipelineTrace", - "StepTrace", - "ExecutionStrategy", - "GovernanceState", - "StrategyInfo", - "PipelineAbortError", - "PipelineState", - "PipelineStepError", - "PipelineStepNotFoundError", - "StepNotFoundError", - "StepNotRemovableError", - "StepNotReplaceableError", - "StepNameDuplicateError", - "StrategyNotFoundError", - "StepMiddleware", - "ConfigurationError", - "PipelineDependencyError", - # Pipeline Configuration (0.17.0) - "register_step_type", - "unregister_step_type", - "registered_step_types", - "build_strategy_from_config", - # Pipeline Preset Builders (parity with apcore-typescript / apcore-rust) - "build_standard_strategy", - "build_internal_strategy", - "build_testing_strategy", - "build_performance_strategy", - "build_minimal_strategy", - # Builtin Pipeline Steps (parity with apcore-typescript / apcore-rust) - "BuiltinContextCreation", - "BuiltinCallChainGuard", - "BuiltinModuleLookup", - "BuiltinACLCheck", - "BuiltinApprovalGate", - "BuiltinMiddlewareBefore", - "BuiltinInputValidation", - "BuiltinExecute", - "BuiltinOutputValidation", - "BuiltinMiddlewareAfter", - "BuiltinReturnResult", - # Config Bus (0.15.0) - "ConfigBindError", - "ConfigEnvMapConflictError", - "ConfigEnvPrefixConflictError", - "ConfigMountError", - "ConfigNamespaceDuplicateError", - "ConfigNamespaceReservedError", - # Error Formatter (0.15.0) - "ErrorFormatter", - "ErrorFormatterRegistry", - "ErrorFormatterDuplicateError", - # Built-in context keys - "TRACING_SPANS", - "TRACING_SAMPLED", - "METRICS_STARTS", - "LOGGING_START", - "REDACTED_OUTPUT", - "RETRY_COUNT_BASE", - # System module classes - "HealthSummaryModule", - "HealthModule", - "ManifestFullModule", - "ManifestModule", - "UsageSummaryModule", - "UsageModule", - "UpdateConfigModule", - "ReloadModule", - "ToggleFeatureModule", - "ToggleState", - # Overrides Store (cross-language alignment with TS / Rust) - "OverridesStore", - "InMemoryOverridesStore", - "FileOverridesStore", - # System Modules context type - "SysModulesContext", - # System module registration - "register_sys_modules", - # Module-level constants (parity with apcore-typescript / apcore-rust) - "DEFAULT_MAX_CALL_DEPTH", - "DEFAULT_MAX_MODULE_REPEAT", - "FRAMEWORK_ERROR_CODE_PREFIXES", - "METRIC_CALLS_TOTAL", - "METRIC_DURATION_SECONDS", - # Health utility - "classify_health_status", - # Context-data namespace validation (middleware-system.md 1.1) — peer of - # apcore-typescript validateContextKey / apcore-rust validate_context_key - "validate_context_key", - "NamespaceCheck", - "APCORE_KEY_PREFIX", - "EXT_KEY_PREFIX", + "TraceContext", + "UnregisterOptions", + "call", + "call_async", + "close", + "module", + "redact_sensitive", + "register", + "stream", + "to_strict_schema", + "validate", } def test_all_contains_all_expected_names(self): @@ -844,8 +522,8 @@ def test_default_client_is_lazy_and_close_resets(self): # After close(), a new instance is created on next access — not the same object. assert first is not second - def test_deprecated_subscriber_apis_not_advertised(self): - """Deprecated subscriber registry APIs must not appear in __all__ but remain importable.""" + def test_legacy_global_subscriber_apis_removed(self): + """Subscriber registration belongs to the host registry.""" deprecated = ( "register_subscriber_type", "unregister_subscriber_type", @@ -853,5 +531,4 @@ def test_deprecated_subscriber_apis_not_advertised(self): ) for name in deprecated: assert name not in apcore.__all__, f"Deprecated {name} should not be advertised in __all__" - # Back-compat: still importable via attribute access. - assert hasattr(apcore, name), f"Deprecated {name} must remain importable" + assert not hasattr(apcore, name) diff --git a/python/uv.lock b/python/uv.lock index 7c593ebb..79df6e80 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -199,45 +199,68 @@ wheels = [ [[package]] name = "apcore" -version = "1.0.0a1" +version = "1.0.0a2" source = { editable = "." } dependencies = [ { name = "jsonschema" }, { name = "pydantic" }, - { name = "pyyaml" }, { name = "referencing" }, ] [package.optional-dependencies] +all = [ + { name = "aiohttp" }, + { name = "opentelemetry-exporter-otlp-proto-http" }, + { name = "opentelemetry-sdk" }, + { name = "pyyaml" }, + { name = "watchdog" }, +] +config = [ + { name = "pyyaml" }, +] dev = [ { name = "apdev", extra = ["dev"] }, { name = "mypy" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-cov" }, + { name = "pyyaml" }, { name = "ruff" }, { name = "watchdog" }, ] +discovery = [ + { name = "pyyaml" }, + { name = "watchdog" }, +] events = [ { name = "aiohttp" }, ] +observability = [ + { name = "opentelemetry-exporter-otlp-proto-http" }, + { name = "opentelemetry-sdk" }, +] [package.metadata] requires-dist = [ { name = "aiohttp", marker = "extra == 'events'", specifier = ">=3.9" }, + { name = "apcore", extras = ["config", "discovery"], marker = "extra == 'dev'" }, + { name = "apcore", extras = ["config", "discovery", "events", "observability"], marker = "extra == 'all'" }, { name = "apdev", extras = ["dev"], marker = "extra == 'dev'", specifier = ">=0.2.3" }, { name = "jsonschema", specifier = ">=4.21,<5" }, { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.0" }, + { name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'observability'", specifier = ">=1.34,<2" }, + { name = "opentelemetry-sdk", marker = "extra == 'observability'", specifier = ">=1.34,<2" }, { name = "pydantic", specifier = ">=2.7,<3" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.23" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0" }, - { name = "pyyaml", specifier = ">=6.0,<7" }, + { name = "pyyaml", marker = "extra == 'config'", specifier = ">=6.0,<7" }, + { name = "pyyaml", marker = "extra == 'discovery'", specifier = ">=6.0,<7" }, { name = "referencing", specifier = ">=0.30,<1" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.15.0,<0.17" }, - { name = "watchdog", marker = "extra == 'dev'", specifier = ">=3.0" }, + { name = "watchdog", marker = "extra == 'discovery'", specifier = ">=3.0" }, ] -provides-extras = ["events", "dev"] +provides-extras = ["config", "discovery", "events", "observability", "all", "dev"] [[package]] name = "apdev" @@ -345,6 +368,162 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ad/9b/9fb3585dabcd73a1b2a6267f63f62649347c9e6d072c9fde365b105abb2c/build-1.6.1-py3-none-any.whl", hash = "sha256:ecd351a4be9d35a9eaaba244a7687143c9c7d4aea6ac964e7e7ddab20cbcf4e7", size = 31179, upload-time = "2026-09-10T07:55:59.148Z" }, ] +[[package]] +name = "certifi" +version = "2026.11.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/51/33/4cd27639502f010084bcef7a2036391dd637439901341ce1a530f36f6e51/certifi-2026.11.20.tar.gz", hash = "sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e", size = 128901, upload-time = "2026-11-20T23:37:49.522Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/39/5eec3296860b94ac20bb8ed807725b88f6adfab3f343df592afd975f5f86/certifi-2026.11.20-py3-none-any.whl", hash = "sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f", size = 127913, upload-time = "2026-11-20T23:37:48.117Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/67/6a0b94a7960d5e1b5eacd2fb529f3fccc47db4644f7f0a7cfdcfc3be578a/charset_normalizer-3.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6", size = 370642, upload-time = "2026-09-30T04:35:06.91Z" }, + { url = "https://files.pythonhosted.org/packages/fb/94/01009e13b94041599004edf32e56e382c24e570f60f79bab8efe45cfe1eb/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5", size = 259280, upload-time = "2026-09-30T04:35:08.448Z" }, + { url = "https://files.pythonhosted.org/packages/66/85/3b5358f60a13210f0b67d3755c168ef758701b021e655d88d4da28554467/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74", size = 245335, upload-time = "2026-09-30T04:35:10.104Z" }, + { url = "https://files.pythonhosted.org/packages/74/75/77c1c479b09ecd751d1e767b251ea5c14d4d50ff757bf404afab2692f600/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab", size = 291707, upload-time = "2026-09-30T04:35:11.575Z" }, + { url = "https://files.pythonhosted.org/packages/0b/0d/363f78cacb70f58f15f4b083961bbd9d292f335d3f5c66fc4f1cfe69cb90/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c", size = 286747, upload-time = "2026-09-30T04:35:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/e4/ed/cf505d3011ffceb12c2067a7a5d3cfe92b875d4d44bb0ff0d69375e2c184/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f", size = 269972, upload-time = "2026-09-30T04:35:14.606Z" }, + { url = "https://files.pythonhosted.org/packages/15/d8/f0a93a431d170e7ca681d4f6650fee3de934d18560e474e7267eb4b0f987/charset_normalizer-3.5.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288", size = 269339, upload-time = "2026-09-30T04:35:16.087Z" }, + { url = "https://files.pythonhosted.org/packages/86/bd/9b2bd1c5b7af02462c9752d33994834ff972a96b4c483eefde9e594488e2/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400", size = 261683, upload-time = "2026-09-30T04:35:17.488Z" }, + { url = "https://files.pythonhosted.org/packages/76/a5/cac540ab0fd61f3fec88ad3dbb64509e71424593d73cfdfff5ab3e4db279/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd", size = 248143, upload-time = "2026-09-30T04:35:18.849Z" }, + { url = "https://files.pythonhosted.org/packages/71/7a/ff467301deef2089fad87f72df9e000a26a78fec7acbb18e1999371b8369/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37", size = 292358, upload-time = "2026-09-30T04:35:20.326Z" }, + { url = "https://files.pythonhosted.org/packages/ad/77/22d7e785d1e210afc2e2f58600dd1799d17a35665faf84383f002826c5f8/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac", size = 268766, upload-time = "2026-09-30T04:35:21.72Z" }, + { url = "https://files.pythonhosted.org/packages/ae/91/e8e946267f1c2d9e2bd651726e2fbd2addf02c4d36cea5069e32ca9d7bb5/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a", size = 287432, upload-time = "2026-09-30T04:35:23.273Z" }, + { url = "https://files.pythonhosted.org/packages/4e/88/7561d8a88d555e7df6623abe7c0070b4baf47549b9408783a2ae0a1a6cf7/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640", size = 272470, upload-time = "2026-09-30T04:35:24.655Z" }, + { url = "https://files.pythonhosted.org/packages/35/7e/578c702301ec036f01455f30744a08d2b42f6ab35b9b2d4bf8cae0ef2a80/charset_normalizer-3.5.2-cp311-cp311-win32.whl", hash = "sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d", size = 186688, upload-time = "2026-09-30T04:35:26.225Z" }, + { url = "https://files.pythonhosted.org/packages/e8/fc/fdf8cf52ff21cd5bf158f20978991cf985325842f74283eb6df26c8a39d8/charset_normalizer-3.5.2-cp311-cp311-win_amd64.whl", hash = "sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96", size = 214932, upload-time = "2026-09-30T04:35:27.796Z" }, + { url = "https://files.pythonhosted.org/packages/97/66/3e45a506d8110b632541faf9a9470185aa9878f1ed44020f31346c1c5e5b/charset_normalizer-3.5.2-cp311-cp311-win_arm64.whl", hash = "sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1", size = 202828, upload-time = "2026-09-30T04:35:29.259Z" }, + { url = "https://files.pythonhosted.org/packages/e7/c8/693809898870237d82785a03f3b2b58fe4c9f14669f84a7d4e623c92a59e/charset_normalizer-3.5.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491", size = 367780, upload-time = "2026-09-30T04:35:30.888Z" }, + { url = "https://files.pythonhosted.org/packages/c9/87/2fea8c13dc24b3ca9c6f803a5b2dfdeae73eb4f9e12c7885ed908ff0433c/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c", size = 246730, upload-time = "2026-09-30T04:35:32.286Z" }, + { url = "https://files.pythonhosted.org/packages/a8/9e/09efac30b937722f46d3110ba30b875b24b2e3a266ed746cc4e376a94d80/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0", size = 237707, upload-time = "2026-09-30T04:35:33.709Z" }, + { url = "https://files.pythonhosted.org/packages/9e/18/70d76670b13686237863a379928d60bd10e021f17d243ab3d7014c4a5f4e/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51", size = 273050, upload-time = "2026-09-30T04:35:35.138Z" }, + { url = "https://files.pythonhosted.org/packages/54/e2/77a8b09d5adc013ed07b95b01b8b8fa5441c4e810e83ee7e4aae2fa4d91a/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5", size = 270345, upload-time = "2026-09-30T04:35:36.502Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c5/38806a25ab5e65fc178f39affeda20858efafede2fce1ffc2556cfc9fe73/charset_normalizer-3.5.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649", size = 257601, upload-time = "2026-09-30T04:35:37.919Z" }, + { url = "https://files.pythonhosted.org/packages/ae/8d/213565184708fdb263ae55e2c04ee1ff748129dd65d48ed0e3502da9c85a/charset_normalizer-3.5.2-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e", size = 252222, upload-time = "2026-09-30T04:35:39.544Z" }, + { url = "https://files.pythonhosted.org/packages/7e/24/76d2cefc25472531e4c5c7dfff68865eb1c39b78482f0fdc15b46f047830/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346", size = 248482, upload-time = "2026-09-30T04:35:41.088Z" }, + { url = "https://files.pythonhosted.org/packages/7d/dc/65a801b66ab4c197e22c433ab25e7ac24324ac6f45a2269aca42cce309bf/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1", size = 241206, upload-time = "2026-09-30T04:35:42.59Z" }, + { url = "https://files.pythonhosted.org/packages/a7/95/ca9b5eabde673002c6f1e7ada1b223916fe18f6d661da7aabd4d643718f1/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875", size = 273190, upload-time = "2026-09-30T04:35:44.347Z" }, + { url = "https://files.pythonhosted.org/packages/2d/8b/803b4d2a3f6e1740f63f1e87b04d14b42f3d4fdfe6ed7d4db2d34102b14f/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1", size = 253527, upload-time = "2026-09-30T04:35:45.915Z" }, + { url = "https://files.pythonhosted.org/packages/a9/55/93c0e5dbd085ae0471346026abbe7e0db9ea2d6fea74e51f0b5a46f233a7/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413", size = 271285, upload-time = "2026-09-30T04:35:47.49Z" }, + { url = "https://files.pythonhosted.org/packages/95/69/0dbd0e0b9b16cfa816cdfcb3e2e3854a1f680dc07fb1245ea125e7448060/charset_normalizer-3.5.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869", size = 260010, upload-time = "2026-09-30T04:35:48.996Z" }, + { url = "https://files.pythonhosted.org/packages/58/9d/e7b88e7b1bf403590c3b573277b5e1e488c68c7a6fbacca310a2c324e90c/charset_normalizer-3.5.2-cp312-cp312-win32.whl", hash = "sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e", size = 184125, upload-time = "2026-09-30T04:35:50.777Z" }, + { url = "https://files.pythonhosted.org/packages/eb/e6/e6e083884cbcfd49c64865af05027fe7011be7b2d9179524f099a1b611f3/charset_normalizer-3.5.2-cp312-cp312-win_amd64.whl", hash = "sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc", size = 207486, upload-time = "2026-09-30T04:35:52.194Z" }, + { url = "https://files.pythonhosted.org/packages/c4/e3/017aea0911ada7405a825c7d937eb3a13009664e2f5b38e8c4bbf2abf894/charset_normalizer-3.5.2-cp312-cp312-win_arm64.whl", hash = "sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3", size = 196734, upload-time = "2026-09-30T04:35:53.636Z" }, + { url = "https://files.pythonhosted.org/packages/c5/34/68292d68512768591aaff07c59bb53ee31341c87759433a859c4641a50c2/charset_normalizer-3.5.2-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5", size = 225946, upload-time = "2026-09-30T04:35:55.313Z" }, + { url = "https://files.pythonhosted.org/packages/e3/80/bee0b01b90ccd5322ae1d0abb33fab1bd95b7c2eadaf02aeccf22e04ee83/charset_normalizer-3.5.2-cp313-cp313-android_24_x86_64.whl", hash = "sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e", size = 238619, upload-time = "2026-09-30T04:35:56.863Z" }, + { url = "https://files.pythonhosted.org/packages/78/6e/60ce52a85a7fd631ae8482ae6d74521014ca2f255892679484dc04d7ef56/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a", size = 206701, upload-time = "2026-09-30T04:35:58.639Z" }, + { url = "https://files.pythonhosted.org/packages/36/8c/71aafad23f971afc84c2b295bc0c560739ce1dac558aad9fec22e39f3639/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d", size = 210506, upload-time = "2026-09-30T04:36:00.147Z" }, + { url = "https://files.pythonhosted.org/packages/91/da/3c5a7798c046df7d2d68ad653cf5b6c5a8bfee225055a843c6f2f42aac1a/charset_normalizer-3.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055", size = 366626, upload-time = "2026-09-30T04:36:01.77Z" }, + { url = "https://files.pythonhosted.org/packages/e1/16/710ac3de2ee354e2bd1a9c94efe45a2d27b5c6ad39b2d6a905be2c094b6c/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858", size = 244624, upload-time = "2026-09-30T04:36:03.389Z" }, + { url = "https://files.pythonhosted.org/packages/d6/39/45c7439f5b63d24f7d5b2a1d760f34af7628782d7144b4cc8ded45c2d4bc/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234", size = 235731, upload-time = "2026-09-30T04:36:04.987Z" }, + { url = "https://files.pythonhosted.org/packages/4d/34/38f3154785ce92e9f56eb226f4d35bdfae6b008480dd055f58837a89c810/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21", size = 270352, upload-time = "2026-09-30T04:36:06.412Z" }, + { url = "https://files.pythonhosted.org/packages/04/f3/859f74e7babc977705026b30593b3be04049632a522fb7000f83c033d747/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718", size = 267393, upload-time = "2026-09-30T04:36:07.865Z" }, + { url = "https://files.pythonhosted.org/packages/4b/85/41d27f234b82e47c167a5f6c0f62501dc0c640585ff4aba79e08a390336a/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4", size = 254660, upload-time = "2026-09-30T04:36:09.248Z" }, + { url = "https://files.pythonhosted.org/packages/58/ca/5d1a997587febe5b26d8daffe363b5c1a091cece19828eec6502fd09c5ef/charset_normalizer-3.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3", size = 249996, upload-time = "2026-09-30T04:36:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/b3/1f/d1e78246f7ed60c8c8d606b4ac27f66ce49cc3e95f24893ccbeba9f77302/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c", size = 247028, upload-time = "2026-09-30T04:36:12.294Z" }, + { url = "https://files.pythonhosted.org/packages/8e/37/eba316edd4f0c4d3a5d945924c4eeeae59abac4056aa815d8a4268f863a2/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429", size = 240562, upload-time = "2026-09-30T04:36:13.887Z" }, + { url = "https://files.pythonhosted.org/packages/c8/8e/aaa037d40ca9ef045977f1a661048b1aa33f223adfce3452fe9be9f79d14/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f", size = 271699, upload-time = "2026-09-30T04:36:15.41Z" }, + { url = "https://files.pythonhosted.org/packages/26/19/1c1c9f75974adf523b87f34b8a2adc5a435cd65916812bcbd0dfa45f9a29/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a", size = 252030, upload-time = "2026-09-30T04:36:16.839Z" }, + { url = "https://files.pythonhosted.org/packages/bc/90/0660ef18e18df0a4d2a1a0edff7dfbba42d4e50ef2425557a5bb7051f77b/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00", size = 268565, upload-time = "2026-09-30T04:36:18.468Z" }, + { url = "https://files.pythonhosted.org/packages/79/ba/57adc269824e8658f1a0f97a9e514c247445a9632b3419b97e0ba37f16dc/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d", size = 257627, upload-time = "2026-09-30T04:36:19.938Z" }, + { url = "https://files.pythonhosted.org/packages/9a/85/33abd4315c052d3d4f54c92b1ee49bfbc0dc7115a981e462a793b6d2ab87/charset_normalizer-3.5.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3", size = 143407, upload-time = "2026-09-30T04:36:21.376Z" }, + { url = "https://files.pythonhosted.org/packages/4f/de/6435e18d1aaa5d910b896d551411c96af1f42a0c56c29afc2016c61ccc2e/charset_normalizer-3.5.2-cp313-cp313-win32.whl", hash = "sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd", size = 183207, upload-time = "2026-09-30T04:36:22.776Z" }, + { url = "https://files.pythonhosted.org/packages/9c/76/b8ec57f4e9ee3253541abf95e4a462c0175fe8032dcd070f1f2421240942/charset_normalizer-3.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639", size = 206489, upload-time = "2026-09-30T04:36:24.306Z" }, + { url = "https://files.pythonhosted.org/packages/3e/60/c647c6ae47480221e875ea5d743ff94946f7416e3c69415ab772928e8d32/charset_normalizer-3.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3", size = 195501, upload-time = "2026-09-30T04:36:25.846Z" }, + { url = "https://files.pythonhosted.org/packages/58/ca/7aa91362a2f77ac8e9e28a9b902a74f7d0e11a851ef0d27a74308da8cd90/charset_normalizer-3.5.2-cp314-cp314-android_24_arm64_v8a.whl", hash = "sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187", size = 226010, upload-time = "2026-09-30T04:36:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/a8/cf/ac8878d0322cf88a1aad4c7b147db32ca0bd806eb0060957b2e31486dbe6/charset_normalizer-3.5.2-cp314-cp314-android_24_x86_64.whl", hash = "sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad", size = 239266, upload-time = "2026-09-30T04:36:29.434Z" }, + { url = "https://files.pythonhosted.org/packages/c9/6d/9a08d7e0b29b7208e2c6c01dc56c8e0520e7c7beadbbfb024b58fd69c8a5/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf", size = 206783, upload-time = "2026-09-30T04:36:30.872Z" }, + { url = "https://files.pythonhosted.org/packages/82/44/b0aa350280e6ff5a5492d17cf10460dd39d5ee848f872f7ba2df10607f60/charset_normalizer-3.5.2-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995", size = 210449, upload-time = "2026-09-30T04:36:32.625Z" }, + { url = "https://files.pythonhosted.org/packages/7c/8a/40db9aa9f5907bb0e6f8b6d64064bf8852fb33d4b813ff9414911df7647c/charset_normalizer-3.5.2-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424", size = 367815, upload-time = "2026-09-30T04:36:34.197Z" }, + { url = "https://files.pythonhosted.org/packages/7f/72/9c5e7707b57c8ddfa9ddf7b0b1d009d7fbab9e9e887d5b721060f37e307d/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13", size = 247095, upload-time = "2026-09-30T04:36:35.803Z" }, + { url = "https://files.pythonhosted.org/packages/83/09/71e453691e927de4ddf792770cfaab3f49d494e222f66ea5e404bbd5e39c/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d", size = 233942, upload-time = "2026-09-30T04:36:37.407Z" }, + { url = "https://files.pythonhosted.org/packages/9f/86/85c84e4da8b27dd409577d9437926ff581c5f9d3c66038dc68c1a526de51/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4", size = 273762, upload-time = "2026-09-30T04:36:38.904Z" }, + { url = "https://files.pythonhosted.org/packages/92/08/564955a4b5f2ccb410ab480bbe8c6a18063ff27f2d35458731c4a5335df9/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438", size = 269514, upload-time = "2026-09-30T04:36:40.469Z" }, + { url = "https://files.pythonhosted.org/packages/18/24/bad3ac4271589df29cf5ce2f5ae490518a5739358052bd0d61209e6fea54/charset_normalizer-3.5.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a", size = 255056, upload-time = "2026-09-30T04:36:42.02Z" }, + { url = "https://files.pythonhosted.org/packages/d6/3e/350d89ad49916b86554d6f5f2d03ec1152148f87e5ff735106c6a03b1a36/charset_normalizer-3.5.2-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56", size = 251311, upload-time = "2026-09-30T04:36:43.577Z" }, + { url = "https://files.pythonhosted.org/packages/56/5b/4970a2d154df502e133402906dd04e3ae7cada7b3011283c88d0479a2585/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd", size = 250190, upload-time = "2026-09-30T04:36:45.185Z" }, + { url = "https://files.pythonhosted.org/packages/88/8c/f1a91bddc8fb47c2889e29ea7ea49a194eb0d9868675d786806519c00d76/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204", size = 237098, upload-time = "2026-09-30T04:36:46.689Z" }, + { url = "https://files.pythonhosted.org/packages/24/0e/bb5dace3cc7e79068425386a6589c19b5a2ab5fefc2a46abea6919683332/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7", size = 274228, upload-time = "2026-09-30T04:36:48.31Z" }, + { url = "https://files.pythonhosted.org/packages/9d/79/b849ad523017ea9f5a45581bbebed91439e0cf42fd2860a6f64e358eb5a6/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd", size = 252401, upload-time = "2026-09-30T04:36:50.091Z" }, + { url = "https://files.pythonhosted.org/packages/89/8c/75469d690cf47200bce8f6cad7655724fc23148e147abfc5ce78b5f65863/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc", size = 271846, upload-time = "2026-09-30T04:36:51.719Z" }, + { url = "https://files.pythonhosted.org/packages/26/cd/6d52d3c7437cdcf2e310ce9f28f282e733d4ef60ed19105d1819c356255f/charset_normalizer-3.5.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874", size = 258151, upload-time = "2026-09-30T04:36:53.234Z" }, + { url = "https://files.pythonhosted.org/packages/f7/4c/070b38bdb5f49a70199fce923ec0726a49536a63ab262abbfcaaf351110b/charset_normalizer-3.5.2-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655", size = 143570, upload-time = "2026-09-30T04:36:54.816Z" }, + { url = "https://files.pythonhosted.org/packages/81/84/9ebfc8ed6c8c4fcd8e726ff6bf220cc8deb3966e31dce9be8dd8aa017e64/charset_normalizer-3.5.2-cp314-cp314-win32.whl", hash = "sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0", size = 186412, upload-time = "2026-09-30T04:36:56.643Z" }, + { url = "https://files.pythonhosted.org/packages/d1/78/5ed86f743d4bc350db307e7636419a0a5ee1d91806d30c7f667bd5c80dae/charset_normalizer-3.5.2-cp314-cp314-win_amd64.whl", hash = "sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c", size = 210965, upload-time = "2026-09-30T04:36:58.205Z" }, + { url = "https://files.pythonhosted.org/packages/53/94/a3a7698e9b1a395e1eb99ccd9a324be9347973bff4e72db2a06496d7cd27/charset_normalizer-3.5.2-cp314-cp314-win_arm64.whl", hash = "sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253", size = 200406, upload-time = "2026-09-30T04:36:59.764Z" }, + { url = "https://files.pythonhosted.org/packages/c1/48/c5dd00d5ef7791f02666de250a5bb6071e29b7e133cf4b835800b6d3bc27/charset_normalizer-3.5.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709", size = 396871, upload-time = "2026-09-30T04:37:01.543Z" }, + { url = "https://files.pythonhosted.org/packages/12/c8/8379554b42e8368161d898476686947a0fdbd3e8865170d7909dcabfdee8/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084", size = 249711, upload-time = "2026-09-30T04:37:03.111Z" }, + { url = "https://files.pythonhosted.org/packages/4a/eb/2ddb1035d17320caa9f41682935123a9a250277b261c3efc86b2d2a21343/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb", size = 231146, upload-time = "2026-09-30T04:37:04.721Z" }, + { url = "https://files.pythonhosted.org/packages/4a/24/2ecb4bde104322cd7859d6594fcfa74649f8d90b3221c9feecbef149875b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f", size = 271552, upload-time = "2026-09-30T04:37:06.295Z" }, + { url = "https://files.pythonhosted.org/packages/3f/98/9d5f6ebc3aee9fef5d30b4aff11fb2ab7a1222b4064f8ef2c7c87cde217a/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09", size = 269810, upload-time = "2026-09-30T04:37:07.905Z" }, + { url = "https://files.pythonhosted.org/packages/09/e1/a3b06a10461b1b7628853c934c644e03bc28e42767116afb52f19a56519b/charset_normalizer-3.5.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80", size = 259845, upload-time = "2026-09-30T04:37:09.554Z" }, + { url = "https://files.pythonhosted.org/packages/fd/d3/6f561f74a296cf27d61775a1dc665ad13f3bff6a798810ca05907f37a7c4/charset_normalizer-3.5.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c", size = 252825, upload-time = "2026-09-30T04:37:11.274Z" }, + { url = "https://files.pythonhosted.org/packages/26/9f/69e13ca3b18f43e0eafcd34c04a45b732ae22a43b54a5fc9e119103356eb/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f", size = 252659, upload-time = "2026-09-30T04:37:12.941Z" }, + { url = "https://files.pythonhosted.org/packages/73/a9/ace29806a0dae18939919c76ba526472d83214afa101105fabff2cf30625/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03", size = 238819, upload-time = "2026-09-30T04:37:14.659Z" }, + { url = "https://files.pythonhosted.org/packages/f8/c1/6116d52a2e3311ec80f21f5fb5e17b27405f10b9608af8f6e69516841a1b/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604", size = 272973, upload-time = "2026-09-30T04:37:16.346Z" }, + { url = "https://files.pythonhosted.org/packages/19/aa/9955c7e93bba10a9c7e8f7a5031b7ced66f3a1883a55c00712b8d5850ff3/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8", size = 253692, upload-time = "2026-09-30T04:37:18.212Z" }, + { url = "https://files.pythonhosted.org/packages/bb/33/2a6ae7fdc1b10cb581cef91addd8cdfc5f40d50abb5702309369d5834579/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93", size = 268757, upload-time = "2026-09-30T04:37:19.877Z" }, + { url = "https://files.pythonhosted.org/packages/a2/22/80992720a0282cd39bba1db35868e6b9c22f41281160143a836544bc1d8a/charset_normalizer-3.5.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915", size = 262220, upload-time = "2026-09-30T04:37:21.583Z" }, + { url = "https://files.pythonhosted.org/packages/92/9f/181fd07e1bffea1d95cd80c84ac537354f50699c22cfc4d3c02b6fc16208/charset_normalizer-3.5.2-cp314-cp314t-win32.whl", hash = "sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5", size = 197797, upload-time = "2026-09-30T04:37:23.235Z" }, + { url = "https://files.pythonhosted.org/packages/49/1c/25d8415ec1c4f2f41f1680435e4c87cfb378ff2f677d950946f2a45d0632/charset_normalizer-3.5.2-cp314-cp314t-win_amd64.whl", hash = "sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc", size = 222765, upload-time = "2026-09-30T04:37:24.891Z" }, + { url = "https://files.pythonhosted.org/packages/3e/b4/46b48f013dadfc0d0d33b375438e31bdf5a989dc68389c6bf627054d4df9/charset_normalizer-3.5.2-cp314-cp314t-win_arm64.whl", hash = "sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105", size = 210985, upload-time = "2026-09-30T04:37:26.634Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e9/34e597dee616d0b8ee4b34d29399e85c2204ade174157a48505d42baa4ff/charset_normalizer-3.5.2-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26", size = 367676, upload-time = "2026-09-30T04:37:28.329Z" }, + { url = "https://files.pythonhosted.org/packages/60/9f/a5d1c91c0263745e2cd344c5a4415d787c575501ab1d449f1148ac6b495d/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364", size = 248414, upload-time = "2026-09-30T04:37:30.167Z" }, + { url = "https://files.pythonhosted.org/packages/26/79/e697f77464748a3ee3cf490c83d592459400d4898380d66c38366b03080c/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253", size = 244775, upload-time = "2026-09-30T04:37:31.964Z" }, + { url = "https://files.pythonhosted.org/packages/ca/87/3d42a42e18ea066e2513936fd678a00696e77878b5ae04528976abdbcb83/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0", size = 273877, upload-time = "2026-09-30T04:37:33.661Z" }, + { url = "https://files.pythonhosted.org/packages/c3/76/8a28136f3938ba9836f84280ce0c4d61ed1cf15a036b2034900c62634162/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc", size = 269455, upload-time = "2026-09-30T04:37:35.573Z" }, + { url = "https://files.pythonhosted.org/packages/a0/a1/4fbf5d0f0f1b2a080474c1cf9a2f12c4c6531bb0e8ba591055e846d2b4e9/charset_normalizer-3.5.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229", size = 257336, upload-time = "2026-09-30T04:37:37.397Z" }, + { url = "https://files.pythonhosted.org/packages/ba/a2/8b50aa320adb880ad579518e6f718f24944804b42a88b83d267d5d444125/charset_normalizer-3.5.2-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5", size = 257584, upload-time = "2026-09-30T04:37:39.522Z" }, + { url = "https://files.pythonhosted.org/packages/a5/57/50e3fed84e175f40349bd0da7a4fce94c87f0378f52d74f511d89e0bdc20/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98", size = 251854, upload-time = "2026-09-30T04:37:41.23Z" }, + { url = "https://files.pythonhosted.org/packages/d6/54/f7fbb3493c9f49091213b9c2d6dd65800696f1ce1a3f196a4205f50417b1/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3", size = 248767, upload-time = "2026-09-30T04:37:42.883Z" }, + { url = "https://files.pythonhosted.org/packages/d9/37/b3a6385acc5a1e45b39ae9c90bfb9cf838a09b9dd37ef2740ab4c6b4a2eb/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2", size = 274479, upload-time = "2026-09-30T04:37:44.658Z" }, + { url = "https://files.pythonhosted.org/packages/89/44/809913e2cfd279e635a9294fdbbfb1b1dc62a8189d473d561f649fce98d8/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf", size = 258310, upload-time = "2026-09-30T04:37:46.529Z" }, + { url = "https://files.pythonhosted.org/packages/af/a2/f28400ab13359d91bd39179df8e149376b9bf36588e739a3a4f9de2b84b2/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95", size = 271100, upload-time = "2026-09-30T04:37:48.399Z" }, + { url = "https://files.pythonhosted.org/packages/e9/89/9bab37955edf0adb3b66f8a3a6617d9f2f487e0d56f295a6a286cb640aa6/charset_normalizer-3.5.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d", size = 259936, upload-time = "2026-09-30T04:37:50.023Z" }, + { url = "https://files.pythonhosted.org/packages/23/b5/4459e08d45a679f903d50fea08bc52cfa728cca4d7bd02c757b5e5abda2e/charset_normalizer-3.5.2-cp315-cp315-win32.whl", hash = "sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847", size = 186301, upload-time = "2026-09-30T04:37:51.722Z" }, + { url = "https://files.pythonhosted.org/packages/98/e8/55d5fd3935b4bce6da4fe0df61898e8c82653e317e677bd58aceb9c60f13/charset_normalizer-3.5.2-cp315-cp315-win_amd64.whl", hash = "sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8", size = 210858, upload-time = "2026-09-30T04:37:53.427Z" }, + { url = "https://files.pythonhosted.org/packages/a9/5b/974423c2fd8e524c7a7f64318c1e02240ef954912fa2b4d70344107b9c68/charset_normalizer-3.5.2-cp315-cp315-win_arm64.whl", hash = "sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a", size = 200309, upload-time = "2026-09-30T04:37:55.015Z" }, + { url = "https://files.pythonhosted.org/packages/ee/f9/00ee0195db1013d8f7c416fd770fbeb560bb46eb2e36b054d05cb56f6cfa/charset_normalizer-3.5.2-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1", size = 395343, upload-time = "2026-09-30T04:37:56.743Z" }, + { url = "https://files.pythonhosted.org/packages/04/3a/c00b50e94c964cf934c7899cd47c97952fc11dad71cc5884b3c61795b09b/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b", size = 250114, upload-time = "2026-09-30T04:37:58.607Z" }, + { url = "https://files.pythonhosted.org/packages/50/27/d102dc880bbcffd0479ab64dfc1fb96777a854355a55e2bda72a71efadcb/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f", size = 239997, upload-time = "2026-09-30T04:38:00.511Z" }, + { url = "https://files.pythonhosted.org/packages/a5/4a/bf7ef45794dd293fab5f98a9309817977fbb845b9998f171b8cc5d8437a3/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3", size = 272313, upload-time = "2026-09-30T04:38:02.509Z" }, + { url = "https://files.pythonhosted.org/packages/e8/ee/008a2837737991474c5754bb3191010007663860979701990982a502cbaf/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e", size = 269986, upload-time = "2026-09-30T04:38:04.435Z" }, + { url = "https://files.pythonhosted.org/packages/93/ad/bd74a283940dc910c5b14f8e4f80a248082bc9c0fcbe1f54530cb6d9cc5e/charset_normalizer-3.5.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9", size = 260202, upload-time = "2026-09-30T04:38:06.549Z" }, + { url = "https://files.pythonhosted.org/packages/8a/7b/ed341c66f69f688723501fac752be3d63c7159ca0d0d4174fc611e5710bb/charset_normalizer-3.5.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a", size = 259083, upload-time = "2026-09-30T04:38:08.311Z" }, + { url = "https://files.pythonhosted.org/packages/cc/9d/e41588b777965e5031a43128a1e96173ebb35ac75fc53ec3b517e7c21cd4/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115", size = 253081, upload-time = "2026-09-30T04:38:10.402Z" }, + { url = "https://files.pythonhosted.org/packages/81/35/b761eb6d8c1eb218b9b42b9b4d5ac902afdc399fb6dac6f9a9aac7bda589/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c", size = 248712, upload-time = "2026-09-30T04:38:12.317Z" }, + { url = "https://files.pythonhosted.org/packages/4d/2c/147169a041b747759f37405c0a97157e8e92de967968373101ff14915cba/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d", size = 274176, upload-time = "2026-09-30T04:38:14.138Z" }, + { url = "https://files.pythonhosted.org/packages/f0/2d/0ff8db0d373ba8538db686db11cd7e8912031490b9e4f383b41912e8d594/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d", size = 259413, upload-time = "2026-09-30T04:38:15.841Z" }, + { url = "https://files.pythonhosted.org/packages/8a/8e/b4a085fb47c9d3a7e43576a4784fdd8fe23f907514a972de8086edaf7a48/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4", size = 269434, upload-time = "2026-09-30T04:38:17.626Z" }, + { url = "https://files.pythonhosted.org/packages/83/1c/d8d8d7322a7c3eecdf3237a4a419cf41d2eaad8e006ce7dfdd9d4c8fa2eb/charset_normalizer-3.5.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b", size = 262716, upload-time = "2026-09-30T04:38:19.214Z" }, + { url = "https://files.pythonhosted.org/packages/a0/16/0e4c6ba9b44e97a2da150e52d331e8f9c968b21b358fbffa6c856cebcd89/charset_normalizer-3.5.2-cp315-cp315t-win32.whl", hash = "sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800", size = 197159, upload-time = "2026-09-30T04:38:21.037Z" }, + { url = "https://files.pythonhosted.org/packages/be/33/e90bc2b1374f7f36ef106f56620de5a783907e19ca857efe2277e31cac3e/charset_normalizer-3.5.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21", size = 221322, upload-time = "2026-09-30T04:38:22.886Z" }, + { url = "https://files.pythonhosted.org/packages/66/89/dfa6dcb08c200b7830ab56439e8c1890f2971d51aafbb3937894a2e7fcfc/charset_normalizer-3.5.2-cp315-cp315t-win_arm64.whl", hash = "sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58", size = 209192, upload-time = "2026-09-30T04:38:24.648Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + [[package]] name = "colorama" version = "0.4.6" @@ -585,6 +764,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, ] +[[package]] +name = "googleapis-common-protos" +version = "1.75.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b5/c8/f439cffde755cffa462bfbb156278fa6f9d09119719af9814b858fd4f81f/googleapis_common_protos-1.75.0.tar.gz", hash = "sha256:53a062ff3c32552fbd62c11fe23768b78e4ddf0494d5e5fd97d3f4689c75fbbd", size = 151035, upload-time = "2026-05-07T08:04:49.423Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/c8/e2645aa8ed02fd4c7a2f59d68783b65b1f3cbdfe39a6308e156509d1fee8/googleapis_common_protos-1.75.0-py3-none-any.whl", hash = "sha256:961ed60399c457ceb0ee8f285a84c870aabc9c6a832b9d37bb281b5bebde43ed", size = 300631, upload-time = "2026-05-07T08:03:30.345Z" }, +] + [[package]] name = "idna" version = "3.20" @@ -594,6 +785,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, ] +[[package]] +name = "importlib-metadata" +version = "8.7.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "zipp" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f3/49/3b30cad09e7771a4982d9975a8cbf64f00d4a1ececb53297f1d9a7be1b10/importlib_metadata-8.7.1.tar.gz", hash = "sha256:49fef1ae6440c182052f407c8d34a68f72efc36db9ca90dc0113398f2fdde8bb", size = 57107, upload-time = "2025-12-21T10:00:19.278Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fa/5e/f8e9a1d23b9c20a551a8a02ea3637b4642e22c2626e3a13a9a29cdea99eb/importlib_metadata-8.7.1-py3-none-any.whl", hash = "sha256:5a1f80bf1daa489495071efbb095d75a634cf28a8bc299581244063b53176151", size = 27865, upload-time = "2025-12-21T10:00:18.329Z" }, +] + [[package]] name = "iniconfig" version = "2.3.1" @@ -973,6 +1176,88 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b5/99/7b1adac7e97ce7bbda34792dc6e9b2f5cc5cffd1875883f78a818b2a2687/mypy_extensions-1.2.0-py3-none-any.whl", hash = "sha256:993e7a20aa5671eb41a7132cf555af30062da99729601601b9a8382b11cae768", size = 5114, upload-time = "2026-11-03T16:26:32.731Z" }, ] +[[package]] +name = "opentelemetry-api" +version = "1.34.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "importlib-metadata" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4d/5e/94a8cb759e4e409022229418294e098ca7feca00eb3c467bb20cbd329bda/opentelemetry_api-1.34.1.tar.gz", hash = "sha256:64f0bd06d42824843731d05beea88d4d4b6ae59f9fe347ff7dfa2cc14233bbb3", size = 64987, upload-time = "2025-06-10T08:55:19.818Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a5/3a/2ba85557e8dc024c0842ad22c570418dc02c36cbd1ab4b832a93edf071b8/opentelemetry_api-1.34.1-py3-none-any.whl", hash = "sha256:b7df4cb0830d5a6c29ad0c0691dbae874d8daefa934b8b1d642de48323d32a8c", size = 65767, upload-time = "2025-06-10T08:54:56.717Z" }, +] + +[[package]] +name = "opentelemetry-exporter-otlp-proto-common" +version = "1.34.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-proto" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/86/f0/ff235936ee40db93360233b62da932d4fd9e8d103cd090c6bcb9afaf5f01/opentelemetry_exporter_otlp_proto_common-1.34.1.tar.gz", hash = "sha256:b59a20a927facd5eac06edaf87a07e49f9e4a13db487b7d8a52b37cb87710f8b", size = 20817, upload-time = "2025-06-10T08:55:22.55Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/e8/8b292a11cc8d8d87ec0c4089ae21b6a58af49ca2e51fa916435bc922fdc7/opentelemetry_exporter_otlp_proto_common-1.34.1-py3-none-any.whl", hash = "sha256:8e2019284bf24d3deebbb6c59c71e6eef3307cd88eff8c633e061abba33f7e87", size = 18834, upload-time = "2025-06-10T08:55:00.806Z" }, +] + +[[package]] +name = "opentelemetry-exporter-otlp-proto-http" +version = "1.34.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "googleapis-common-protos" }, + { name = "opentelemetry-api" }, + { name = "opentelemetry-exporter-otlp-proto-common" }, + { name = "opentelemetry-proto" }, + { name = "opentelemetry-sdk" }, + { name = "requests" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/8f/954bc725961cbe425a749d55c0ba1df46832a5999eae764d1a7349ac1c29/opentelemetry_exporter_otlp_proto_http-1.34.1.tar.gz", hash = "sha256:aaac36fdce46a8191e604dcf632e1f9380c7d5b356b27b3e0edb5610d9be28ad", size = 15351, upload-time = "2025-06-10T08:55:24.657Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/79/54/b05251c04e30c1ac70cf4a7c5653c085dfcf2c8b98af71661d6a252adc39/opentelemetry_exporter_otlp_proto_http-1.34.1-py3-none-any.whl", hash = "sha256:5251f00ca85872ce50d871f6d3cc89fe203b94c3c14c964bbdc3883366c705d8", size = 17744, upload-time = "2025-06-10T08:55:03.802Z" }, +] + +[[package]] +name = "opentelemetry-proto" +version = "1.34.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/b3/c3158dd012463bb7c0eb7304a85a6f63baeeb5b4c93a53845cf89f848c7e/opentelemetry_proto-1.34.1.tar.gz", hash = "sha256:16286214e405c211fc774187f3e4bbb1351290b8dfb88e8948af209ce85b719e", size = 34344, upload-time = "2025-06-10T08:55:32.25Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/28/ab/4591bfa54e946350ce8b3f28e5c658fe9785e7cd11e9c11b1671a867822b/opentelemetry_proto-1.34.1-py3-none-any.whl", hash = "sha256:eb4bb5ac27f2562df2d6857fc557b3a481b5e298bc04f94cc68041f00cebcbd2", size = 55692, upload-time = "2025-06-10T08:55:14.904Z" }, +] + +[[package]] +name = "opentelemetry-sdk" +version = "1.34.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6f/41/fe20f9036433da8e0fcef568984da4c1d1c771fa072ecd1a4d98779dccdd/opentelemetry_sdk-1.34.1.tar.gz", hash = "sha256:8091db0d763fcd6098d4781bbc80ff0971f94e260739aa6afe6fd379cdf3aa4d", size = 159441, upload-time = "2025-06-10T08:55:33.028Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/1b/def4fe6aa73f483cabf4c748f4c25070d5f7604dcc8b52e962983491b29e/opentelemetry_sdk-1.34.1-py3-none-any.whl", hash = "sha256:308effad4059562f1d92163c61c8141df649da24ce361827812c40abb2a1e96e", size = 118477, upload-time = "2025-06-10T08:55:16.02Z" }, +] + +[[package]] +name = "opentelemetry-semantic-conventions" +version = "0.55b1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5d/f0/f33458486da911f47c4aa6db9bda308bb80f3236c111bf848bd870c16b16/opentelemetry_semantic_conventions-0.55b1.tar.gz", hash = "sha256:ef95b1f009159c28d7a7849f5cbc71c4c34c845bb514d66adfdf1b3fff3598b3", size = 119829, upload-time = "2025-06-10T08:55:33.881Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1a/89/267b0af1b1d0ba828f0e60642b6a5116ac1fd917cde7fc02821627029bd1/opentelemetry_semantic_conventions-0.55b1-py3-none-any.whl", hash = "sha256:5da81dfdf7d52e3d37f8fe88d5e771e191de924cfff5f550ab0b8f7b2409baed", size = 196223, upload-time = "2025-06-10T08:55:17.638Z" }, +] + [[package]] name = "packaging" version = "26.3" @@ -1128,6 +1413,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f5/cd/785c64ed382f3f04201870267b02783f63b4678c2acfddc177a3ebcc2727/propcache-0.5.4-py3-none-any.whl", hash = "sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468", size = 16338, upload-time = "2026-09-16T00:17:13.106Z" }, ] +[[package]] +name = "protobuf" +version = "5.29.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/57/394a763c103e0edf87f0938dafcd918d53b4c011dfc5c8ae80f3b0452dbb/protobuf-5.29.6.tar.gz", hash = "sha256:da9ee6a5424b6b30fd5e45c5ea663aef540ca95f9ad99d1e887e819cdf9b8723", size = 425623, upload-time = "2026-02-04T22:54:40.584Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d4/88/9ee58ff7863c479d6f8346686d4636dd4c415b0cbeed7a6a7d0617639c2a/protobuf-5.29.6-cp310-abi3-win32.whl", hash = "sha256:62e8a3114992c7c647bce37dcc93647575fc52d50e48de30c6fcb28a6a291eb1", size = 423357, upload-time = "2026-02-04T22:54:25.805Z" }, + { url = "https://files.pythonhosted.org/packages/1c/66/2dc736a4d576847134fb6d80bd995c569b13cdc7b815d669050bf0ce2d2c/protobuf-5.29.6-cp310-abi3-win_amd64.whl", hash = "sha256:7e6ad413275be172f67fdee0f43484b6de5a904cc1c3ea9804cb6fe2ff366eda", size = 435175, upload-time = "2026-02-04T22:54:28.592Z" }, + { url = "https://files.pythonhosted.org/packages/06/db/49b05966fd208ae3f44dcd33837b6243b4915c57561d730a43f881f24dea/protobuf-5.29.6-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:b5a169e664b4057183a34bdc424540e86eea47560f3c123a0d64de4e137f9269", size = 418619, upload-time = "2026-02-04T22:54:30.266Z" }, + { url = "https://files.pythonhosted.org/packages/b7/d7/48cbf6b0c3c39761e47a99cb483405f0fde2be22cf00d71ef316ce52b458/protobuf-5.29.6-cp38-abi3-manylinux2014_aarch64.whl", hash = "sha256:a8866b2cff111f0f863c1b3b9e7572dc7eaea23a7fae27f6fc613304046483e6", size = 320284, upload-time = "2026-02-04T22:54:31.782Z" }, + { url = "https://files.pythonhosted.org/packages/e3/dd/cadd6ec43069247d91f6345fa7a0d2858bef6af366dbd7ba8f05d2c77d3b/protobuf-5.29.6-cp38-abi3-manylinux2014_x86_64.whl", hash = "sha256:e3387f44798ac1106af0233c04fb8abf543772ff241169946f698b3a9a3d3ab9", size = 320478, upload-time = "2026-02-04T22:54:32.909Z" }, + { url = "https://files.pythonhosted.org/packages/5a/cb/e3065b447186cb70aa65acc70c86baf482d82bf75625bf5a2c4f6919c6a3/protobuf-5.29.6-py3-none-any.whl", hash = "sha256:6b9edb641441b2da9fa8f428760fc136a49cf97a52076010cf22a2ff73438a86", size = 173126, upload-time = "2026-02-04T22:54:39.462Z" }, +] + [[package]] name = "pydantic" version = "2.14.3" @@ -1409,6 +1708,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, ] +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + [[package]] name = "rpds-py" version = "2026.9.1" @@ -1590,6 +1904,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, ] +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + [[package]] name = "watchdog" version = "7.1.0" @@ -1773,3 +2096,12 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/91/41e284ca2cf5211e05dae031d126a3668aea88fa759df56e7e35c6ad25ba/yarl-1.25.1-cp315-cp315t-win_arm64.whl", hash = "sha256:783dd1467083f4d3f7722ad6a313f24c173e7571372738fcb7a6e6d1ba48df25", size = 101804, upload-time = "2026-09-15T19:34:57.231Z" }, { url = "https://files.pythonhosted.org/packages/54/22/318c7980066769c6bcd9221ed2248294f5698811da099013098c670565ed/yarl-1.25.1-py3-none-any.whl", hash = "sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3", size = 63617, upload-time = "2026-09-15T19:34:59.616Z" }, ] + +[[package]] +name = "zipp" +version = "4.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/05/ba1458dee0ac485b2a01071c1b88f5199fe878a485df482e10e1ef2205cc/zipp-4.1.2.tar.gz", hash = "sha256:cf474b90b07ea932637e17c6b9479de2b2882900b0d311bdaf4f5c000a15a97f", size = 27864, upload-time = "2026-10-21T18:57:04.743Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/44/7bd2007260da11cccca29ba2d4c345f1287aa663db38ee7cefeabf6386a5/zipp-4.1.2-py3-none-any.whl", hash = "sha256:b30cb6cd253122169c47de245ca24a86bac2a5d3802ba15bf7ba6414eb9e144d", size = 10581, upload-time = "2026-10-21T18:57:03.79Z" }, +] From 2bc9795f829c3773c1c44fb79361f8bbe5262ff5 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:14:23 +0800 Subject: [PATCH 02/10] refactor(rust): gate runtime extensions and switch Core defaults Signed-off-by: tercel --- rust/Cargo.lock | 2 +- rust/Cargo.toml | 43 +- rust/README.md | 45 +- rust/apcore-conformance.yaml | 11 +- rust/src/acl.rs | 12 +- rust/src/async_task.rs | 13 +- rust/src/bindings.rs | 35 +- rust/src/builtin_steps.rs | 57 +- rust/src/client.rs | 314 ++++++---- rust/src/config.rs | 58 +- rust/src/context.rs | 39 -- rust/src/events/circuit_breaker.rs | 2 +- rust/src/events/emitter.rs | 2 +- rust/src/events/mod.rs | 7 +- rust/src/events/subscribers.rs | 460 +++----------- rust/src/executor.rs | 53 +- rust/src/lib.rs | 39 +- rust/src/lifecycle.rs | 2 + rust/src/middleware/yaml_config.rs | 3 +- rust/src/observability/mod.rs | 2 - rust/src/observability/prometheus_exporter.rs | 364 ----------- rust/src/observability/redaction.rs | 4 +- rust/src/observability/usage.rs | 40 +- rust/src/policy.rs | 37 +- rust/src/registry/managed_drain.rs | 28 +- rust/src/registry/managed_lifecycle.rs | 3 + rust/src/registry/managed_reload.rs | 1 + rust/src/registry/metadata.rs | 6 +- rust/src/registry/mod.rs | 8 +- rust/src/registry/registry.rs | 42 +- rust/src/schema/exporter.rs | 427 +------------ rust/src/schema/mod.rs | 6 +- rust/src/schema/strict.rs | 58 +- rust/src/sys_modules/audit.rs | 6 +- rust/src/sys_modules/control.rs | 53 +- rust/src/sys_modules/health.rs | 19 +- rust/src/sys_modules/mod.rs | 104 +++- rust/src/version.rs | 3 + rust/tests/apcore_client_spec.rs | 28 +- rust/tests/conformance_test.rs | 14 +- rust/tests/core_profile.rs | 194 ++++++ rust/tests/event_system_spec.rs | 129 +--- rust/tests/it.rs | 2 - rust/tests/observability_spec.rs | 68 +-- rust/tests/policy_governance.rs | 32 +- rust/tests/test_client.rs | 39 +- rust/tests/test_compute_delay_ms.rs | 17 +- rust/tests/test_context_logger_deprecation.rs | 104 ---- rust/tests/test_crate_root_exports.rs | 28 +- rust/tests/test_event_delivery_conformance.rs | 24 +- ..._event_management_hardening_conformance.rs | 116 ++-- rust/tests/test_events.rs | 76 +-- rust/tests/test_executor.rs | 14 +- rust/tests/test_governance_state.rs | 7 +- .../test_governance_state_conformance.rs | 4 +- rust/tests/test_issue_123_conformance.rs | 170 +----- ...est_observability_hardening_conformance.rs | 8 +- .../test_reload_dependents_deprecation.rs | 200 +------ .../test_reload_path_filter_conformance.rs | 7 +- rust/tests/test_schema_exporter.rs | 566 ++---------------- rust/tests/test_serde_wire_format.rs | 30 - rust/tests/test_single_sdk_defects.rs | 54 +- rust/tests/test_subscriber_retry_config.rs | 12 - ...st_system_modules_hardening_conformance.rs | 87 +++ rust/tests/test_unified_registry.rs | 28 +- .../tests/test_webhook_http_retry_contract.rs | 87 +-- 66 files changed, 1504 insertions(+), 3049 deletions(-) delete mode 100644 rust/src/observability/prometheus_exporter.rs create mode 100644 rust/tests/core_profile.rs delete mode 100644 rust/tests/test_context_logger_deprecation.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 0b4cab0c..554d1a0c 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -42,7 +42,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.1" +version = "1.0.0-alpha.2" dependencies = [ "async-stream", "async-trait", diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 1f8c7cd2..557bbd1a 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore" -version = "1.0.0-alpha.1" +version = "1.0.0-alpha.2" 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 @@ -39,6 +39,11 @@ rustdoc-args = ["--cfg", "docsrs"] [[test]] name = "it" path = "tests/it.rs" +required-features = ["config", "discovery", "events-file", "sys-modules"] + +[[test]] +name = "core_profile" +path = "tests/core_profile.rs" # Files that register into the process-global Config namespace registry or # mutate env vars are kept as SEPARATE binaries so each runs in its own process @@ -49,22 +54,37 @@ path = "tests/it.rs" [[example]] name = "format_date" path = "examples/bindings/format_date.rs" +required-features = ["config"] + +[[example]] +name = "acl_config_driven" +path = "examples/acl_config_driven.rs" +required-features = ["config"] + +[[example]] +name = "execution_policy" +path = "examples/execution_policy.rs" +required-features = ["config"] [[test]] name = "config_bus" path = "tests/config_bus.rs" +required-features = ["config", "discovery", "sys-modules"] [[test]] name = "config_bus_spec" path = "tests/config_bus_spec.rs" +required-features = ["config", "discovery", "sys-modules"] [[test]] name = "config_discovery" path = "tests/config_discovery.rs" +required-features = ["config", "discovery", "sys-modules"] [[test]] name = "conformance_test" path = "tests/conformance_test.rs" +required-features = ["config", "discovery", "sys-modules"] # The three §9.2.1 / §9.2.2 / §5.12.6 conformance drivers. Each mutates the # process environment (`APCORE_*`, `HOME`) and/or the working directory, which @@ -72,14 +92,17 @@ path = "tests/conformance_test.rs" [[test]] name = "test_config_path_typed_keys_conformance" path = "tests/test_config_path_typed_keys_conformance.rs" +required-features = ["config", "discovery", "sys-modules"] [[test]] name = "test_bindings_dir_resolution_conformance" path = "tests/test_bindings_dir_resolution_conformance.rs" +required-features = ["config", "discovery", "sys-modules"] [[test]] name = "test_config_project_root_conformance" path = "tests/test_config_project_root_conformance.rs" +required-features = ["config", "discovery", "sys-modules"] # §9.2.4's deprecation notice is asserted at the ENVIRONMENT tier too, so this # file sets `APCORE_*` variables. A leaked variable is invisible to the test @@ -88,29 +111,35 @@ path = "tests/test_config_project_root_conformance.rs" [[test]] name = "test_deprecated_inert_keys" path = "tests/test_deprecated_inert_keys.rs" +required-features = ["config", "discovery", "sys-modules"] # Mutates `APCORE_*` for the environment tier, so it gets its own process # like the discovery drivers above. [[test]] name = "test_get_declared_typed_sections" path = "tests/test_get_declared_typed_sections.rs" +required-features = ["config", "discovery", "sys-modules"] # Sets `APCORE_ID__MAP_OVERRIDES` and the working directory per case. [[test]] name = "test_id_map_from_config_conformance" path = "tests/test_id_map_from_config_conformance.rs" +required-features = ["discovery"] [[test]] name = "test_capture_point_redaction" path = "tests/test_capture_point_redaction.rs" +required-features = ["config", "discovery", "sys-modules"] [[test]] name = "test_extensions_ignore_patterns" path = "tests/test_extensions_ignore_patterns.rs" +required-features = ["config", "discovery", "sys-modules"] [[test]] name = "test_issue_123_conformance" path = "tests/test_issue_123_conformance.rs" +required-features = ["config", "discovery", "sys-modules"] # Changes proxy environment variables, so it must run outside the shared test binary. [[test]] @@ -119,10 +148,10 @@ path = "tests/test_otlp_proxy_routing.rs" required-features = ["events"] [dependencies] -tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "fs", "io-util", "net"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"] } serde = { version = "1", features = ["derive"] } serde_json = "1" -serde_yaml_ng = "0.10" +serde_yaml_ng = { version = "0.10", optional = true } chrono = { version = "0.4", features = ["serde"] } uuid = { version = "1", features = ["v4", "serde"] } thiserror = "2" @@ -143,11 +172,17 @@ async-stream = "0.3" parking_lot = "0.12" schemars = "0.8" dashmap = "6" -notify = { version = "8", default-features = false, features = ["macos_fsevent"] } +notify = { version = "8", optional = true, default-features = false, features = ["macos_fsevent"] } [features] +# Retain the existing default API while consumers opt into named extensions. default = [] +config = ["dep:serde_yaml_ng"] +discovery = ["config", "dep:notify"] events = ["reqwest", "dep:h2", "dep:url"] +events-file = ["tokio/fs", "tokio/io-util"] +sys-modules = ["config"] +full = ["config", "discovery", "events", "events-file", "sys-modules"] [dev-dependencies] tempfile = "3" diff --git a/rust/README.md b/rust/README.md index 8104fa65..a653aef4 100644 --- a/rust/README.md +++ b/rust/README.md @@ -92,7 +92,7 @@ tests at `tests/test_async_task.rs` and `tests/test_extensions.rs`. |------|-------------| | `SchemaLoader` | Load schemas from YAML or native types | | `SchemaValidator` | Validate data against schemas | -| `SchemaExporter` | Export schemas for MCP, OpenAI, Anthropic, generic | +| `export_generic` / `to_strict_schema` | Preserve the full JSON Schema or apply the A23 transform | | `RefResolver` | Resolve `$ref` references in JSON Schema | **Observability** @@ -127,18 +127,45 @@ For full documentation, including Quick Start guides for Python and Rust, visit: - Rust >= 1.86 (enforced by `rust-version` in `Cargo.toml`) - Tokio async runtime -## Installation +## Installation and feature profiles -Add to your `Cargo.toml`: +[APCore::new](./src/client.rs) assembles the in-memory registry and executor. +The default profile keeps Tokio runtime, macros, synchronization, and timers +for streaming, cancellation, and managed lifecycle. Discovery, filesystem +watching, YAML loading, and network delivery are opt-in. -```toml -[dependencies] -apcore = "0.32" -tokio = { version = "1", features = ["full"] } -serde_json = "1" -async-trait = "0.1" +| Cargo feature | Capability | +|---------------|------------| +| `config` | YAML configuration, file-backed ACLs, and bindings | +| `discovery` | Filesystem module discovery and watching | +| `sys-modules` | Configured system modules and event setup | +| `events` | HTTP webhook delivery and OTLP transport | +| `events-file` | JSONL event subscribers | +| `full` | All of the above | + +Use `APCore::with_config` or `APCore::try_start` with the required features for +configured startup. Calls requiring approval are denied when a handler is +missing. Destructive modules require approval by default. Configure an +`ApprovalHandler` to resolve those calls or set the relevant +`ExecutionPolicy` switch explicitly. + +Add the crate to your project: + +```sh +cargo add apcore +cargo add tokio --features macros,rt-multi-thread +cargo add serde_json async-trait ``` +For a prerelease, select its exact version on [crates.io](https://crates.io/crates/apcore). +Enable `full` on the `apcore` dependency when the application uses all of the +optional integrations. + +Configured health summaries expose `project.version` when supplied. Explicit +`sys_modules.usage.retention_hours` sets the cutoff for hourly usage buckets +at collector startup. Without that setting, the collector keeps up to 168 +occupied buckets per module. + ## Bare-name canonicalization Use `canonicalize_name` for one external name, such as a CLI command or diff --git a/rust/apcore-conformance.yaml b/rust/apcore-conformance.yaml index 35910987..16f569f2 100644 --- a/rust/apcore-conformance.yaml +++ b/rust/apcore-conformance.yaml @@ -1,6 +1,6 @@ implementation: name: apcore-rust - version: 1.0.0-alpha.1 + version: 1.0.0-alpha.2 language: rust spec_version: 1.65.0 maintainer: AI Perceivable @@ -10,9 +10,9 @@ conformance: date: '2026-10-08' fixture_results: scope: issue-123-and-canonicalize-name - fixtures: 9 - cases: 79 - passed: 79 + fixtures: 8 + cases: 74 + passed: 74 failed: 0 skipped: 0 report: @@ -24,7 +24,6 @@ conformance: - env_prefix_dispatch - ephemeral_modules - error_details_shape - - export_profiles - json_input_native_types - preflight_check_reporting - timeout_cancellation @@ -44,5 +43,5 @@ conformance: severity: minor - feature: complete fixture inventory certification spec: conformance declaration - reason: This declaration certifies the eight issue-123 fixtures and the bare-name fixture only; it does not claim that every canonical fixture case or a higher conformance level was verified. + reason: This declaration certifies the seven Core issue-123 fixtures and the bare-name fixture only; it does not claim that every canonical fixture case or a higher conformance level was verified. severity: major diff --git a/rust/src/acl.rs b/rust/src/acl.rs index 488bcd4f..87d5c03b 100644 --- a/rust/src/acl.rs +++ b/rust/src/acl.rs @@ -3,9 +3,11 @@ use chrono::Utc; use serde::{Deserialize, Serialize}; +#[cfg(feature = "config")] use serde_yaml_ng as serde_yaml; use std::collections::{HashMap, HashSet}; use std::future::Future; +#[cfg(feature = "config")] use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Once}; @@ -23,6 +25,7 @@ use crate::utils::match_pattern; /// /// Closed on purpose: a key nothing evaluates is otherwise dropped in silence, /// which widens an `allow` rule with no warning (#107). +#[cfg(feature = "config")] const RULE_KEYS: &[&str] = &[ "callers", "targets", @@ -48,6 +51,7 @@ const EFFECTS: &[&str] = &["allow", "deny"]; /// Rejected like any other unknown key, but named as reserved in the message: /// an operator who wrote `actions: ["describe"]` meant to restrict the rule and /// is better served by "not implemented" than by "unknown key". +#[cfg(feature = "config")] const RESERVED_RULE_KEYS: &[&str] = &["id", "actions", "priority"]; /// The caller identity an absent `caller_id` resolves to (PROTOCOL_SPEC §6.5). @@ -68,6 +72,7 @@ const RESERVED_RULE_KEYS: &[&str] = &["id", "actions", "priority"]; pub const EXTERNAL_CALLER: &str = "@external"; /// Reject any rule key outside [`RULE_KEYS`]. +#[cfg(feature = "config")] fn reject_unknown_rule_keys( index: usize, path: &str, @@ -940,6 +945,7 @@ pub(crate) fn warn_audit_block_overridden( /// /// Validates the SUBTREE only: types and unknown keys inside the block. Every /// other unrecognised root key in an ACL file keeps being ignored. +#[cfg(feature = "config")] pub(crate) fn parse_audit_block( raw: &serde_json::Value, path: &str, @@ -1975,6 +1981,7 @@ impl ACL { } /// Load ACL rules from a YAML file. + #[cfg(feature = "config")] pub fn load(path: &str) -> Result { let content = std::fs::read_to_string(path).map_err(|e| { ModuleError::new( @@ -2182,6 +2189,7 @@ impl ACL { /// # Errors /// Returns [`ModuleError`] when a policy path cannot be inspected or /// the policy cannot be loaded. A missing path yields `Ok(None)`. + #[cfg(feature = "config")] pub fn discover(config: &crate::config::Config) -> Result, ModuleError> { let Some(root_path) = config.get_path("acl.root") else { return Ok(None); @@ -2209,6 +2217,7 @@ impl ACL { Self::load(&path.to_string_lossy()).map(Some) } + #[cfg(feature = "config")] fn discover_metadata(path: &Path) -> Result, ModuleError> { let inspect_error = |error: std::io::Error| { ModuleError::new( @@ -2260,6 +2269,7 @@ impl ACL { /// Holding `&mut self` across `Self::load` would block any concurrent /// reader for the duration of the file read; the brace scope below /// makes that explicitly impossible (sync finding A-D-303). + #[cfg(feature = "config")] pub fn reload(&mut self) -> Result<(), ModuleError> { let path = { // Narrow scope: the immutable borrow on `self.yaml_path` ends @@ -3025,7 +3035,7 @@ impl Default for ACL { } } -#[cfg(test)] +#[cfg(all(test, feature = "config"))] mod reload_tests { use super::*; use std::io::Write; diff --git a/rust/src/async_task.rs b/rust/src/async_task.rs index 6fe9ccdb..0be6b5f8 100644 --- a/rust/src/async_task.rs +++ b/rust/src/async_task.rs @@ -282,9 +282,7 @@ impl RetryConfig { /// differ by under 1 ms, and only for a non-integer product. /// /// Cross-language: this is the canonical name across `apcore-python` and - /// `apcore-typescript` (sync alignment D-08). The legacy - /// [`Self::delay_for_attempt`] alias delegates to this method and is - /// `#[deprecated]`; it will be removed in the next minor version. + /// `apcore-typescript` (sync alignment D-08). #[must_use] pub fn compute_delay_ms(&self, attempt: u32) -> u64 { // Use f64 arithmetic to apply the backoff factor, then clamp to the cap. @@ -307,15 +305,6 @@ impl RetryConfig { let out = capped as u64; out } - - /// Deprecated alias for [`Self::compute_delay_ms`] (sync alignment D-08). - /// - /// Kept for one minor version to allow callers a graceful migration. - #[must_use] - #[deprecated(since = "0.21.0", note = "use compute_delay_ms")] - pub fn delay_for_attempt(&self, attempt: u32) -> u64 { - self.compute_delay_ms(attempt) - } } // --------------------------------------------------------------------------- diff --git a/rust/src/bindings.rs b/rust/src/bindings.rs index df26c2f6..18484906 100644 --- a/rust/src/bindings.rs +++ b/rust/src/bindings.rs @@ -7,26 +7,36 @@ // is byte-identical across Python, TypeScript, and Rust SDKs. use serde::{Deserialize, Serialize}; +#[cfg(feature = "config")] use serde_yaml_ng as serde_yaml; use std::collections::HashMap; +#[cfg(feature = "config")] use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::Arc; use crate::context::Context; +#[cfg(feature = "config")] use crate::decorator::FunctionModule; use crate::errors::{ErrorCode, ModuleError}; +#[cfg(feature = "config")] use crate::module::ModuleAnnotations; +#[cfg(feature = "config")] use crate::registry::registry::Registry; +#[cfg(feature = "config")] use crate::schema::openai_strict::assert_openai_strict_compatible; +#[cfg(feature = "config")] use crate::utils::helpers::match_glob; +#[cfg(feature = "config")] const CURRENT_SPEC_VERSION: &str = "1.0"; /// Config key naming the directory scanned for binding files (§9.1.1). +#[cfg(feature = "config")] const CONFIG_KEY_BINDINGS_DIR: &str = "bindings.dir"; /// Config key naming the glob binding files must match within that directory. +#[cfg(feature = "config")] const CONFIG_KEY_BINDINGS_PATTERN: &str = "bindings.pattern"; /// Canonical default for `bindings.dir`, from `schemas/defaults.schema.json` @@ -48,12 +58,15 @@ const CONFIG_KEY_BINDINGS_PATTERN: &str = "bindings.pattern"; /// pinned rather than trusted: `the_loader_default_matches_the_canonical_ /// default_table` asserts these two constants equal `Config::default_for` for /// their keys, so the pair cannot drift. +#[cfg(feature = "config")] const DEFAULT_BINDING_DIR: &str = "./bindings"; /// Canonical default for `bindings.pattern`, from the same schemas, kept on the /// same terms as [`DEFAULT_BINDING_DIR`]. +#[cfg(feature = "config")] const DEFAULT_BINDING_PATTERN: &str = "*.binding.yaml"; +#[cfg(feature = "config")] const SUPPORTED_SPEC_VERSIONS: &[&str] = &["1.0"]; /// Boxed async handler function type. @@ -205,6 +218,7 @@ impl AutoSchemaValue { /// without a configuration uses — so a binding file that loaded before this /// type existed still loads after it. #[derive(Debug, Default, Clone)] +#[cfg(feature = "config")] pub struct ValidationLimits { description_max: Option, documentation_max: Option, @@ -212,6 +226,7 @@ pub struct ValidationLimits { require_semver: bool, } +#[cfg(feature = "config")] impl ValidationLimits { /// Read the four keys from a [`Config`]. Unset keys stay unconstrained. /// @@ -253,6 +268,7 @@ impl ValidationLimits { } /// Apply the configured limits to one entry. Unset limits check nothing. + #[cfg(feature = "config")] fn check(&self, entry: &BindingEntry, path: &Path) -> Result<(), ModuleError> { let invalid = |reason: String| { ModuleError::new( @@ -318,6 +334,7 @@ impl ValidationLimits { /// spaces inside the pattern. It compiled, and it rejected EVERY version /// including valid SemVer. There is no `(?x)` flag here: whitespace in this /// pattern is significant, so it must contain none. +#[cfg(feature = "config")] fn semver_re() -> &'static regex::Regex { static RE: std::sync::OnceLock = std::sync::OnceLock::new(); RE.get_or_init(|| { @@ -391,6 +408,7 @@ pub struct BindingsFile { /// In-memory resolved schema pair for a binding. #[derive(Debug, Clone)] +#[cfg(feature = "config")] struct ResolvedSchemas { input: serde_json::Value, output: serde_json::Value, @@ -398,6 +416,7 @@ struct ResolvedSchemas { /// Loads and resolves module bindings from `*.binding.yaml` files. #[derive(Debug)] +#[cfg(feature = "config")] pub struct BindingLoader { /// Registered binding entries keyed by `module_id`. bindings: HashMap, @@ -409,6 +428,7 @@ pub struct BindingLoader { limits: ValidationLimits, } +#[cfg(feature = "config")] fn read_schema_reference( binding_dir: &Path, source_path: &Path, @@ -467,6 +487,7 @@ fn read_schema_reference( }) } +#[cfg(feature = "config")] fn reference_in_schema_root( reference: &Path, binding_root: &Path, @@ -484,6 +505,7 @@ fn reference_in_schema_root( .is_some_and(|parent| reference.starts_with(parent.join("schemas"))) } +#[cfg(feature = "config")] impl BindingLoader { /// Create a new empty binding loader. #[must_use] @@ -1023,6 +1045,7 @@ impl BindingLoader { } } +#[cfg(feature = "config")] impl Default for BindingLoader { fn default() -> Self { Self::new() @@ -1032,6 +1055,7 @@ impl Default for BindingLoader { /// Normalized `auto_schema` mode for an entry: `Some("permissive")`, /// `Some("strict")`, or `None` (absent, explicitly `false`, or invalid — the /// latter two are already rejected by `resolve_schemas` at ingest). +#[cfg(feature = "config")] fn normalized_auto_mode(entry: &BindingEntry) -> Option<&'static str> { match entry.auto_schema.as_ref()?.normalize() { Ok(Some("strict")) => Some("strict"), @@ -1047,6 +1071,7 @@ fn normalized_auto_mode(entry: &BindingEntry) -> Option<&'static str> { /// apcore-typescript `BindingSchemaInferenceFailedError`: message carries the /// `{file_path}: ` prefix from protocol-spec §5.12.8 and the details /// map carries `module_id`, `target` and `file_path`. +#[cfg(feature = "config")] fn strict_inference_failed(entry: &BindingEntry, module_id: &str, reason: &str) -> ModuleError { let mode = normalized_auto_mode(entry).unwrap_or("implicit"); let loc = entry @@ -1091,6 +1116,7 @@ fn strict_inference_failed(entry: &BindingEntry, module_id: &str, reason: &str) /// apcore-python and apcore-typescript emit for the same file — a message-parity /// divergence that no test could see, because the driver for that fixture case /// asserted nothing (apcore#93). +#[cfg(feature = "config")] fn require_bindings_key(path: &Path, bindings: Option<&T>) -> Result<(), ModuleError> { if bindings.is_some() { return Ok(()); @@ -1120,6 +1146,7 @@ fn require_bindings_key(path: &Path, bindings: Option<&T>) -> Result<(), Modu /// separator loaded silently and failed much later as an unrelated /// handler-lookup miss. The message matches apcore-python's /// `BindingInvalidTargetError` byte for byte. +#[cfg(feature = "config")] fn validate_target(target: &str) -> Result<(), ModuleError> { let well_formed = target .split_once(':') @@ -1134,6 +1161,7 @@ fn validate_target(target: &str) -> Result<(), ModuleError> { } /// Detect which schema-mode fields a binding entry sets. +#[cfg(feature = "config")] fn detect_modes(entry: &BindingEntry) -> Vec { let mut modes = Vec::new(); if entry.auto_schema.is_some() { @@ -1174,6 +1202,7 @@ fn detect_modes(entry: &BindingEntry) -> Vec { /// `annotations.extra`, where the executor reads it (D-11). Keeping the budget /// in `extra` matches the canonical wire form (§4.4.1): extension keys are not /// flattened onto the annotations root. +#[cfg(feature = "config")] fn annotations_with_resources( entry: &BindingEntry, module_id: &str, @@ -1185,6 +1214,7 @@ fn annotations_with_resources( Ok(annotations) } +#[cfg(feature = "config")] fn annotations_from_value( module_id: &str, value: Option<&serde_json::Value>, @@ -1204,6 +1234,7 @@ fn annotations_from_value( } /// Publish the canonical overlay and retain the Rust compatibility key. +#[cfg(feature = "config")] fn apply_display_metadata( metadata: &mut HashMap, display: Option<&serde_json::Value>, @@ -1216,7 +1247,7 @@ fn apply_display_metadata( } } -#[cfg(test)] +#[cfg(all(test, feature = "config"))] mod tests { /// PROTOCOL_SPEC §9.1.2 requirement 6 — BOTH halves. @@ -1644,7 +1675,7 @@ bindings: } } -#[cfg(test)] +#[cfg(all(test, feature = "config"))] mod bindings_dir_from_config_tests { //! `bindings.dir` / `bindings.pattern` reaching the loader from a //! **config file** (aiperceivable/apcore#114, PROTOCOL_SPEC §5.12.6). diff --git a/rust/src/builtin_steps.rs b/rust/src/builtin_steps.rs index 82f134d7..0c9287be 100644 --- a/rust/src/builtin_steps.rs +++ b/rust/src/builtin_steps.rs @@ -10,7 +10,7 @@ use crate::errors::{ErrorCode, ModuleError}; use crate::events::emitter::ApCoreEvent; use crate::executor::{redact_sensitive_with, validate_against_schema}; use crate::pipeline::{BuiltinGate, ExecutionStrategy, PipelineContext, Step, StepResult}; -use crate::policy::PolicyDecision; +use crate::policy::{ExecutionPolicy, PolicyDecision}; // Macro for step metadata — execute is implemented manually per step. macro_rules! step_meta { @@ -720,28 +720,17 @@ impl Step for BuiltinApprovalGate { // the inputs exist so the call site reaches the audit trail (rule 3). // These are the business arguments at the gate. Module middleware and // schema validation run later, and the resume credential is isolated. - let decision: Option = ctx.policy.clone().map(|policy| { - policy.resolve_with_call_site( - &ctx.module_id, - module_annotations.as_ref(), - Some(&ctx.inputs), - Some(&ctx.context), - ) - }); - - let (policy_effective_approval, effective_destructive) = match &decision { - Some(d) => (d.needs_approval, d.destructive), - None => ( - module_annotations - .as_ref() - .is_some_and(|a| a.requires_approval), - module_annotations.as_ref().is_some_and(|a| a.destructive), - ), - }; + let policy = ExecutionPolicy::effective(ctx.policy.as_deref()); + let decision = policy.resolve_with_call_site( + &ctx.module_id, + module_annotations.as_ref(), + Some(&ctx.inputs), + Some(&ctx.context), + ); // PROTOCOL_SPEC §7.4 / §6.9 rows 3-5: the gate fires on the UNION of // the module's `annotations.requires_approval`, the Step-4 ACL - // decision, and `gate_destructive`. `policy_effective_approval` already + // decision, and `gate_destructive`. `decision.needs_approval` already // folds the annotation and `gate_destructive` together; the ACL's // requirement joins them here. // @@ -756,20 +745,18 @@ impl Step for BuiltinApprovalGate { // `requires_approval: false` overrides the module's *annotation* and // never the ACL's decision. let acl_requires_approval = ctx.acl_approval_required; - let needs_approval = policy_effective_approval || acl_requires_approval; + let needs_approval = decision.needs_approval || acl_requires_approval; // Audit a policy-driven override: log, span, and bus event (apcore#77). - if let Some(d) = &decision { - if d.overridden { - Self::emit_policy_override(ctx, d); - Self::emit_policy_override_event(ctx, d).await; - } + if decision.overridden { + Self::emit_policy_override(ctx, &decision); + Self::emit_policy_override_event(ctx, &decision).await; } if !needs_approval { // Fail-loud governance (apcore#76): a module that is effectively // destructive but that no approval gate covers is warned about once. - if effective_destructive { + if decision.destructive { Self::warn_once( ctx, &format!("destructive_ungated:{}", ctx.module_id), @@ -785,10 +772,9 @@ impl Step for BuiltinApprovalGate { return Ok(StepResult::continue_step()); } - // The module needs approval. Resolve the handler; when none is - // configured, FLIP the historical silent-skip to fail-loud (apcore#76). + // A missing handler refuses an approval-required call by default. let Some(handler) = ctx.approval_handler.clone() else { - if ctx.policy.as_ref().is_some_and(|p| p.strict) { + if policy.strict { // strict=true fails CLOSED: build a rejected result, audit it, // and deny. let result = crate::approval::ApprovalResult { @@ -804,17 +790,16 @@ impl Step for BuiltinApprovalGate { Self::emit_approval_decision_event(ctx, &result, None).await; return Err(Self::approval_error(&ctx.module_id, &result)); } - // Non-strict: keep the PROTOCOL_SPEC §7.4 skip behavior but warn - // once per module (fail-loud, not silent). Emits no decision event + // An explicit non-strict policy warns once per module and + // continues. It emits no decision event // — parity with the "no audit log when gate skipped" contract. Self::warn_once( ctx, &format!("no_handler:{}", ctx.module_id), &format!( "Module '{}' requires approval but no ApprovalHandler is configured; \ - the approval gate is skipped per PROTOCOL_SPEC §7.4. Configure an \ - approval handler, or ExecutionPolicy(strict=true) to fail closed. \ - (apcore#76)", + the explicit non-strict policy permits this call. Configure an \ + approval handler or enable strict enforcement.", ctx.module_id ), ); @@ -824,7 +809,7 @@ impl Step for BuiltinApprovalGate { let module = module.ok_or_else(|| ModuleError::module_not_found(&ctx.module_id))?; let mut annotations = module_annotations.unwrap_or_default(); annotations.requires_approval = true; - annotations.destructive = effective_destructive; + annotations.destructive = decision.destructive; let description = module.description(); let request = crate::approval::ApprovalRequest { module_id: ctx.module_id.clone(), diff --git a/rust/src/client.rs b/rust/src/client.rs index 11b04efb..875ee866 100644 --- a/rust/src/client.rs +++ b/rust/src/client.rs @@ -12,7 +12,7 @@ use crate::context::Context; use crate::decorator::FunctionModule; use crate::errors::ModuleError; use crate::events::emitter::EventEmitter; -use crate::events::subscribers::EventSubscriber; +use crate::events::subscribers::{EventSubscriber, SubscriberRegistry}; use crate::executor::Executor; use crate::lifecycle::{ invalid_lifecycle_input, lifecycle_runtime, LifecycleOperation, ShutdownOptions, @@ -25,7 +25,9 @@ use crate::module::ModuleAnnotations; use crate::observability::metrics::MetricsCollector; use crate::policy::ExecutionPolicy; use crate::registry::registry::{ModuleDescriptor, Registry, DEFAULT_MODULE_VERSION}; -use crate::sys_modules::{SysModuleError, SysModulesContext, SysModulesStartup, ToggleState}; +#[cfg(feature = "sys-modules")] +use crate::sys_modules::SysModulesStartup; +use crate::sys_modules::{SysModuleError, SysModulesContext, ToggleState}; /// Options for [`APCore::try_start`] and [`APCore::try_with_options`]. #[derive(Default)] @@ -96,6 +98,19 @@ pub struct APCore { toggle_state: Arc, } +#[derive(Clone, Copy)] +enum Bootstrap<'a> { + InMemory, + Configured(Option<&'a SubscriberRegistry>), +} + +#[derive(Default)] +struct SystemAssembly { + context: Option, + errors: Vec, + emitter: Option>, +} + struct ClientShutdown { operation: LifecycleOperation, event_flush_timeout_ms: u32, @@ -130,9 +145,18 @@ impl Default for APCore { } impl APCore { - /// Create a new `APCore` client with default configuration. + /// Create a new `APCore` client with in-memory defaults. + /// + /// Use [`Self::with_config`] or [`Self::try_start`] for configured startup. pub fn new() -> Self { - Self::with_options(None, None, None, None) + Self::in_memory() + } + + /// Assemble a client from an empty registry and in-memory defaults. + /// File discovery and config-driven integrations are skipped during startup. + #[must_use] + pub fn in_memory() -> Self { + Self::build(APCoreOptions::default(), Bootstrap::InMemory) } /// Create a new `APCore` client with all optional parameters. @@ -154,13 +178,16 @@ impl APCore { config: Option, metrics_collector: Option, ) -> Self { - Self::build(APCoreOptions { - registry, - executor, - config, - metrics_collector, - ..Default::default() - }) + Self::build( + APCoreOptions { + registry, + executor, + config, + metrics_collector, + ..Default::default() + }, + Bootstrap::Configured(None), + ) } /// Create a client with explicit startup and governance options. @@ -177,7 +204,7 @@ impl APCore { /// error. Use [`Self::try_start`] to report it during construction. pub fn try_with_options(options: APCoreOptions) -> Result { let fail_on_error = options.fail_on_error; - let mut client = Self::build(options); + let mut client = Self::build(options, Bootstrap::Configured(None)); client.check_system_registration(fail_on_error)?; Ok(client) } @@ -187,8 +214,24 @@ impl APCore { /// Reports invalid pipeline or ACL configuration, and honours /// [`APCoreOptions::fail_on_error`] for system-module registration. pub fn try_start(options: APCoreOptions) -> Result { + Self::try_start_configured(options, None) + } + + /// Start this client with its own factories for configured event subscribers. + /// Reports the same startup errors as [`Self::try_start`]. + pub fn try_start_with_subscribers( + options: APCoreOptions, + subscribers: &SubscriberRegistry, + ) -> Result { + Self::try_start_configured(options, Some(subscribers)) + } + + fn try_start_configured( + options: APCoreOptions, + subscribers: Option<&SubscriberRegistry>, + ) -> Result { let fail_on_error = options.fail_on_error; - let mut client = Self::build(options); + let mut client = Self::build(options, Bootstrap::Configured(subscribers)); if let Some(source) = &client.executor.pipeline_load_error { return Err(APCoreStartupError::PipelineLoadFailed { source: source.clone(), @@ -210,7 +253,7 @@ impl APCore { Ok(()) } - fn build(options: APCoreOptions) -> Self { + fn build(options: APCoreOptions, bootstrap: Bootstrap<'_>) -> Self { let APCoreOptions { registry, executor, @@ -220,7 +263,17 @@ impl APCore { approval_handler, policy, } = options; - let config = config.unwrap_or_default(); + let (configured, subscribers) = match bootstrap { + Bootstrap::InMemory => (false, None), + Bootstrap::Configured(subscribers) => (true, subscribers), + }; + let config = config.unwrap_or_else(|| { + if configured { + Config::default() + } else { + Config::in_memory() + } + }); // Resolve the shared registry: use the executor's if provided, // otherwise the explicit `registry` arg, otherwise a fresh default. @@ -237,7 +290,9 @@ impl APCore { // explicit > config > default in their Registry constructors; this is the // Rust equivalent, placed here because `Registry::new()` takes no Config. // Roots already set explicitly are left alone (see the method's docs). - registry.set_extension_roots_from_config(&config); + if configured { + registry.set_extension_roots_from_config(&config); + } // Track whether the caller supplied their own Executor: if so, respect // its ACL wiring as-is and skip config-driven ACL discovery below. @@ -253,90 +308,29 @@ impl APCore { let toggle_state = executor.bind_client_toggle_state(executor_supplied); - // Config-driven ACL discovery (D-64, Recommendation A). Resolve - // `acl.root` and attach an ACL only when the path exists; a missing path - // is a no-op that preserves today's no-enforcement default (it must NOT - // synthesize an empty default-deny ACL). Wired before sys_modules - // registration so system modules execute under the discovered policy. - // A caller-supplied Executor is respected as-is and never overwritten. - if !executor_supplied { - match crate::acl::ACL::discover(&config) { - Ok(Some(acl)) => executor.set_acl(acl), - Ok(None) => {} - Err(e) => { - tracing::error!(error = %e, "ACL discovery failed; module execution is disabled"); - executor.acl_load_error = Some(e); - } - } - } - - // Config-driven tracing (PROTOCOL_SPEC §10.1.1). `observability.tracing.*` - // was five declared keys that reached nothing: no SDK had ever built a - // TracingMiddleware from configuration, so `enabled: true` installed - // nothing and the other four configured a middleware that did not exist. - // - // Skipped when the caller supplied their own Executor — an Executor the - // caller built is respected as-is, tracing included, exactly as - // config-driven ACL discovery above treats it. That is also what makes - // §10.1.1 requirement 6 hold without a second check: the Executor built - // here has an empty middleware chain, so configuration can never be the - // thing that adds a SECOND tracing middleware. - // - // A self-contradictory configuration (requirement 3) is logged rather - // than propagated, for the same reason `ACL::discover` above is: - // `APCore::with_options` returns `Self` and cannot carry an error. The - // middleware is not installed, so nothing runs under a configuration - // this constructor could not honour. - if !executor_supplied { - match crate::observability::tracing_config::build_tracing_middleware(&config) { - Ok(Some(mw)) => { - if let Err(e) = executor.use_middleware(Box::new(mw)) { - tracing::error!(error = %e, "Failed to install the configured tracing middleware"); - } - } - Ok(None) => {} - Err(e) => { - tracing::error!(error = %e, "observability.tracing.* is invalid; no tracing middleware was installed"); - } - } + if configured && !executor_supplied { + Self::apply_configured_acl(&mut executor, &config); + Self::apply_configured_tracing(&mut executor, &config); } - let mut startup = SysModulesStartup::default(); - let enable_sys_modules = executor.pipeline_load_error.is_none() + let system = if configured + && executor.pipeline_load_error.is_none() && executor.acl_load_error.is_none() - && Self::sys_modules_enabled(&config); - let sys_modules_context = if enable_sys_modules { - match crate::sys_modules::register_sys_modules_for_client( - Arc::clone(®istry), + && Self::sys_modules_enabled(&config) + { + Self::configure_system_modules( &executor, &config, - metrics_collector.clone(), - crate::sys_modules::SysModulesOptions { - toggle_state: Some(Arc::clone(&toggle_state)), - fail_on_error, - ..Default::default() - }, - &mut startup, + metrics_collector.as_ref(), + &toggle_state, + subscribers, + fail_on_error, executor_supplied, - ) { - Ok(ctx) => Some(ctx), - Err(e) => { - if !fail_on_error { - tracing::error!(error = %e, "System modules registration failed"); - } - startup.errors.push(e); - None - } - } + ) } else { - None + SystemAssembly::default() }; - let event_emitter = sys_modules_context - .as_ref() - .filter(|_| startup.events_enabled) - .map(|context| Arc::clone(&context.emitter)); - // Thread the shared event bus into the auto-created executor so the // pipeline publishes governance events (apcore#77: // `apcore.approval.decision` / `apcore.policy.override` / @@ -344,7 +338,7 @@ impl APCore { // caller-supplied executor keeps its own wiring (parity with ACL // discovery above). if !executor_supplied { - if let Some(ref emitter) = event_emitter { + if let Some(ref emitter) = system.emitter { executor.set_event_emitter(Some(Arc::clone(emitter))); } } @@ -353,15 +347,125 @@ impl APCore { config, executor: executor.into_shared(), registry, - event_emitter, + event_emitter: system.emitter, shutdown_operation: parking_lot::Mutex::new(None), metrics_collector, - sys_modules_context, - sys_modules_errors: startup.errors, + sys_modules_context: system.context, + sys_modules_errors: system.errors, toggle_state, } } + #[cfg(feature = "sys-modules")] + fn configure_system_modules( + executor: &Executor, + config: &Config, + metrics: Option<&MetricsCollector>, + toggle_state: &Arc, + subscribers: Option<&SubscriberRegistry>, + fail_on_error: bool, + executor_supplied: bool, + ) -> SystemAssembly { + let mut startup = SysModulesStartup { + subscribers, + ..Default::default() + }; + let context = match crate::sys_modules::register_sys_modules_for_client( + Arc::clone(&executor.registry), + executor, + config, + metrics.cloned(), + crate::sys_modules::SysModulesOptions { + toggle_state: Some(Arc::clone(toggle_state)), + fail_on_error, + ..Default::default() + }, + &mut startup, + executor_supplied, + ) { + Ok(context) => Some(context), + Err(error) => { + if !fail_on_error { + tracing::error!(%error, "System modules registration failed"); + } + startup.errors.push(error); + None + } + }; + let emitter = context + .as_ref() + .filter(|_| startup.events_enabled) + .map(|context| Arc::clone(&context.emitter)); + SystemAssembly { + context, + errors: startup.errors, + emitter, + } + } + + #[cfg(not(feature = "sys-modules"))] + fn configure_system_modules( + _executor: &Executor, + _config: &Config, + _metrics: Option<&MetricsCollector>, + _toggle_state: &Arc, + _subscribers: Option<&SubscriberRegistry>, + _fail_on_error: bool, + _executor_supplied: bool, + ) -> SystemAssembly { + SystemAssembly { + errors: vec![SysModuleError::RegistrationFailed { + module_id: "system".to_string(), + source: ModuleError::new( + crate::errors::ErrorCode::SysModulesDisabled, + "System-module configuration requires the 'sys-modules' feature", + ), + }], + ..SystemAssembly::default() + } + } + + #[cfg(feature = "config")] + fn apply_configured_acl(executor: &mut Executor, config: &Config) { + // Config discovery only wires ACLs backed by existing documents (D-64). + match crate::acl::ACL::discover(config) { + Ok(Some(acl)) => executor.set_acl(acl), + Ok(None) => {} + Err(e) => { + tracing::error!(error = %e, "ACL discovery failed; module execution is disabled"); + executor.acl_load_error = Some(e); + } + } + } + + #[cfg(not(feature = "config"))] + fn apply_configured_acl(executor: &mut Executor, config: &Config) { + if config + .get_declared("acl.root") + .is_some_and(|value| !value.is_null() && value.as_str() != Some("")) + { + executor.acl_load_error = Some(ModuleError::new( + crate::errors::ErrorCode::ConfigInvalid, + "ACL file configuration requires the 'config' feature", + )); + } + } + + fn apply_configured_tracing(executor: &mut Executor, config: &Config) { + // Apply configured tracing only to a client-created executor (§10.1.1). + match crate::observability::tracing_config::build_tracing_middleware(config) { + Ok(Some(mw)) => { + if let Err(e) = executor.use_middleware(Box::new(mw)) { + tracing::error!(error = %e, "Failed to install the configured tracing middleware"); + } + } + Ok(None) => {} + Err(e) => { + tracing::error!(error = %e, "observability.tracing.* is invalid; no tracing middleware was installed"); + } + } + } + /// System-module registration failures recovered during startup. #[must_use] pub fn sys_modules_errors(&self) -> &[SysModuleError] { @@ -406,6 +510,7 @@ impl APCore { } /// Create a new `APCore` client from a configuration file path. + #[cfg(feature = "config")] pub fn from_path(path: impl AsRef) -> Result { let config = Config::load(path.as_ref())?; let client = Self::with_config(config); @@ -999,22 +1104,6 @@ impl APCore { }) } - /// Deprecated: use [`on()`](Self::on) instead. - /// - /// `on_fn(event_type, callback)` was renamed to `on(event_type, callback)` in 0.19.0 - /// to align with the Python and TypeScript SDK naming convention. - #[deprecated( - since = "0.19.0", - note = "Renamed to `on()`. Use `client.on(event_type, callback)` instead." - )] - pub fn on_fn( - &mut self, - event_type: &str, - callback: impl Fn(&crate::events::emitter::ApCoreEvent) + Send + Sync + 'static, - ) -> Result { - self.on(event_type, callback) - } - /// Unsubscribe a single handler by its subscriber ID. /// /// The ID is the string returned by [`on()`](Self::on). Returns `true` if @@ -1074,6 +1163,7 @@ impl APCore { /// /// **Rust-only convenience** — Python and TypeScript expose config reload /// only on the Config object itself, not on the client facade. + #[cfg(feature = "config")] pub fn reload(&mut self) -> Result<(), ModuleError> { self.config.reload()?; Ok(()) @@ -1157,7 +1247,7 @@ impl APCore { } } -/// Internal subscriber that wraps a plain closure for [`APCore::on_fn()`]. +/// Internal subscriber that wraps a plain closure for [`APCore::on()`]. struct ClosureSubscriber { id: String, callback: Box, diff --git a/rust/src/config.rs b/rust/src/config.rs index 13ef3585..4f1c432b 100644 --- a/rust/src/config.rs +++ b/rust/src/config.rs @@ -4,6 +4,7 @@ use parking_lot::RwLock; use serde::de::{DeserializeOwned, Error as DeError}; use serde::{Deserialize, Deserializer, Serialize}; +#[cfg(feature = "config")] use serde_yaml_ng as serde_yaml; use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -23,6 +24,7 @@ pub enum ConfigMode { /// Source for a `config.mount()` operation. pub enum MountSource { Dict(serde_json::Value), + #[cfg(feature = "config")] File(PathBuf), } @@ -39,6 +41,7 @@ pub const DEFAULT_MAX_DEPTH: usize = 5; /// inside the **declared** document that [`Config::validate`]'s §9.1 /// required-field check reads through [`Config::get_declared`]. /// `discover_config_file` consumes it; both env-override passes drop it. +#[cfg(feature = "config")] const ENV_CONFIG_FILE: &str = "APCORE_CONFIG_FILE"; /// Environment variable key conversion strategy for a namespace. @@ -288,6 +291,7 @@ fn is_declared_prefix(path: &str) -> bool { } /// Return the canonical spelling of a known framework key, preserving user keys. +#[cfg(feature = "sys-modules")] pub(crate) fn canonical_config_key(key: &str) -> &str { key.strip_prefix("apcore.") .filter(|bare| is_declared_prefix(bare)) @@ -435,6 +439,7 @@ const PATH_TYPED_CONFIG_KEYS: &[&str] = &[ /// `acl.default_effect` joined in v1.47.0 as §9.1.3's first application: it is /// read from the ACL FILE, and the `apcore.yaml` twin reaches nothing. Ordered /// first because §9.2.4's table lists it first. +#[cfg(feature = "config")] const DEPRECATED_INERT_KEYS: &[&str] = &[ "acl.default_effect", "observability.metrics.enabled", @@ -760,13 +765,25 @@ pub struct Config { impl Default for Config { fn default() -> Self { + Self { + project_root_path: current_project_directory(), + ..Self::in_memory() + } + } +} + +impl Config { + /// Construct an in-memory configuration without consulting the host environment. + /// Its base for relative paths is the literal `.`. + #[must_use] + pub fn in_memory() -> Self { Self { modules_path: None, executor: ExecutorConfig::default(), observability: ObservabilityConfig::default(), user_namespaces: HashMap::new(), yaml_path: None, - project_root_path: current_project_directory(), + project_root_path: PathBuf::from("."), absolute_source_path: None, mode: ConfigMode::default(), generation: 0, @@ -1080,15 +1097,18 @@ fn apply_allow_unknown( impl Config { /// Load config from a JSON file, apply env overrides, and validate. + #[cfg(feature = "config")] pub fn from_json_file(path: &Path) -> Result { Self::load_file(path, true, None) } /// Load config from a YAML file, apply env overrides, and validate. + #[cfg(feature = "config")] pub fn from_yaml_file(path: &Path) -> Result { Self::load_file(path, false, None) } + #[cfg(feature = "config")] fn load_file( source: &Path, json: bool, @@ -1141,10 +1161,12 @@ impl Config { } /// Auto-detect format by file extension and load. + #[cfg(feature = "config")] pub fn load(path: &Path) -> Result { Self::load_with_root(path, None) } + #[cfg(feature = "config")] fn load_with_root(path: &Path, project_root: Option) -> Result { let json = path .extension() @@ -1162,6 +1184,7 @@ impl Config { /// separate method. This helper restores no-arg load parity for portable /// cross-language code without changing the strict-typed `load(&Path)` /// signature for callers that already know the path. + #[cfg(feature = "config")] pub fn load_or_discover() -> Result { Self::discover() } @@ -1624,6 +1647,7 @@ impl Config { /// Build config from defaults, applying env var overrides. #[must_use] + #[cfg(feature = "config")] pub fn from_defaults() -> Self { let mut config = Self::default(); config.detect_mode(); @@ -1641,7 +1665,7 @@ impl Config { /// Return the project root captured when this configuration was created (§9.2.2). /// Explicit and project-local files use their containing directory. User-level - /// discovery and in-memory configuration use the working directory at load time. + /// discovery uses the working directory at load time. [`Self::in_memory`] uses `.`. #[must_use] pub fn project_root(&self) -> PathBuf { self.project_root_path.clone() @@ -1678,6 +1702,7 @@ impl Config { /// validate, still answer `get()`, and are still accepted under /// `_config.strict`. This adds the one thing they have never had — a way for /// an operator to find out that setting them does nothing. + #[cfg(feature = "config")] fn warn_deprecated_inert_keys(&self) { // Read the AS-WRITTEN document, not `get_declared` and not `data()`. // `observability` is a typed struct field, so both of those always carry @@ -1747,6 +1772,7 @@ impl Config { /// Discover and load config using the §9.14 search order. /// /// If no file is found, returns `Config::from_defaults()`. + #[cfg(feature = "config")] pub fn discover() -> Result { match discover_config_file() { Some((path, project_root)) => Self::load_with_root(&path, project_root), @@ -2161,6 +2187,7 @@ impl Config { } /// Reload config from the stored `yaml_path`. Returns error if no path stored. + #[cfg(feature = "config")] pub fn reload(&mut self) -> Result<(), ModuleError> { let start_gen = self.generation; let path = self.yaml_path.clone().ok_or_else(|| { @@ -2225,6 +2252,7 @@ impl Config { /// Equivalent to [`Config::reload`] — kept as a separate method so the /// reload-module call site reads naturally and the spec terminology /// (`reload_from_disk`) stays first-class in the public API. + #[cfg(feature = "config")] pub fn reload_from_disk(&mut self) -> Result<(), ModuleError> { self.reload() } @@ -2392,8 +2420,10 @@ impl Config { "cannot mount to reserved namespace '_config'", )); } + #[cfg(feature = "config")] let data = match source { MountSource::Dict(v) => v, + #[cfg(feature = "config")] MountSource::File(path) => { let content = std::fs::read_to_string(&path) .map_err(|e| ModuleError::config_mount_error(namespace, &e.to_string()))?; @@ -2401,6 +2431,8 @@ impl Config { .map_err(|e| ModuleError::config_mount_error(namespace, &e.to_string()))? } }; + #[cfg(not(feature = "config"))] + let MountSource::Dict(data) = source; if !data.is_object() { return Err(ModuleError::config_mount_error( namespace, @@ -2494,6 +2526,7 @@ impl Config { // --- Private helpers --- + #[cfg(feature = "config")] fn detect_mode(&mut self) { // W-3: Only activate namespace mode when "apcore" key is a mapping. // A null or scalar value is not a valid namespace indicator. @@ -2508,6 +2541,7 @@ impl Config { /// In legacy mode, all `APCORE_*` vars are mapped via `env_key_to_dot_path`. /// In namespace mode, registered `env_prefix` values are dispatched via /// longest-prefix-match (§9.10). + #[cfg(feature = "config")] fn apply_env_overrides(&mut self) { if self.mode == ConfigMode::Namespace { self.apply_namespace_env_overrides(); @@ -2545,6 +2579,7 @@ impl Config { } /// §9.10: Namespace-aware env routing via longest-prefix-match. + #[cfg(feature = "config")] fn apply_namespace_env_overrides(&mut self) { let registry = global_ns_registry().read(); let gmap = global_env_map().read(); @@ -2658,6 +2693,7 @@ impl Config { /// Non-path-typed keys are untouched. An empty `APCORE_LOGGING_LEVEL` is a /// value the operator can mean, and §9.2.1's requirement is scoped to the /// closed path-typed set precisely because `""` is meaningless only there. + #[cfg(feature = "config")] fn apply_one_env_override(&mut self, env_key: &str, dot_path: &str, value: &str) { let path_typed = Self::is_path_typed_key(dot_path.strip_prefix("apcore.").unwrap_or(dot_path)); @@ -2869,11 +2905,13 @@ impl Config { /// Example: `EXECUTOR_MAX__CALL__DEPTH` → `executor.max_call_depth` /// /// So to set `max_call_depth` via env, use `APCORE_EXECUTOR_MAX__CALL__DEPTH`. + #[cfg(feature = "config")] fn env_key_to_dot_path(raw: &str) -> String { Self::env_key_to_dot_path_with_depth(raw, usize::MAX) } /// Convert env var suffix to dot-path, stopping at `max_depth` segments. + #[cfg(feature = "config")] fn env_key_to_dot_path_with_depth(raw: &str, max_depth: usize) -> String { let lower = raw.to_lowercase(); let chars: Vec = lower.chars().collect(); @@ -2902,6 +2940,7 @@ impl Config { } /// Try to match suffix against keys in a JSON object tree (recursive). + #[cfg(feature = "config")] fn match_suffix_to_tree( suffix: &str, tree: &serde_json::Map, @@ -2935,6 +2974,7 @@ impl Config { } /// Resolve an env var suffix based on the registration's `env_style`. + #[cfg(feature = "config")] fn resolve_env_suffix(suffix: &str, reg: &NamespaceRegistration) -> String { match reg.env_style { EnvStyle::Flat => suffix.to_lowercase(), @@ -2954,6 +2994,7 @@ impl Config { } } + #[cfg(feature = "config")] fn coerce_env_value(value: &str) -> serde_json::Value { if value.eq_ignore_ascii_case("true") { return serde_json::Value::Bool(true); @@ -2977,6 +3018,7 @@ impl Config { // Built-in namespace initialization (§9.15) // --------------------------------------------------------------------------- +#[cfg(feature = "config")] fn init_builtin_namespaces() { static INIT: OnceLock<()> = OnceLock::new(); INIT.get_or_init(|| { @@ -3073,6 +3115,7 @@ fn init_builtin_namespaces() { /// `$APCORE_CONFIG_FILE` is *consumed* here: both env-override passes skip it /// so it never becomes the `config.file` override (apcore#88). +#[cfg(feature = "config")] fn discover_config_file() -> Option<(PathBuf, Option)> { if let Ok(env_path) = std::env::var(ENV_CONFIG_FILE) { if !env_path.is_empty() { @@ -3100,6 +3143,7 @@ fn discover_config_file() -> Option<(PathBuf, Option)> { /// Tier 6 is the XDG-style path — `~/Library/Application Support/apcore/` on /// macOS, `~/.config/apcore/` elsewhere — and tier 7 the legacy `~/.apcore/`. /// +#[cfg(feature = "config")] fn user_level_config_candidates() -> Vec { let Some(home) = dirs_home() else { return Vec::new(); @@ -3118,9 +3162,15 @@ fn user_level_config_candidates() -> Vec { } fn current_project_directory() -> PathBuf { - std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")) + #[cfg(feature = "config")] + { + std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")) + } + #[cfg(not(feature = "config"))] + PathBuf::from(".") } +#[cfg(feature = "config")] fn dirs_home() -> Option { std::env::var("HOME").ok().map(std::path::PathBuf::from) } @@ -3146,7 +3196,7 @@ fn deep_merge_value(base: &mut serde_json::Value, overlay: &serde_json::Value) { } } -#[cfg(test)] +#[cfg(all(test, feature = "config"))] mod tests { use super::*; diff --git a/rust/src/context.rs b/rust/src/context.rs index 10c393b2..85746603 100644 --- a/rust/src/context.rs +++ b/rust/src/context.rs @@ -9,7 +9,6 @@ use parking_lot::RwLock; use std::sync::Arc; use crate::cancel::CancelToken; -use crate::observability::logging::ContextLogger; use crate::trace_context::TraceParent; const TRACE_ID_ZEROS: &str = "00000000000000000000000000000000"; @@ -457,44 +456,6 @@ impl Context { }) } - /// Get a context-scoped logger. - /// - /// # Deprecated - /// - /// Use the host application's logger (apcore#121). Removed at v2.0. - /// - /// Application and module code SHOULD log through the logger the host - /// application has already configured — `tracing`, `log`, or whatever the - /// binary installed. To emit automatic apcore execution events instead, - /// install `ObsLoggingMiddleware` explicitly: that is a different facility, - /// not a drop-in replacement for ad-hoc logging. - /// - /// This method has no configuration door and cannot acquire one without - /// paying for it somewhere the framework should not. Its logger is built - /// per call from a [`Context`], which carries no `Config` in any SDK, and - /// the only route that avoids threading one through `Context`'s pinned - /// six-parameter contract is a process-global logger — which would end the - /// multi-instance isolation apcore currently gets for free. So the output - /// is fixed at stderr / `info` / JSON, bypassing whatever the host has - /// configured, and notably NOT going through `tracing`. Per PROTOCOL_SPEC - /// §9.2.4's D-67 boundary, apcore does not own the host's logging policy. - #[deprecated( - since = "0.31.0", - note = "use the host application's logger; its output is under the host's control and \ - this one's is not (always stderr, info, JSON, bypassing `tracing`). To emit \ - automatic apcore execution events, install ObsLoggingMiddleware explicitly. \ - See apcore#121. Removed at v2.0." - )] - pub fn logger(&self) -> ContextLogger { - let module_id = self.call_chain.last().cloned(); - let caller_id = self.caller_id.clone(); - let mut logger = ContextLogger::new("apcore"); - logger.trace_id = Some(self.trace_id.clone()); - logger.module_id = module_id; - logger.caller_id = caller_id; - logger - } - /// Create a context from the canonical caller-supplied inputs. /// /// Unified factory signature per apcore Issue #66 / `core-executor.md` diff --git a/rust/src/events/circuit_breaker.rs b/rust/src/events/circuit_breaker.rs index 3ebbbdcc..be505303 100644 --- a/rust/src/events/circuit_breaker.rs +++ b/rust/src/events/circuit_breaker.rs @@ -394,7 +394,7 @@ impl EventSubscriber for CircuitBreakerWrapper { /// /// We don't have access to the concrete generic type name at runtime, but the /// `subscriber_id` carries a deterministic prefix for built-in types -/// (`webhook-…`, `a2a-…`, `file-…`, `stdout-…`, `filter-…`). Use that prefix +/// (`webhook-…`, `file-…`, `stdout-…`, `filter-…`). Use that prefix /// when present; otherwise fall back to the literal id. /// The DECLARED subscriber kind, the same value the DLQ path reports (D-116). /// diff --git a/rust/src/events/emitter.rs b/rust/src/events/emitter.rs index 8eb3fa8f..aa937f3d 100644 --- a/rust/src/events/emitter.rs +++ b/rust/src/events/emitter.rs @@ -653,7 +653,7 @@ impl EventEmitter { /// `matches_pattern` here would have it also fire on /// `apcore.acl.rule_matched`. /// - /// Every other subscriber (`WebhookSubscriber`, `A2ASubscriber`, a bare + /// Every other subscriber (`WebhookSubscriber`, a bare /// `EventSubscriber` impl, the DLQ's own `"*"` catch-all) reports `None` /// from `event_type_filter()` and keeps this crate's `*`-wildcard glob /// semantics via `event_pattern()` + [`Self::matches_pattern`] — those diff --git a/rust/src/events/mod.rs b/rust/src/events/mod.rs index 15f3b9eb..08443151 100644 --- a/rust/src/events/mod.rs +++ b/rust/src/events/mod.rs @@ -12,8 +12,9 @@ pub use circuit_breaker::{ }; pub use emitter::{ApCoreEvent, EventEmitter}; pub use retry::EventRetryConfig; +#[cfg(feature = "events-file")] +pub use subscribers::FileSubscriber; pub use subscribers::{ - create_subscriber, register_subscriber_type, reset_subscriber_registry, - unregister_subscriber_type, EventSubscriber, FileSubscriber, FilterSubscriber, OutputFormat, - StdoutSubscriber, WebhookSubscriber, + create_subscriber, EventSubscriber, FilterSubscriber, OutputFormat, StdoutSubscriber, + WebhookSubscriber, }; diff --git a/rust/src/events/subscribers.rs b/rust/src/events/subscribers.rs index 389f9383..7edcc111 100644 --- a/rust/src/events/subscribers.rs +++ b/rust/src/events/subscribers.rs @@ -1,14 +1,15 @@ // APCore Protocol — Event subscribers -// Spec reference: Event subscription, webhook delivery, A2A delivery +// Spec reference: Event subscription and Webhook delivery -use parking_lot::RwLock; use std::collections::HashMap; +#[cfg(feature = "events-file")] use std::path::PathBuf; +use std::sync::Arc; +#[cfg(feature = "events")] use std::sync::OnceLock; use async_trait::async_trait; -#[cfg(feature = "events")] -use serde_json::json; +#[cfg(feature = "events-file")] use tokio::io::AsyncWriteExt; use super::emitter::ApCoreEvent; @@ -31,7 +32,7 @@ fn next_subscriber_id(type_name: &str) -> String { format!("{type_name}-{current}") } -/// Process-wide shared `reqwest::Client` for webhook / A2A delivery. +/// Process-wide shared `reqwest::Client` for Webhook delivery. /// /// Constructing a `reqwest::Client` is expensive and, on macOS, can perform a /// blocking SystemConfiguration proxy lookup (`SCDynamicStoreCopyProxies`). @@ -305,166 +306,6 @@ impl EventSubscriber for WebhookSubscriber { } } -// --------------------------------------------------------------------------- -// A2ASubscriber -// --------------------------------------------------------------------------- - -/// Authentication for A2A subscriber. -#[derive(Debug, Clone)] -pub enum A2AAuth { - /// Bearer token → `Authorization: Bearer `. - Bearer(String), - /// Dict of headers to merge into the request. - Headers(HashMap), -} - -/// Delivers events via the A2A protocol to the platform. -/// -/// Payload: `{ "skillId": "", "event": }`. -/// The `skill_id` field defaults to `"apevo.event_receiver"` and can be -/// overridden per-subscriber. -/// -/// Delivery contract (spec docs/features/event-system.md §Event Delivery -/// Semantics, Issue #61): `on_event` performs a **single** HTTP attempt and -/// returns `Err(ModuleError)` on 5xx or network errors so that the -/// surrounding [`EventEmitter`](super::EventEmitter) retry+DLQ policy -/// (configured via `retry`) applies uniformly across subscriber types. -/// 4xx responses are non-retryable client errors — they are logged at WARN -/// and reported as `Ok` to suppress the spec retry loop. -#[derive(Debug, Clone)] -pub struct A2ASubscriber { - pub id: String, - pub platform_url: String, - pub auth: Option, - pub event_pattern: String, - pub timeout_ms: u64, - /// The A2A skill ID included in the outgoing payload. - /// Default: `"apevo.event_receiver"` (per apcore A2A spec). - pub skill_id: String, - /// Retry policy applied by [`EventEmitter`](super::EventEmitter) — see - /// event-system.md §Delivery Semantics. - pub retry: crate::events::retry::EventRetryConfig, -} - -impl A2ASubscriber { - pub fn new( - id: impl Into, - platform_url: impl Into, - event_pattern: impl Into, - ) -> Self { - Self { - id: id.into(), - platform_url: platform_url.into(), - auth: None, - event_pattern: event_pattern.into(), - timeout_ms: 5000, - skill_id: "apevo.event_receiver".to_string(), - retry: crate::events::retry::EventRetryConfig::default(), - } - } - - /// Override the A2A skill ID used in the outgoing payload. - #[must_use] - pub fn with_skill_id(mut self, skill_id: impl Into) -> Self { - self.skill_id = skill_id.into(); - self - } - - /// Override the retry policy applied by [`EventEmitter`](super::EventEmitter). - #[must_use] - pub fn with_retry(mut self, retry: crate::events::retry::EventRetryConfig) -> Self { - self.retry = retry; - self - } -} - -#[async_trait] -impl EventSubscriber for A2ASubscriber { - fn subscriber_id(&self) -> &str { - &self.id - } - - #[allow(clippy::unnecessary_literal_bound)] // Keep the EventSubscriber borrowed-string signature. - fn subscriber_type(&self) -> &str { - "a2a" - } - - fn event_pattern(&self) -> &str { - &self.event_pattern - } - - fn retry(&self) -> crate::events::retry::EventRetryConfig { - self.retry - } - - #[cfg(feature = "events")] - async fn on_event(&self, event: &ApCoreEvent) -> Result<(), ModuleError> { - let payload = json!({ - "skillId": self.skill_id, - "event": { - "event_type": event.event_type, - "module_id": event.module_id, - "timestamp": event.timestamp, - "severity": event.severity, - "data": event.data, - } - }); - - let client = shared_http_client()?; - - let mut req = client - .post(&self.platform_url) - .timeout(std::time::Duration::from_millis(self.timeout_ms)) - .json(&payload); - req = req.header("Content-Type", "application/json"); - match &self.auth { - Some(A2AAuth::Bearer(token)) => { - req = req.header("Authorization", format!("Bearer {token}")); - } - Some(A2AAuth::Headers(headers)) => { - for (k, v) in headers { - req = req.header(k.as_str(), v.as_str()); - } - } - None => {} - } - - match req.send().await { - Ok(resp) => { - let status = resp.status().as_u16(); - if (200..300).contains(&status) { - return Ok(()); - } - if status < 500 { - // 4xx is a non-retryable client error per the spec retry - // table — log and report success so EventEmitter does not - // retry. (A-D-EVT-001.) - tracing::warn!(status, url = %self.platform_url, "A2ASubscriber: non-retryable 4xx"); - return Ok(()); - } - // 5xx — bubble up so EventEmitter::deliver_with_dlq applies - // the per-subscriber retry policy + DLQ on exhaustion. - Err(ModuleError::new( - ErrorCode::GeneralInternalError, - format!("A2ASubscriber: HTTP {status} from {}", self.platform_url), - )) - } - Err(e) => Err(ModuleError::new( - ErrorCode::GeneralInternalError, - format!("A2ASubscriber: network error to {}: {e}", self.platform_url), - )), - } - } - - #[cfg(not(feature = "events"))] - async fn on_event(&self, _event: &ApCoreEvent) -> Result<(), ModuleError> { - Err(ModuleError::new( - ErrorCode::GeneralInternalError, - "A2ASubscriber requires the 'events' feature", - )) - } -} - // --------------------------------------------------------------------------- // FileSubscriber — built-in `file` type // --------------------------------------------------------------------------- @@ -493,6 +334,7 @@ impl OutputFormat { /// limit at write time, the current file is renamed to `.1` before the /// next write — matching the Python `FileSubscriber` behaviour. #[derive(Debug, Clone)] +#[cfg(feature = "events-file")] pub struct FileSubscriber { pub id: String, pub path: PathBuf, @@ -505,6 +347,7 @@ pub struct FileSubscriber { pub retry: crate::events::retry::EventRetryConfig, } +#[cfg(feature = "events-file")] impl FileSubscriber { #[must_use] pub fn new(path: impl Into) -> Self { @@ -571,6 +414,7 @@ impl FileSubscriber { } } +#[cfg(feature = "events-file")] #[async_trait] impl EventSubscriber for FileSubscriber { fn subscriber_id(&self) -> &str { @@ -882,9 +726,6 @@ impl EventSubscriber for FilterSubscriber { // Subscriber factory — config-driven instantiation // --------------------------------------------------------------------------- -type SubscriberFactory = - Box Result, ModuleError> + Send + Sync>; - /// Parse a subscriber's nested `retry:` block into an [`EventRetryConfig`]. /// /// Implements the per-subscriber retry policy documented in @@ -971,44 +812,7 @@ fn build_webhook_subscriber( } #[allow(clippy::result_large_err)] // The subscriber factory returns the protocol ModuleError. -fn build_a2a_subscriber( - config: &serde_json::Value, -) -> Result, ModuleError> { - let platform_url = config - .get("platform_url") - .and_then(|v| v.as_str()) - .ok_or_else(|| { - ModuleError::new(ErrorCode::ConfigInvalid, "a2a: 'platform_url' is required") - })? - .to_string(); - let timeout_ms = config - .get("timeout_ms") - .and_then(serde_json::Value::as_u64) - .unwrap_or(5000); - let auth = match config.get("auth") { - Some(serde_json::Value::String(s)) => Some(A2AAuth::Bearer(s.clone())), - Some(serde_json::Value::Object(m)) => { - let mut headers = HashMap::new(); - for (k, v) in m { - if let Some(vs) = v.as_str() { - headers.insert(k.clone(), vs.to_string()); - } - } - Some(A2AAuth::Headers(headers)) - } - _ => None, - }; - let id = next_subscriber_id("a2a"); - let mut sub = A2ASubscriber::new(id, platform_url, "*"); - sub.auth = auth; - sub.timeout_ms = timeout_ms; - if let Some(retry) = parse_retry_config(config) { - sub.retry = retry; - } - Ok(Box::new(sub) as Box) -} - -#[allow(clippy::result_large_err)] // The subscriber factory returns the protocol ModuleError. +#[cfg(feature = "events-file")] fn build_file_subscriber( config: &serde_json::Value, ) -> Result, ModuleError> { @@ -1059,6 +863,7 @@ fn build_stdout_subscriber( #[allow(clippy::result_large_err)] // The subscriber factory returns the protocol ModuleError. fn build_filter_subscriber( + registry: &SubscriberRegistry, config: &serde_json::Value, ) -> Result, ModuleError> { let delegate_type = config @@ -1086,7 +891,7 @@ fn build_filter_subscriber( "filter: 'delegate_config' must be an object", )); } - let delegate = create_subscriber(&delegate_config)?; + let delegate = registry.create(&delegate_config)?; let include = config .get("include_events") @@ -1118,80 +923,93 @@ fn build_filter_subscriber( Ok(Box::new(sub) as Box) } -/// Register the built-in subscriber type factories -/// (`webhook`, `a2a`, `file`, `stdout`, `filter`). -fn register_builtin_factories(map: &mut HashMap) { - map.insert("webhook".to_string(), Box::new(build_webhook_subscriber)); - map.insert("a2a".to_string(), Box::new(build_a2a_subscriber)); - map.insert("file".to_string(), Box::new(build_file_subscriber)); - map.insert("stdout".to_string(), Box::new(build_stdout_subscriber)); - map.insert("filter".to_string(), Box::new(build_filter_subscriber)); -} +type RegistryFactory = Arc< + dyn Fn(&SubscriberRegistry, &serde_json::Value) -> Result, ModuleError> + + Send + + Sync, +>; -fn global_subscriber_factories() -> &'static RwLock> { - static FACTORIES: OnceLock>> = OnceLock::new(); - FACTORIES.get_or_init(|| { - let mut map: HashMap = HashMap::new(); - register_builtin_factories(&mut map); - RwLock::new(map) - }) +/// Subscriber factories selected by a single host assembly. +#[derive(Clone)] +pub struct SubscriberRegistry { + factories: HashMap, } -/// Register a custom subscriber type factory. -pub fn register_subscriber_type(type_name: &str, factory: SubscriberFactory) { - let mut map = global_subscriber_factories().write(); - map.insert(type_name.to_string(), factory); -} +impl SubscriberRegistry { + /// Construct a registry with the protocol-neutral subscriber factories. + #[must_use] + pub fn new() -> Self { + let mut registry = Self { + factories: HashMap::new(), + }; + registry.register("webhook", build_webhook_subscriber); + #[cfg(feature = "events-file")] + registry.register("file", build_file_subscriber); + registry.register("stdout", build_stdout_subscriber); + registry + .factories + .insert("filter".to_string(), Arc::new(build_filter_subscriber)); + registry + } + + /// Add or replace the named factory for this registry. + pub fn register(&mut self, type_name: &str, factory: F) + where + F: Fn(&serde_json::Value) -> Result, ModuleError> + + Send + + Sync + + 'static, + { + self.factories.insert( + type_name.to_string(), + Arc::new(move |_, config| factory(config)), + ); + } -/// Unregister a subscriber type. -pub fn unregister_subscriber_type(type_name: &str) -> Result<(), ModuleError> { - let mut map = global_subscriber_factories().write(); - if map.remove(type_name).is_none() { - return Err(ModuleError::new( - ErrorCode::GeneralInternalError, - format!("Subscriber type '{type_name}' is not registered"), - )); + /// Remove the named factory from this registry. + #[must_use] + pub fn unregister(&mut self, type_name: &str) -> bool { + self.factories.remove(type_name).is_some() + } + + /// Create a subscriber and resolve any nested delegates from this registry. + pub fn create( + &self, + config: &serde_json::Value, + ) -> Result, ModuleError> { + let type_name = config.get("type").and_then(|v| v.as_str()).ok_or_else(|| { + ModuleError::new( + ErrorCode::ConfigInvalid, + "subscriber config missing 'type' field", + ) + })?; + let factory = self.factories.get(type_name).ok_or_else(|| { + ModuleError::new( + ErrorCode::ConfigInvalid, + format!("Unknown subscriber type '{type_name}'"), + ) + })?; + factory(self, config) } - Ok(()) } -/// Reset the subscriber factory registry to built-in types only. -pub fn reset_subscriber_registry() { - let mut map = global_subscriber_factories().write(); - map.clear(); - register_builtin_factories(&mut map); +impl Default for SubscriberRegistry { + fn default() -> Self { + Self::new() + } } -/// Create a subscriber from config using the factory registry. +/// Create a subscriber from the protocol-neutral built-ins. pub fn create_subscriber( config: &serde_json::Value, ) -> Result, ModuleError> { - let type_name = config.get("type").and_then(|v| v.as_str()).ok_or_else(|| { - ModuleError::new( - ErrorCode::ConfigInvalid, - "subscriber config missing 'type' field", - ) - })?; - - let map = global_subscriber_factories().read(); - let factory = map.get(type_name).ok_or_else(|| { - ModuleError::new( - ErrorCode::ConfigInvalid, - format!("Unknown subscriber type '{type_name}'"), - ) - })?; - factory(config) + SubscriberRegistry::new().create(config) } #[cfg(test)] mod tests { use super::*; use serde_json::json; - use std::sync::Mutex; - - /// Tests that call `reset_subscriber_registry` or mutate the global - /// subscriber registry must hold this lock to avoid cross-test races. - static REGISTRY_LOCK: Mutex<()> = Mutex::new(()); #[test] fn test_webhook_subscriber_new() { @@ -1211,43 +1029,6 @@ mod tests { assert_eq!(sub.event_pattern(), "*"); } - #[test] - fn test_a2a_subscriber_new() { - let sub = A2ASubscriber::new("a2a1", "https://platform.example.com", "module.*"); - assert_eq!(sub.id, "a2a1"); - assert_eq!(sub.platform_url, "https://platform.example.com"); - assert_eq!(sub.event_pattern, "module.*"); - assert!(sub.auth.is_none()); - assert_eq!(sub.timeout_ms, 5000); - } - - #[test] - fn test_a2a_subscriber_trait_methods() { - let sub = A2ASubscriber::new("a2a1", "https://p.com", "ev.*"); - assert_eq!(sub.subscriber_id(), "a2a1"); - assert_eq!(sub.event_pattern(), "ev.*"); - } - - #[test] - fn test_a2a_auth_bearer() { - let auth = A2AAuth::Bearer("my_token".to_string()); - match auth { - A2AAuth::Bearer(t) => assert_eq!(t, "my_token"), - A2AAuth::Headers(_) => panic!("expected Bearer"), - } - } - - #[test] - fn test_a2a_auth_headers() { - let mut headers = HashMap::new(); - headers.insert("X-Custom".to_string(), "value".to_string()); - let auth = A2AAuth::Headers(headers); - match auth { - A2AAuth::Headers(h) => assert_eq!(h.get("X-Custom").unwrap(), "value"), - A2AAuth::Bearer(_) => panic!("expected Headers"), - } - } - #[cfg(not(feature = "events"))] #[tokio::test] async fn test_webhook_on_event_requires_events_feature() { @@ -1259,17 +1040,6 @@ mod tests { assert_eq!(result.unwrap_err().code, ErrorCode::GeneralInternalError); } - #[cfg(not(feature = "events"))] - #[tokio::test] - async fn test_a2a_on_event_requires_events_feature() { - use super::super::emitter::ApCoreEvent; - let sub = A2ASubscriber::new("a1", "https://p.com", "*"); - let event = ApCoreEvent::new("test", json!({})); - let result = sub.on_event(&event).await; - assert!(result.is_err()); - assert_eq!(result.unwrap_err().code, ErrorCode::GeneralInternalError); - } - #[test] fn test_create_subscriber_missing_type_field() { let config = json!({"url": "https://example.com"}); @@ -1282,8 +1052,6 @@ mod tests { #[test] fn test_create_subscriber_unknown_type() { - let _lock = REGISTRY_LOCK.lock().unwrap(); - reset_subscriber_registry(); let config = json!({"type": "nonexistent"}); let result = create_subscriber(&config); assert!(result.is_err()); @@ -1292,8 +1060,6 @@ mod tests { #[test] fn test_create_webhook_subscriber_via_factory() { - let _lock = REGISTRY_LOCK.lock().unwrap(); - reset_subscriber_registry(); let config = json!({ "type": "webhook", "url": "https://example.com/hook", @@ -1308,39 +1074,12 @@ mod tests { #[test] fn test_create_webhook_subscriber_missing_url() { - let _lock = REGISTRY_LOCK.lock().unwrap(); - reset_subscriber_registry(); let config = json!({"type": "webhook"}); let result = create_subscriber(&config); assert!(result.is_err()); assert!(result.unwrap_err().message.contains("url")); } - #[test] - fn test_create_a2a_subscriber_via_factory() { - let _lock = REGISTRY_LOCK.lock().unwrap(); - reset_subscriber_registry(); - let config = json!({ - "type": "a2a", - "platform_url": "https://platform.example.com", - "timeout_ms": 2000, - "auth": "my_bearer_token" - }); - let sub = create_subscriber(&config).unwrap(); - assert!(sub.subscriber_id().starts_with("a2a-")); - assert_eq!(sub.event_pattern(), "*"); - } - - #[test] - fn test_create_a2a_subscriber_missing_platform_url() { - let _lock = REGISTRY_LOCK.lock().unwrap(); - reset_subscriber_registry(); - let config = json!({"type": "a2a"}); - let result = create_subscriber(&config); - assert!(result.is_err()); - assert!(result.unwrap_err().message.contains("platform_url")); - } - #[test] fn test_register_and_unregister_custom_subscriber_type() { #[derive(Debug)] @@ -1362,39 +1101,20 @@ mod tests { } } - let _lock = REGISTRY_LOCK.lock().unwrap(); let type_name = "custom_unique_test_type"; - register_subscriber_type( - type_name, - Box::new(|_config| Ok(Box::new(CustomSub) as Box)), - ); + let mut registry = SubscriberRegistry::new(); + registry.register(type_name, |_| { + Ok(Box::new(CustomSub) as Box) + }); let config = json!({"type": type_name}); - let sub = create_subscriber(&config).unwrap(); + assert!(SubscriberRegistry::new().create(&config).is_err()); + let sub = registry.create(&config).unwrap(); assert_eq!(sub.subscriber_id(), "custom-1"); - unregister_subscriber_type(type_name).unwrap(); - let result = create_subscriber(&config); - assert!(result.is_err()); - } - - #[test] - fn test_unregister_nonexistent_type_returns_error() { - let _lock = REGISTRY_LOCK.lock().unwrap(); - reset_subscriber_registry(); - let result = unregister_subscriber_type("does_not_exist"); - assert!(result.is_err()); - } - - #[test] - fn test_reset_subscriber_registry_restores_builtins() { - let _lock = REGISTRY_LOCK.lock().unwrap(); - reset_subscriber_registry(); - let wh_config = json!({"type": "webhook", "url": "https://example.com"}); - assert!(create_subscriber(&wh_config).is_ok()); - - let a2a_config = json!({"type": "a2a", "platform_url": "https://p.com"}); - assert!(create_subscriber(&a2a_config).is_ok()); + assert!(registry.unregister(type_name)); + assert!(!registry.unregister(type_name)); + assert!(registry.create(&config).is_err()); } } diff --git a/rust/src/executor.rs b/rust/src/executor.rs index be62b2ec..2b68fb9a 100644 --- a/rust/src/executor.rs +++ b/rust/src/executor.rs @@ -754,7 +754,7 @@ pub struct GovernanceState { pub approval_handler_configured: bool, /// The running strategy contains the built-in approval gate, matched by capability. pub builtin_approval_gate_wired: bool, - /// An `ExecutionPolicy` with `strict = true` is attached. + /// The effective policy uses strict approval enforcement. pub policy_strict: bool, /// Every registered `system.control.*` module declares `requires_approval`. /// @@ -1191,7 +1191,7 @@ impl Executor { /// Step-5 approval gate (apcore#76 RFC pilot). Mirrors /// [`Self::set_approval_handler`]; the policy flows to the gate via /// `PipelineContext` at each invocation, so this takes effect immediately - /// for subsequent calls. Pass `None` to remove the policy. + /// for subsequent calls. Pass `None` to restore the default policy. pub fn set_policy(&mut self, policy: Option) { self.policy = policy.map(Arc::new); } @@ -1558,19 +1558,11 @@ impl Executor { .as_ref(), pipe_ctx.declared_module_annotations().as_ref(), ); - let policy_effective_approval = if let Some(policy) = self.policy.as_ref() { - // §7.9.6: preflight resolves through the same call-site-aware entry - // point the Step-5 gate uses, so the two cannot report different - // verdicts. The built-in rules ignore the call site (§7.9.6 rule 2), - // so this is identical to `resolve()` for any rule-based policy. - policy - .resolve_with_call_site(module_id, module_annotations.as_ref(), Some(inputs), ctx) - .needs_approval - } else { - module_annotations - .as_ref() - .is_some_and(|a| a.requires_approval) - }; + // Resolve preflight through the same default and call-site-aware + // policy entry point as the Step-5 gate (§7.9.6). + let policy_effective_approval = ExecutionPolicy::effective(self.policy.as_deref()) + .resolve_with_call_site(module_id, module_annotations.as_ref(), Some(inputs), ctx) + .needs_approval; // PROTOCOL_SPEC §7.9.5: report the GOVERNANCE-effective requirement — // the union of §6.9 rows 3-5 for this call site — not merely the // policy-effective one. Since v1.28.0 that union includes an ACL rule @@ -2297,8 +2289,8 @@ impl Executor { /// ACL requirements are evaluated during each invocation. #[must_use] pub fn ungated_approval_modules(&self) -> Vec { - let enforcing_gate = (self.approval_handler.is_some() - || self.policy.as_ref().is_some_and(|policy| policy.strict)) + let policy = ExecutionPolicy::effective(self.policy.as_deref()); + let enforcing_gate = (self.approval_handler.is_some() || policy.strict) && self .strategy .steps() @@ -2312,11 +2304,9 @@ impl Executor { let Some(annotations) = self.registry.governance_annotations(id) else { return false; }; - annotations.requires_approval - && !(enforcing_gate - && self.policy.as_ref().is_none_or(|policy| { - policy.resolve(id, Some(&annotations)).needs_approval - })) + let needs_approval = policy.resolve(id, Some(&annotations)).needs_approval; + (annotations.requires_approval || needs_approval) + && !(enforcing_gate && needs_approval) }) .collect() } @@ -2387,7 +2377,7 @@ impl Executor { // cannot drift from the gate. let acl_configured = self.acl.is_some(); let approval_handler_configured = self.approval_handler.is_some(); - let policy_strict = self.policy.as_ref().is_some_and(|p| p.strict); + let policy_strict = ExecutionPolicy::effective(self.policy.as_deref()).strict; // PROTOCOL_SPEC 6.6.5.1. The approval conjunct carries // `all_control_modules_require_approval` because `approval_gate` is @@ -2426,17 +2416,6 @@ impl Executor { self.strategy.info() } - /// Register a strategy's info in the global registry for introspection. - /// - /// Delegates to the module-level [`register_strategy`] function. - #[deprecated( - since = "0.20.0", - note = "Use the module-level `register_strategy` function directly." - )] - pub fn register_strategy(info: StrategyInfo) { - register_strategy(info); - } - /// Strategy summaries for this executor: its current strategy first, then /// every strategy registered via [`register_strategy`]. /// @@ -2521,6 +2500,7 @@ impl Executor { .await } + #[cfg(feature = "sys-modules")] pub(crate) fn set_runtime_config(&self, config: Arc>) { *self.runtime_config.write() = Some(Arc::new(RuntimeConfig { source: config, @@ -3374,7 +3354,7 @@ mod tests { } #[tokio::test] - async fn test_approval_token_stripped_when_no_handler_configured() { + async fn test_approval_token_stripped_when_nonstrict_and_no_handler_configured() { // PROTOCOL_SPEC §7.4 is unconditional: `_approval_token` MUST be // removed from the arguments before they reach a subsequent step. The // no-handler skip returns from Step 5 early, so the token used to @@ -3387,7 +3367,8 @@ mod tests { requires_approval: true, ..Default::default() }; - let executor = build_executor_with_module(module, annotations); + let mut executor = build_executor_with_module(module, annotations); + executor.set_policy(Some(ExecutionPolicy::default().with_strict(false))); let result = executor .call( diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 08d553ce..8dae8533 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -65,9 +65,10 @@ pub use async_task::{ AsyncTaskManager, InMemoryTaskStore, ReaperConfig, ReaperHandle, RetryConfig as AsyncRetryConfig, TaskInfo, TaskStatus, TaskStore, }; +#[cfg(feature = "config")] +pub use bindings::BindingLoader; pub use bindings::{ - typed_handler, AutoSchemaValue, BindingEntry, BindingHandler, BindingLoader, BindingsFile, - TypedBindingHandler, + typed_handler, AutoSchemaValue, BindingEntry, BindingHandler, BindingsFile, TypedBindingHandler, }; pub use builtin_steps::{ build_internal_strategy, build_minimal_strategy, build_performance_strategy, @@ -100,10 +101,11 @@ pub use events::circuit_breaker::{ }; pub use events::emitter::{ApCoreEvent, EventEmitter}; pub use events::retry::EventRetryConfig; +#[cfg(feature = "events-file")] +pub use events::subscribers::FileSubscriber; pub use events::subscribers::{ - create_subscriber, register_subscriber_type, reset_subscriber_registry, - unregister_subscriber_type, A2ASubscriber, EventSubscriber, FileSubscriber, FilterSubscriber, - OutputFormat, StdoutSubscriber, WebhookSubscriber, + create_subscriber, EventSubscriber, FilterSubscriber, OutputFormat, StdoutSubscriber, + SubscriberRegistry, WebhookSubscriber, }; pub use executor::{ list_strategies, redact_sensitive, register_strategy, Executor, GovernanceState, REDACTED_VALUE, @@ -144,7 +146,6 @@ pub use observability::processor::{ BatchSpanProcessor, BatchSpanProcessorBuilder, BatchSpanProcessorConfig, SimpleSpanProcessor, SpanProcessor, }; -pub use observability::prometheus_exporter::PrometheusExporter; pub use observability::redaction::{RedactionConfig, RedactionConfigBuilder, RedactionConfigError}; pub use observability::render_prometheus_metrics; pub use observability::span::{Span, SpanExporter}; @@ -171,27 +172,35 @@ pub use registry::registry::{ }; pub use registry::{ class_name_to_segment, compute_base_id, derive_module_ids, detect_id_conflicts, ConflictResult, - ConflictSeverity, ConflictType, DefaultDiscoverer, DiscoveredClass, DiscoveryConfig, - ModuleFactory, MultiClassEntry, MAX_MODULE_ID_LEN, + ConflictSeverity, ConflictType, DiscoveredClass, DiscoveryConfig, MultiClassEntry, + MAX_MODULE_ID_LEN, }; +#[cfg(feature = "discovery")] +pub use registry::{DefaultDiscoverer, ModuleFactory}; pub use schema::{ - assert_openai_strict_compatible, detect_openai_strict_incompatibilities, to_strict_schema, - ExportProfile, RefResolver, SchemaDefinition, SchemaExporter, SchemaLoader, SchemaStrategy, - SchemaValidator, + assert_openai_strict_compatible, detect_openai_strict_incompatibilities, export_generic, + to_strict_schema, SchemaDefinition, SchemaValidator, }; +#[cfg(feature = "config")] +pub use schema::{RefResolver, SchemaLoader, SchemaStrategy}; pub use stream_completion::{ StreamChunks, StreamCompletion, StreamCompletionHandle, StreamEndReason, StreamFailureDisposition, StreamSkipReason, StreamStepOutcome, }; +#[cfg(feature = "sys-modules")] pub use sys_modules::control::UpdateConfigModule; +#[cfg(feature = "sys-modules")] pub use sys_modules::overrides::{ FileOverridesStore, InMemoryOverridesStore, OverridesError, OverridesStore, }; pub use sys_modules::{ - check_module_disabled, is_module_disabled, register_sys_modules, - register_sys_modules_with_options, HealthModule, HealthSummaryModule, ManifestFullModule, - ManifestModule, ReloadModule, SysModuleError, SysModulesContext, SysModulesOptions, - ToggleFeatureModule, ToggleState, UsageModule, UsageSummaryModule, + check_module_disabled, is_module_disabled, SysModuleError, SysModulesContext, ToggleState, +}; +#[cfg(feature = "sys-modules")] +pub use sys_modules::{ + register_sys_modules, register_sys_modules_with_options, HealthModule, HealthSummaryModule, + ManifestFullModule, ManifestModule, ReloadModule, SysModulesOptions, ToggleFeatureModule, + UsageModule, UsageSummaryModule, }; pub use trace_context::{TraceContext, TraceParent}; pub use utils::{ diff --git a/rust/src/lifecycle.rs b/rust/src/lifecycle.rs index 8bf32684..1adc86f7 100644 --- a/rust/src/lifecycle.rs +++ b/rust/src/lifecycle.rs @@ -54,6 +54,7 @@ pub struct ReloadOptions { } impl ReloadOptions { + #[cfg(feature = "sys-modules")] pub(crate) fn from_wire(value: &serde_json::Value) -> Result { let mut wire = value.clone(); if let Some(timeout) = wire.get_mut("drain_timeout_ms") { @@ -72,6 +73,7 @@ impl ReloadOptions { .validate() } + #[cfg(any(feature = "discovery", feature = "sys-modules"))] pub(crate) fn validate(self) -> Result { validate_duration(self.drain_timeout_ms, "drain_timeout_ms")?; Ok(self) diff --git a/rust/src/middleware/yaml_config.rs b/rust/src/middleware/yaml_config.rs index 801a133a..9d692758 100644 --- a/rust/src/middleware/yaml_config.rs +++ b/rust/src/middleware/yaml_config.rs @@ -96,6 +96,7 @@ pub struct MiddlewareChainConfig { impl MiddlewareChainConfig { /// Parse a YAML document into a chain config. + #[cfg(feature = "config")] pub fn from_yaml(source: &str) -> Result { serde_yaml_ng::from_str(source).map_err(|e| { ModuleError::new( @@ -317,7 +318,7 @@ impl Middleware for PriorityOverride { } } -#[cfg(test)] +#[cfg(all(test, feature = "config"))] mod tests { use super::*; diff --git a/rust/src/observability/mod.rs b/rust/src/observability/mod.rs index 95c0ecc7..17dbb6cf 100644 --- a/rust/src/observability/mod.rs +++ b/rust/src/observability/mod.rs @@ -7,7 +7,6 @@ pub mod logging; pub mod metrics; pub mod processor; mod prometheus; -pub mod prometheus_exporter; pub mod redaction; pub mod span; pub mod storage; @@ -28,7 +27,6 @@ pub use processor::{ SpanProcessor, }; pub use prometheus::render_prometheus_metrics; -pub use prometheus_exporter::PrometheusExporter; pub use redaction::{RedactionConfig, RedactionConfigBuilder, RedactionConfigError}; pub use span::{Span, SpanExporter}; pub use storage::{default_storage_backend, InMemoryStorageBackend, StorageBackend, StorageError}; diff --git a/rust/src/observability/prometheus_exporter.rs b/rust/src/observability/prometheus_exporter.rs deleted file mode 100644 index 3b86618c..00000000 --- a/rust/src/observability/prometheus_exporter.rs +++ /dev/null @@ -1,364 +0,0 @@ -// APCore Protocol — Prometheus exporter & K8s health endpoints -// Spec reference: observability.md §1.6 K8s/Prometheus Integration Hooks - -use std::io; -use std::net::SocketAddr; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::net::{TcpListener, TcpStream}; -use tokio::sync::{oneshot, Semaphore}; -use tokio::task::JoinSet; -use tokio::time::{timeout, Duration}; - -use super::metrics::MetricsCollector; -use super::prometheus::render_prometheus_metrics; -use super::usage::UsageCollector; - -/// Per-connection read deadline. A slow client that drip-feeds bytes is -/// treated as a slow-loris attempt; the request is dropped after this window. -const REQUEST_READ_TIMEOUT: Duration = Duration::from_secs(10); -const RESPONSE_WRITE_TIMEOUT: Duration = Duration::from_secs(10); - -/// Maximum simultaneously-open connections served by [`PrometheusExporter`]. -/// Bounds spawn fan-out so a hostile client cannot exhaust the runtime. -const MAX_CONCURRENT_CONNECTIONS: usize = 64; - -/// HTTP server that serves Prometheus text metrics plus `/healthz` and -/// `/readyz` endpoints. -/// -/// Endpoints (observability.md §1.6): -/// GET /metrics — Prometheus text exposition format -/// GET /healthz — liveness, always 200 OK -/// GET /readyz — readiness, 200 OK after `mark_ready()`, else 503 -#[derive(Debug, Clone)] -pub struct PrometheusExporter { - collector: MetricsCollector, - usage_collector: Option, - ready: Arc, - listener: Arc>>, -} - -#[derive(Debug)] -struct RunningListener { - address: SocketAddr, - shutdown: Option>, -} - -struct ListenerBinding(Arc>>); - -impl Drop for ListenerBinding { - fn drop(&mut self) { - self.0.lock().take(); - } -} - -impl PrometheusExporter { - /// Create a new exporter bound to the given collector. - #[must_use] - pub fn new(collector: MetricsCollector) -> Self { - Self { - collector, - usage_collector: None, - ready: Arc::new(AtomicBool::new(false)), - listener: Arc::new(parking_lot::Mutex::new(None)), - } - } - - /// Attach a `UsageCollector` whose `apcore_usage_*` metrics will be - /// appended to every `/metrics` response (system-modules.md §1.3). - #[must_use] - pub fn with_usage_collector(mut self, usage: UsageCollector) -> Self { - self.usage_collector = Some(usage); - self - } - - /// Return the current metrics in Prometheus text format. - #[must_use] - pub fn export(&self) -> String { - render_prometheus_metrics(&self.collector, self.usage_collector.as_ref()) - } - - /// Mark the application as ready to serve traffic. `/readyz` will return 200. - pub fn mark_ready(&self) { - self.ready.store(true, Ordering::SeqCst); - } - - /// Mark the application as not ready (e.g. during shutdown). - pub fn mark_not_ready(&self) { - self.ready.store(false, Ordering::SeqCst); - } - - /// Address of the listening socket, or `None` after it closes. - #[must_use] - pub fn local_addr(&self) -> Option { - self.listener - .lock() - .as_ref() - .map(|listener| listener.address) - } - - /// Spawn a background HTTP server on the given port, serving metrics at `path`. - /// - /// The returned future resolves once the listener is bound. The server runs - /// until `shutdown()` is called. - /// - /// # Errors - /// Returns an error if the exporter is already listening or the port cannot be bound. - pub async fn start(&self, port: u16, path: &str) -> io::Result<()> { - let addr: SocketAddr = ([0, 0, 0, 0], port).into(); - let listener = TcpListener::bind(addr).await?; - let address = listener.local_addr()?; - let (shutdown, stop) = oneshot::channel(); - { - let mut state = self.listener.lock(); - if state.is_some() { - return Err(io::Error::new( - io::ErrorKind::AlreadyExists, - "PrometheusExporter is already listening", - )); - } - *state = Some(RunningListener { - address, - shutdown: Some(shutdown), - }); - } - tokio::spawn(serve( - listener, - self.clone(), - path.to_owned(), - stop, - ListenerBinding(Arc::clone(&self.listener)), - )); - Ok(()) - } - - /// Signal the running server to stop accepting new connections. - pub fn shutdown(&self) { - let shutdown = self - .listener - .lock() - .as_mut() - .and_then(|listener| listener.shutdown.take()); - if let Some(shutdown) = shutdown { - let _ = shutdown.send(()); - } - } -} - -async fn serve( - listener: TcpListener, - exporter: PrometheusExporter, - path: String, - mut stop: oneshot::Receiver<()>, - binding: ListenerBinding, -) { - let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_CONNECTIONS)); - let mut connections = JoinSet::new(); - loop { - tokio::select! { - biased; - _ = &mut stop => break, - Some(_) = connections.join_next() => {}, - accept = listener.accept() => match accept { - Ok((stream, _)) => { - let Ok(permit) = Arc::clone(&semaphore).try_acquire_owned() else { - tracing::warn!("PrometheusExporter: connection refused, max concurrent connections reached"); - continue; - }; - let exporter = exporter.clone(); - let path = path.clone(); - connections.spawn(async move { - let _permit = permit; - if let Err(error) = handle_connection(stream, exporter, &path).await { - tracing::debug!(%error, "PrometheusExporter: connection error"); - } - }); - } - Err(error) => tracing::warn!(%error, "PrometheusExporter: accept failed"), - }, - } - } - - drop(listener); - drop(binding); - if timeout(REQUEST_READ_TIMEOUT, async { - while connections.join_next().await.is_some() {} - }) - .await - .is_err() - { - connections.abort_all(); - } -} - -async fn handle_connection( - mut stream: TcpStream, - exporter: PrometheusExporter, - metrics_path: &str, -) -> io::Result<()> { - // Bound the read so a slow-loris client cannot pin a task indefinitely. - let request_line = match timeout(REQUEST_READ_TIMEOUT, read_request_line(&mut stream)).await { - Ok(result) => result?, - Err(_) => { - return Err(io::Error::new( - io::ErrorKind::TimedOut, - "PrometheusExporter: request read timed out", - )); - } - }; - let target = parse_target(&request_line).unwrap_or_default(); - - let (status, content_type, body) = if target == metrics_path { - let body = exporter.export(); - ("200 OK", "text/plain; version=0.0.4; charset=utf-8", body) - } else if target == "/healthz" { - ("200 OK", "text/plain; charset=utf-8", "OK\n".to_string()) - } else if target == "/readyz" { - if exporter.ready.load(Ordering::SeqCst) { - ("200 OK", "text/plain; charset=utf-8", "OK\n".to_string()) - } else { - ( - "503 Service Unavailable", - "text/plain; charset=utf-8", - "Not ready\n".to_string(), - ) - } - } else { - ( - "404 Not Found", - "text/plain; charset=utf-8", - "Not Found\n".to_string(), - ) - }; - - let response = format!( - "HTTP/1.1 {status}\r\n\ - Content-Type: {content_type}\r\n\ - Content-Length: {len}\r\n\ - Connection: close\r\n\r\n{body}", - len = body.len(), - ); - timeout(RESPONSE_WRITE_TIMEOUT, async { - stream.write_all(response.as_bytes()).await?; - let _ = stream.shutdown().await; - Ok(()) - }) - .await - .unwrap_or_else(|_| { - Err(io::Error::new( - io::ErrorKind::TimedOut, - "PrometheusExporter: response write timed out", - )) - }) -} - -async fn read_request_line(stream: &mut TcpStream) -> io::Result { - let mut buf = Vec::with_capacity(512); - let mut tmp = [0u8; 256]; - while !buf.windows(4).any(|w| w == b"\r\n\r\n") { - let n = stream.read(&mut tmp).await?; - if n == 0 { - break; - } - buf.extend_from_slice(&tmp[..n]); - if buf.len() > 8192 { - break; - } - } - let text = String::from_utf8_lossy(&buf); - Ok(text.lines().next().unwrap_or_default().to_string()) -} - -fn parse_target(request_line: &str) -> Option { - let mut parts = request_line.split_whitespace(); - let _method = parts.next()?; - let target = parts.next()?; - Some(target.to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[tokio::test] - async fn shutdown_before_listener_task_starts_releases_port_and_allows_restart() { - let exporter = PrometheusExporter::new(MetricsCollector::new()); - exporter.start(0, "/metrics").await.unwrap(); - let bound = exporter.local_addr().unwrap(); - exporter.shutdown(); - - timeout(Duration::from_secs(2), async { - loop { - match TcpListener::bind(bound).await { - Ok(_) => break, - Err(error) if error.kind() == io::ErrorKind::AddrInUse => { - tokio::time::sleep(Duration::from_millis(10)).await; - } - Err(error) => panic!("unexpected error rebinding listener: {error}"), - } - } - }) - .await - .expect("shutdown should release the port even before the listener task first polls"); - assert!(exporter.local_addr().is_none()); - - exporter.start(bound.port(), "/metrics").await.unwrap(); - let mut socket = TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, bound.port())) - .await - .unwrap(); - socket - .write_all(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n") - .await - .unwrap(); - let mut response = String::new(); - timeout(Duration::from_secs(2), socket.read_to_string(&mut response)) - .await - .unwrap() - .unwrap(); - assert!(response.starts_with("HTTP/1.1 200 OK\r\n")); - exporter.shutdown(); - } - - #[test] - fn export_includes_required_metrics_when_empty() { - let collector = MetricsCollector::new(); - let exporter = PrometheusExporter::new(collector); - let body = exporter.export(); - assert!(body.contains("apcore_module_calls_total")); - assert!(body.contains("apcore_module_errors_total")); - assert!(body.contains("apcore_module_duration_seconds")); - } - - #[test] - fn export_includes_required_metrics_when_populated() { - let collector = MetricsCollector::new(); - collector.increment_calls("mod.a", "success"); - collector.increment_errors("mod.a", "ERR"); - collector.observe_duration("mod.a", 0.1); - let exporter = PrometheusExporter::new(collector); - let body = exporter.export(); - assert!(body.contains("apcore_module_calls_total")); - assert!(body.contains("apcore_module_errors_total")); - assert!(body.contains("apcore_module_duration_seconds")); - } - - #[test] - fn render_prometheus_metrics_matches_legacy_export_with_live_usage() { - let metrics = MetricsCollector::new(); - let usage = UsageCollector::new(); - let exporter = PrometheusExporter::new(metrics.clone()).with_usage_collector(usage.clone()); - - assert_eq!( - crate::render_prometheus_metrics(&metrics, Some(&usage)), - exporter.export() - ); - metrics.increment_calls("sample.metric", "success"); - usage.record("sample.metric", Some("sample.caller"), 1.0, true); - - let snapshot = crate::render_prometheus_metrics(&metrics, Some(&usage)); - assert_eq!(snapshot, exporter.export()); - assert!(snapshot.contains("apcore_usage_")); - assert!(snapshot.contains("sample.metric")); - } -} diff --git a/rust/src/observability/redaction.rs b/rust/src/observability/redaction.rs index d3c28c0e..d380cf75 100644 --- a/rust/src/observability/redaction.rs +++ b/rust/src/observability/redaction.rs @@ -662,7 +662,7 @@ mod tests { .unwrap_or_else(std::sync::PoisonError::into_inner); LEGACY_REDACTION_KEY_WARNING_EMITTED.store(false, Ordering::Relaxed); - let mut config = Config::from_defaults(); + let mut config = Config::in_memory(); config.set(LEGACY_SENSITIVE_KEYS, json!(["legacy_key"])); let logs = capture_logs(|| { @@ -700,7 +700,7 @@ mod tests { .unwrap_or_else(std::sync::PoisonError::into_inner); LEGACY_REDACTION_KEY_WARNING_EMITTED.store(false, Ordering::Relaxed); - let mut config = Config::from_defaults(); + let mut config = Config::in_memory(); config.set(CANONICAL_SENSITIVE_KEYS, json!(["canonical_key"])); let logs = capture_logs(|| { diff --git a/rust/src/observability/usage.rs b/rust/src/observability/usage.rs index 750a4692..b0874bd4 100644 --- a/rust/src/observability/usage.rs +++ b/rust/src/observability/usage.rs @@ -46,7 +46,7 @@ pub struct UsageStats { /// Maximum records per hourly bucket before oldest are evicted. const MAX_RECORDS_PER_BUCKET: usize = 10_000; -/// Maximum hourly buckets retained per module (168 = 7 days). +/// Maximum occupied buckets per module when a retention window is unset. const MAX_BUCKETS_PER_MODULE: usize = 168; /// Internal module data for aggregation. @@ -76,12 +76,26 @@ impl ModuleData { .flatten() .collect() } + + fn expire_before(&mut self, cutoff_bucket: &str) -> Vec { + let mut expired = Vec::new(); + self.records.retain(|bucket, records| { + if bucket.as_str() < cutoff_bucket { + expired.append(records); + false + } else { + true + } + }); + expired + } } /// Collects usage statistics across module executions. #[derive(Debug, Clone)] pub struct UsageCollector { data: Arc>>, + retention: Option, /// Issue #43 §1: optional `StorageBackend` for persistence beyond process /// lifetime. Each `record()` writes a serialized `UsageRecord` to the /// backend under namespace `"usage"`; the in-memory aggregation still @@ -121,11 +135,20 @@ impl UsageCollector { .then(|| Arc::new(InMemoryStorageBackend::new())); Self { data: Arc::new(Mutex::new(HashMap::new())), + retention: None, storage_backend, default_storage, } } + #[cfg(feature = "sys-modules")] + pub(crate) fn with_retention(retention: Duration) -> Self { + Self { + retention: Some(retention), + ..Self::new() + } + } + /// Generate hourly bucket key from a timestamp: "YYYY-MM-DDTHH". fn bucket_key(ts: DateTime) -> String { ts.format("%Y-%m-%dT%H").to_string() @@ -174,7 +197,16 @@ impl UsageCollector { for expired in bucket_records.drain(..excess) { self.remove_default_record(&expired); } - for expired in module.evict_old_buckets() { + let expired = if let Some(retention) = self.retention { + Utc::now() + .checked_sub_signed(retention) + .map_or_else(Vec::new, |cutoff| { + module.expire_before(&Self::bucket_key(cutoff)) + }) + } else { + module.evict_old_buckets() + }; + for expired in expired { self.remove_default_record(&expired); } if let Some(storage) = &self.default_storage { @@ -386,6 +418,7 @@ impl UsageCollector { /// A record with no caller identity is attributed to the literal /// `"unknown"` (6.7.1.4). #[must_use] + #[cfg(feature = "sys-modules")] pub(crate) fn get_caller_breakdown_for_period( &self, module_id: &str, @@ -439,6 +472,7 @@ impl UsageCollector { /// `period` filters the counts inside each bucket; the 24-entry span the /// sys-module pads to is fixed and is not widened by it (6.7.1.2). #[must_use] + #[cfg(feature = "sys-modules")] pub(crate) fn get_hourly_distribution_for_period( &self, module_id: &str, @@ -657,6 +691,7 @@ fn escape_label_value(v: &str) -> String { /// Per-caller usage statistics. #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg(feature = "sys-modules")] pub(crate) struct CallerStats { pub caller_id: String, pub call_count: u64, @@ -666,6 +701,7 @@ pub(crate) struct CallerStats { /// Hourly usage bucket. #[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg(feature = "sys-modules")] pub(crate) struct HourlyBucket { pub hour: String, pub call_count: u64, diff --git a/rust/src/policy.rs b/rust/src/policy.rs index 515284c9..3de947c8 100644 --- a/rust/src/policy.rs +++ b/rust/src/policy.rs @@ -145,20 +145,31 @@ pub struct PolicyDecision { } /// Declarative execution-time governance overrides (apcore#76 RFC pilot). -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct ExecutionPolicy { rules: Vec, /// When true, modules whose effective `destructive` annotation is true - /// require approval even if `requires_approval` is false — the opt-in - /// resolution of the destructive↔approval gap described in apcore#76. + /// require approval even when `requires_approval` is false. Defaults to true. pub gate_destructive: bool, /// When true, the approval gate fails closed (denies) when a module needs - /// approval but no `ApprovalHandler` is configured. When false (default), - /// the gate keeps the `PROTOCOL_SPEC` §7.4 skip behavior but logs a warning. + /// approval but no `ApprovalHandler` is configured. Defaults to true. + /// An explicit false retains the warn-and-continue behavior. pub strict: bool, } +impl Default for ExecutionPolicy { + fn default() -> Self { + Self::new(Vec::new()) + } +} + impl ExecutionPolicy { + pub(crate) fn effective(configured: Option<&Self>) -> &Self { + static DEFAULT: std::sync::LazyLock = + std::sync::LazyLock::new(ExecutionPolicy::default); + configured.unwrap_or(&DEFAULT) + } + /// Build a policy from ordered pattern-based overrides. The most specific /// matching rule wins (Algorithm A10 specificity); on a tie the more /// restrictive rule wins, then the earlier-defined rule. @@ -166,8 +177,8 @@ impl ExecutionPolicy { pub fn new(rules: Vec) -> Self { Self { rules, - gate_destructive: false, - strict: false, + gate_destructive: true, + strict: true, } } @@ -431,12 +442,16 @@ fn argument_shape(arguments: &serde_json::Value) -> Vec<(&str, &'static str)> { struct PolicyDoc { #[serde(default)] rules: Vec, - #[serde(default)] + #[serde(default = "enabled_by_default")] gate_destructive: bool, - #[serde(default)] + #[serde(default = "enabled_by_default")] strict: bool, } +fn enabled_by_default() -> bool { + true +} + #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct RuleDoc { @@ -505,8 +520,8 @@ mod tests { fn empty_document() { let policy = ExecutionPolicy::from_value(json!({})).unwrap(); assert_eq!(policy.rules(), []); - assert!(!policy.gate_destructive); - assert!(!policy.strict); + assert!(policy.gate_destructive); + assert!(policy.strict); } #[test] diff --git a/rust/src/registry/managed_drain.rs b/rust/src/registry/managed_drain.rs index 8ba90c8b..b9481191 100644 --- a/rust/src/registry/managed_drain.rs +++ b/rust/src/registry/managed_drain.rs @@ -21,6 +21,7 @@ use super::{deadline_after, DrainGuard, RemovalResources}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(super) enum DrainAction { ContinueWaiting, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] AbortReload, CancelThenForce(u32), LegacyForce, @@ -39,6 +40,7 @@ impl DrainAction { fn name(self) -> &'static str { match self { Self::ContinueWaiting => "continue_waiting", + #[cfg(any(feature = "discovery", feature = "sys-modules"))] Self::AbortReload => "abort_reload", Self::CancelThenForce(_) => "cancel_then_force", Self::LegacyForce => "legacy_force", @@ -69,7 +71,9 @@ pub(super) struct DrainPlan { pub(super) struct DrainResult { pub(super) hook_error: Option, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] pub(super) error_preceded_deadline: bool, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] pub(super) timed_out: bool, pub(super) force: bool, } @@ -107,10 +111,24 @@ impl RemovalResources { result = &mut hooks => { let error = result.err(); if error.is_some() && plan.reason == DrainReasonKind::Reload { - return DrainResult { hook_error: error, error_preceded_deadline: true, timed_out: false, force: false }; + return DrainResult { + hook_error: error, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] + error_preceded_deadline: true, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] + timed_out: false, + force: false, + }; } if guard.references.wait_for_drain(Some(plan.deadline)).await { - return DrainResult { hook_error: error, error_preceded_deadline: false, timed_out: false, force: false }; + return DrainResult { + hook_error: error, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] + error_preceded_deadline: false, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] + timed_out: false, + force: false, + }; } (error, self.drain_timeout(operation, index, guard, plan)) }, @@ -131,7 +149,9 @@ impl RemovalResources { guard.references.wait_for_drain(None).await; false } - DrainAction::ContinueWaiting | DrainAction::AbortReload => false, + DrainAction::ContinueWaiting => false, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] + DrainAction::AbortReload => false, DrainAction::LegacyForce => true, DrainAction::CancelThenForce(_) => { !guard.references.wait_for_drain(grace_deadline).await @@ -139,7 +159,9 @@ impl RemovalResources { }; DrainResult { hook_error, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] error_preceded_deadline: false, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] timed_out: true, force, } diff --git a/rust/src/registry/managed_lifecycle.rs b/rust/src/registry/managed_lifecycle.rs index cc4ba4bb..d7882527 100644 --- a/rust/src/registry/managed_lifecycle.rs +++ b/rust/src/registry/managed_lifecycle.rs @@ -23,6 +23,7 @@ use super::{ #[path = "managed_drain.rs"] mod managed_drain; +#[cfg(any(feature = "discovery", feature = "sys-modules"))] #[path = "managed_reload.rs"] mod managed_reload; @@ -157,8 +158,10 @@ impl Registry { }); let registry = Arc::clone(self); let owned = operation.clone(); + #[cfg(feature = "discovery")] let watcher = self.stop_watching(); runtime.spawn(async move { + #[cfg(feature = "discovery")] if let Some(watcher) = watcher { let _ = watcher.await; } diff --git a/rust/src/registry/managed_reload.rs b/rust/src/registry/managed_reload.rs index 70cb228e..0328f7d3 100644 --- a/rust/src/registry/managed_reload.rs +++ b/rust/src/registry/managed_reload.rs @@ -47,6 +47,7 @@ impl Drop for ReloadSlot<'_> { } impl Registry { + #[cfg(feature = "sys-modules")] pub(crate) fn start_managed_reload( self: &Arc, ids: Vec, diff --git a/rust/src/registry/metadata.rs b/rust/src/registry/metadata.rs index 91a8ffe4..a492c78e 100644 --- a/rust/src/registry/metadata.rs +++ b/rust/src/registry/metadata.rs @@ -2,8 +2,10 @@ // Spec reference: §4.13 metadata merge, companion YAML loading use std::collections::HashMap; +#[cfg(feature = "discovery")] use std::path::Path; +#[cfg(feature = "discovery")] use crate::errors::{ErrorCode, ModuleError}; use crate::registry::types::DepInfo; @@ -13,6 +15,7 @@ use crate::registry::types::DepInfo; /// /// Aligned with `apcore-python.load_metadata` and /// `apcore-typescript.loadMetadata`. +#[cfg(feature = "discovery")] pub fn load_metadata(meta_path: &Path) -> Result, ModuleError> { match meta_path.symlink_metadata() { Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(HashMap::new()), @@ -228,6 +231,7 @@ pub(crate) fn merge_annotation_fields( /// /// Aligned with `apcore-python.load_id_map` and /// `apcore-typescript.loadIdMap`. +#[cfg(feature = "discovery")] pub fn load_id_map( id_map_path: &Path, ) -> Result>, ModuleError> { @@ -293,7 +297,7 @@ pub fn load_id_map( Ok(result) } -#[cfg(test)] +#[cfg(all(test, feature = "discovery"))] mod tests { use super::*; diff --git a/rust/src/registry/mod.rs b/rust/src/registry/mod.rs index d908b5c6..f445b987 100644 --- a/rust/src/registry/mod.rs +++ b/rust/src/registry/mod.rs @@ -5,21 +5,26 @@ pub mod registry; pub mod conflicts; +#[cfg(feature = "discovery")] pub mod default_discoverer; pub mod dependencies; pub mod entry_point; pub mod metadata; pub mod multi_class; +#[cfg(feature = "discovery")] pub mod scanner; pub mod types; pub mod validation; pub mod version; pub use conflicts::{detect_id_conflicts, ConflictResult, ConflictSeverity, ConflictType}; +#[cfg(feature = "discovery")] pub use default_discoverer::{DefaultDiscoverer, ModuleFactory}; pub use dependencies::resolve_dependencies; pub use entry_point::{infer_struct_name, resolve_entry_point_name, snake_to_pascal}; -pub use metadata::{load_id_map, load_metadata, merge_module_metadata, parse_dependencies}; +#[cfg(feature = "discovery")] +pub use metadata::{load_id_map, load_metadata}; +pub use metadata::{merge_module_metadata, parse_dependencies}; pub use multi_class::{ class_name_to_segment, compute_base_id, derive_module_ids, DiscoveredClass, DiscoveryConfig, MultiClassEntry, MAX_MODULE_ID_LEN, @@ -29,6 +34,7 @@ pub use registry::{ ModuleDescriptor, ModuleValidator, Registry, RegistryEvents, DEFAULT_MODULE_VERSION, MAX_MODULE_ID_LENGTH, MODULE_ID_PATTERN, REGISTRY_EVENTS, RESERVED_WORDS, }; +#[cfg(feature = "discovery")] pub use scanner::{scan_extensions, scan_multi_root}; pub use types::{DepInfo, DiscoveredFile}; pub use validation::validate_descriptor; diff --git a/rust/src/registry/registry.rs b/rust/src/registry/registry.rs index 17734d29..a31c821a 100644 --- a/rust/src/registry/registry.rs +++ b/rust/src/registry/registry.rs @@ -14,7 +14,9 @@ use std::sync::{ use crate::cancel::CancelToken; use crate::errors::ModuleError; use crate::events::emitter::{ApCoreEvent, EventEmitter}; -use crate::lifecycle::{lifecycle_runtime, lifecycle_worker, ReloadOptions, REGISTRY_CALLBACK}; +#[cfg(feature = "discovery")] +use crate::lifecycle::{lifecycle_runtime, ReloadOptions}; +use crate::lifecycle::{lifecycle_worker, REGISTRY_CALLBACK}; use crate::module::{ Module, ModuleAnnotations, ModuleExample, ValidationErrorDetail, ValidationResult, }; @@ -753,6 +755,7 @@ impl DrainGuard<'_> { modules } + #[cfg(any(feature = "discovery", feature = "sys-modules"))] fn apply_recovery(&self, recovered: bool) -> bool { let mut core = self.core.write(); if core.closed || !self.refers_to_current_registration(&core) { @@ -800,8 +803,10 @@ struct RegistrationOptions<'a> { pub(crate) struct RemovedRegistration { pub(crate) primary: Arc, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] pub(crate) descriptor: ModuleDescriptor, older_versions: Vec, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] source: Option, } @@ -826,6 +831,7 @@ fn resume_reloaded_module(name: &str, module: &dyn Module, state: serde_json::Va } } +#[cfg(any(feature = "discovery", feature = "sys-modules"))] pub(crate) struct ReloadRegistration { pub(crate) removed: RemovedRegistration, pub(crate) state: Option, @@ -890,10 +896,14 @@ impl RegistryCore { if let Some(references) = self.ref_counts.remove(name) { references.drained.notify_waiters(); } + #[cfg(not(any(feature = "discovery", feature = "sys-modules")))] + let _ = (descriptor, source); Some(RemovedRegistration { primary, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] descriptor, older_versions, + #[cfg(any(feature = "discovery", feature = "sys-modules"))] source, }) } @@ -944,9 +954,11 @@ pub struct Registry { extension_roots: RwLock>, /// Live filesystem watcher (sync finding A-D-010). `None` when /// `watch()` has not been called or has been stopped via `unwatch()`. + #[cfg(feature = "discovery")] watcher: parking_lot::Mutex>, /// Background task handle that consumes notify events and triggers /// debounced re-discovery. Cleared on `unwatch()`. + #[cfg(feature = "discovery")] watch_handle: parking_lot::Mutex>>, /// Tracks unpublished registrations and excludes concurrent registrations /// of the same ID, including while rejected loads are being cleaned up. @@ -980,6 +992,7 @@ struct DiscovererRestoreGuard<'a> { /// Watchers report resolved paths (`/private/var/...` on macOS for a root under /// `/var/...`), so both sides of a comparison are canonicalised. A removed file /// can no longer be canonicalised, so its parent is instead. +#[cfg(feature = "discovery")] fn normalize_watched_path(path: &std::path::Path) -> std::path::PathBuf { if let Ok(resolved) = std::fs::canonicalize(path) { return resolved; @@ -1055,7 +1068,9 @@ impl Registry { discoverer: RwLock::new(None), validator: RwLock::new(None), extension_roots: RwLock::new(Vec::new()), + #[cfg(feature = "discovery")] watcher: parking_lot::Mutex::new(None), + #[cfg(feature = "discovery")] watch_handle: parking_lot::Mutex::new(None), in_flight: LoadingRegistrations::default(), load_failed_callbacks: RwLock::new(Vec::new()), @@ -2365,6 +2380,7 @@ impl Registry { Ok(removed) } + #[cfg(any(feature = "discovery", feature = "sys-modules"))] pub(crate) async fn unload_for_reload( &self, name: &str, @@ -2381,6 +2397,7 @@ impl Registry { } /// Restore all versions and the source association after failed replacement. + #[cfg(any(feature = "discovery", feature = "sys-modules"))] pub(crate) async fn restore_reload( &self, name: &str, @@ -2576,21 +2593,6 @@ impl Registry { } } - /// Deprecated alias for [`acquire`](Self::acquire) — kept for backward - /// compatibility with apcore-rust 0.19.x which had separate - /// `acquire`/`acquire_ref` semantics. - #[deprecated(since = "0.20.0", note = "Use `acquire()` — it now ref-counts.")] - pub fn acquire_ref(&self, name: &str) -> Result, ModuleError> { - self.acquire(name) - } - - /// Deprecated alias for [`release`](Self::release) — kept for backward - /// compatibility with apcore-rust 0.19.x. - #[deprecated(since = "0.20.0", note = "Use `release()`.")] - pub fn release_ref(&self, name: &str) { - self.release(name); - } - /// Check if a module is draining. pub fn is_draining(&self, name: &str) -> bool { self.core.read().draining.contains(name) @@ -2695,11 +2697,13 @@ impl Registry { #[allow(unknown_lints)] #[allow(clippy::unused_async)] #[allow(clippy::unused_async_trait_impl)] + #[cfg(feature = "discovery")] pub async fn watch(self: &Arc) -> Result<(), ModuleError> { self.start_watcher(None) } /// Watch configured roots with managed, generation-aware replacement. + #[cfg(feature = "discovery")] pub fn watch_with_lifecycle( self: &Arc, options: ReloadOptions, @@ -2707,6 +2711,7 @@ impl Registry { self.start_watcher(Some(options.validate()?)) } + #[cfg(feature = "discovery")] fn start_watcher( self: &Arc, lifecycle: Option, @@ -2775,6 +2780,7 @@ impl Registry { /// Background task body that consumes notify events and applies each /// debounced batch of changed paths. Exits when the receiver channel /// closes or the `Weak` can no longer be upgraded. + #[cfg(feature = "discovery")] async fn watch_loop( mut rx: tokio::sync::mpsc::UnboundedReceiver>, weak: std::sync::Weak, @@ -2827,6 +2833,7 @@ impl Registry { /// Apply a batch of changed file paths: register new modules, replace the /// modules whose source (or `_meta.yaml` sidecar) changed, and unregister /// those whose source file is gone. + #[cfg(feature = "discovery")] async fn apply_file_changes( self: &Arc, paths: &[std::path::PathBuf], @@ -2893,6 +2900,7 @@ impl Registry { /// Replace a registered module with a freshly discovered instance, /// handing its `on_suspend` state to the new instance's `on_resume`. The /// previous instance is put back if the new one fails to register. + #[cfg(feature = "discovery")] async fn replace_discovered( &self, dm: DiscoveredModule, @@ -2941,10 +2949,12 @@ impl Registry { /// Stop filesystem watching. The background task is aborted and the /// platform watcher is dropped. Idempotent — calling on a non-watching /// Registry is a no-op. + #[cfg(feature = "discovery")] pub fn unwatch(&self) { self.stop_watching(); } + #[cfg(feature = "discovery")] fn stop_watching(&self) -> Option> { let (watcher, handle) = { let mut watcher = self.watcher.lock(); diff --git a/rust/src/schema/exporter.rs b/rust/src/schema/exporter.rs index 63f8f9fd..b972b750 100644 --- a/rust/src/schema/exporter.rs +++ b/rust/src/schema/exporter.rs @@ -1,420 +1,15 @@ -// APCore Protocol — Schema exporter -// Spec reference: Exporting schemas in various formats +use serde_json::{json, Value}; -use std::collections::HashMap; - -use serde::{Deserialize, Serialize}; - -use super::strict::{apply_llm_descriptions, strip_extension_keywords, to_strict_schema}; use super::SchemaDefinition; -use crate::errors::{ErrorCode, ModuleError}; -use crate::module::{ModuleAnnotations, ModuleExample}; - -/// Optional parameters for the spec-compatible [`SchemaExporter::export`] method. -#[derive(Debug, Clone, Default)] -pub struct ExportOptions { - /// Optional annotations to merge into the exported schema (e.g. `x-*` fields). - pub annotations: Option, - /// Optional examples array to include in the exported schema. - pub examples: Option, - /// Override the schema name in the exported output. - pub name: Option, -} - -/// Profile controlling how schemas are exported. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ExportProfile { - Mcp, - #[serde(rename = "openai")] - OpenAi, - Anthropic, - Generic, -} - -/// Exports schemas to various formats. -#[derive(Debug)] -pub struct SchemaExporter; - -impl SchemaExporter { - /// Create a new schema exporter. - #[must_use] - pub fn new() -> Self { - Self - } - - /// Export a schema using the given profile. - /// - /// Returns a [`serde_json::Value`] (spec-compatible with Python/TypeScript `-> dict`). - /// Optional `options` allows overriding the name and merging annotations/examples. - pub fn export( - &self, - schema: &serde_json::Value, - profile: ExportProfile, - options: Option<&ExportOptions>, - ) -> Result { - let mut exported = match profile { - ExportProfile::Mcp => self.export_mcp(schema)?, - ExportProfile::OpenAi => self.export_openai(schema)?, - ExportProfile::Anthropic => self.export_anthropic(schema)?, - ExportProfile::Generic => self.export_generic(schema)?, - }; - - // Apply optional overrides from ExportOptions. - if let Some(opts) = options { - if let (Some(obj), Some(name)) = (exported.as_object_mut(), &opts.name) { - obj.insert("name".to_string(), serde_json::Value::String(name.clone())); - } - if let (Some(obj), Some(annotations)) = (exported.as_object_mut(), &opts.annotations) { - if let Some(ann_obj) = annotations.as_object() { - for (k, v) in ann_obj { - obj.entry(k.clone()).or_insert_with(|| v.clone()); - } - } - } - if let (Some(obj), Some(examples)) = (exported.as_object_mut(), &opts.examples) { - obj.insert("examples".to_string(), examples.clone()); - } - } - - Ok(exported) - } - - /// Export a schema to a pretty-printed JSON string (preserves legacy behaviour). - /// - /// Equivalent to calling [`Self::export`] and serializing the result. - pub fn export_serialized( - &self, - schema: &serde_json::Value, - profile: ExportProfile, - options: Option<&ExportOptions>, - ) -> Result { - let value = self.export(schema, profile, options)?; - serde_json::to_string_pretty(&value).map_err(|e| { - ModuleError::new( - ErrorCode::SchemaParseError, - format!("Failed to serialize exported schema: {e}"), - ) - }) - } - - /// Sync SCHEMA-004: Spec-aligned export taking a [`SchemaDefinition`] plus - /// optional `ModuleAnnotations` and `ModuleExample` collections, so MCP - /// and Anthropic envelopes carry the full annotation + meta + examples - /// payload (matching apcore-python `SchemaExporter.export` and - /// apcore-typescript `SchemaExporter.export`). - /// - /// - `MCP` → emits `{name, description, inputSchema, annotations: {...}, - /// _meta: {cacheable, cacheTtl, paginated, paginationStyle, ...}}` - /// - `OpenAI` → emits the strict-mode envelope (Algorithm A23) - /// - `Anthropic` → emits `{name, description, input_schema}` plus - /// `input_examples` if any examples are supplied - /// - `Generic` → returns the full schema definition - /// - /// `name` overrides the envelope's `name` field; when `None`, falls back - /// to `schema_def.module_id` (with `.` → `_` for OpenAI/Anthropic). - pub fn export_def( - &self, - schema_def: &SchemaDefinition, - profile: ExportProfile, - annotations: Option<&ModuleAnnotations>, - examples: Option<&[ModuleExample]>, - name: Option<&str>, - ) -> Result { - match profile { - ExportProfile::Mcp => Ok(Self::build_mcp_envelope(schema_def, annotations, name)), - ExportProfile::OpenAi => Ok(Self::build_openai_envelope(schema_def, name)), - ExportProfile::Anthropic => { - Ok(Self::build_anthropic_envelope(schema_def, examples, name)) - } - ExportProfile::Generic => Ok(Self::build_generic_envelope(schema_def)), - } - } - - fn build_mcp_envelope( - schema_def: &SchemaDefinition, - annotations: Option<&ModuleAnnotations>, - name: Option<&str>, - ) -> serde_json::Value { - let resolved_name = name.map_or_else(|| schema_def.module_id.clone(), str::to_string); - let ann = annotations.cloned().unwrap_or_default(); - let mut envelope = serde_json::json!({ - "name": resolved_name, - "description": schema_def.description, - "inputSchema": schema_def.input_schema, - "annotations": { - "readOnlyHint": ann.readonly, - "destructiveHint": ann.destructive, - "idempotentHint": ann.idempotent, - "openWorldHint": ann.open_world, - }, - "_meta": { - "cacheable": ann.cacheable, - "cacheTtl": ann.cache_ttl, - "cacheKeyFields": ann.cache_key_fields, - "paginated": ann.paginated, - "paginationStyle": ann.pagination_style, - }, - }); - if ann.requires_approval { - envelope["_meta"]["requiresApproval"] = serde_json::json!(true); - } - if ann.streaming { - envelope["_meta"]["streaming"] = serde_json::json!(true); - } - envelope - } - - fn build_openai_envelope( - schema_def: &SchemaDefinition, - name: Option<&str>, - ) -> serde_json::Value { - let resolved_name = - name.map_or_else(|| schema_def.module_id.replace('.', "_"), str::to_string); - // Sync finding A-D-030: substitute `description` with - // `x-llm-description` at every node BEFORE strict-mode strips x-* - // keys, so the LLM-tuned descriptions survive the export. Mirrors - // apcore-python's `_apply_llm_descriptions` and apcore-typescript's - // `applyLlmDescriptions`. - let with_llm = apply_llm_descriptions(&schema_def.input_schema); - let strict_parameters = to_strict_schema(&with_llm); - serde_json::json!({ - "type": "function", - "function": { - "name": resolved_name, - "description": schema_def.description, - "parameters": strict_parameters, - "strict": true, - } - }) - } - - fn build_anthropic_envelope( - schema_def: &SchemaDefinition, - examples: Option<&[ModuleExample]>, - name: Option<&str>, - ) -> serde_json::Value { - let resolved_name = - name.map_or_else(|| schema_def.module_id.replace('.', "_"), str::to_string); - // A-D-030: substitute description with x-llm-description before - // emitting the input_schema so Anthropic sees the LLM-tuned text. - let input_schema_with_llm = - strip_extension_keywords(&apply_llm_descriptions(&schema_def.input_schema)); - let mut envelope = serde_json::json!({ - "name": resolved_name, - "description": schema_def.description, - "input_schema": input_schema_with_llm, - }); - if let Some(exs) = examples { - if !exs.is_empty() { - let inputs: Vec = exs.iter().map(|e| e.inputs.clone()).collect(); - envelope["input_examples"] = serde_json::Value::Array(inputs); - } - } - envelope - } - - fn build_generic_envelope(schema_def: &SchemaDefinition) -> serde_json::Value { - serde_json::json!({ - "module_id": schema_def.module_id, - "description": schema_def.description, - "input_schema": schema_def.input_schema, - "output_schema": schema_def.output_schema, - "definitions": schema_def.definitions.clone().unwrap_or(serde_json::Value::Null), - }) - } - - /// Export all schemas from a loader using the given profile. - /// - /// Returns a map of schema name → [`serde_json::Value`]. - pub fn export_all( - &self, - loader: &super::loader::SchemaLoader, - profile: ExportProfile, - ) -> Result, ModuleError> { - let mut result = HashMap::new(); - for name in loader.list() { - if let Some(schema) = loader.get(name) { - let exported = self.export(schema, profile, None)?; - result.insert(name.to_string(), exported); - } - } - Ok(result) - } - - /// Export all schemas from a loader to serialized JSON strings (legacy helper). - pub fn export_all_serialized( - &self, - loader: &super::loader::SchemaLoader, - profile: ExportProfile, - ) -> Result, ModuleError> { - let mut result = HashMap::new(); - for name in loader.list() { - if let Some(schema) = loader.get(name) { - let exported = self.export_serialized(schema, profile, None)?; - result.insert(name.to_string(), exported); - } - } - Ok(result) - } - - /// MCP format: { name, description, inputSchema, annotations, _meta } - /// - /// Normalize native annotations and MCP hints through the same envelope - /// builder as typed exports. Approval and streaming are true-only metadata. - #[allow(clippy::unused_self)] // consistent method signature for dispatch through export() - fn export_mcp(&self, schema: &serde_json::Value) -> Result { - let name = schema - .get("name") - .cloned() - .unwrap_or(serde_json::Value::Null); - let description = schema - .get("description") - .cloned() - .unwrap_or(serde_json::Value::String(String::new())); - let input_schema = schema - .get("input_schema") - .or_else(|| schema.get("inputSchema")) - .cloned() - .unwrap_or(serde_json::json!({})); - let mut annotations = schema - .get("annotations") - .cloned() - .unwrap_or_else(|| serde_json::json!({})); - for (hint, native) in [ - ("readOnlyHint", "readonly"), - ("destructiveHint", "destructive"), - ("idempotentHint", "idempotent"), - ("openWorldHint", "open_world"), - ("requiresApproval", "requires_approval"), - ] { - if annotations.get(native).is_none() { - if let Some(value) = annotations.get(hint).cloned() { - annotations[native] = value; - } - } - } - for (meta, native) in [ - ("requiresApproval", "requires_approval"), - ("streaming", "streaming"), - ] { - if annotations.get(native).is_none() { - if let Some(value) = schema - .get("_meta") - .and_then(|value| value.get(meta)) - .cloned() - { - annotations[native] = value; - } - } - } - let annotations: ModuleAnnotations = - serde_json::from_value(annotations).map_err(|error| { - ModuleError::new( - ErrorCode::SchemaParseError, - format!("Invalid export annotations: {error}"), - ) - })?; - let definition = SchemaDefinition { - module_id: String::new(), - description: String::new(), - input_schema, - output_schema: serde_json::json!({}), - error_schema: None, - definitions: None, - version: None, - }; - let mut envelope = Self::build_mcp_envelope(&definition, Some(&annotations), None); - envelope["name"] = name; - envelope["description"] = description; - if let Some(meta) = schema.get("_meta").and_then(serde_json::Value::as_object) { - for (key, value) in meta { - if key != "requiresApproval" && key != "streaming" { - envelope["_meta"][key] = value.clone(); - } - } - } - Ok(envelope) - } - - /// `OpenAI` format: { type: "function", function: { name, description, parameters, strict } } - /// - /// Sync SCHEMA-003: parameters MUST be transformed via Algorithm A23 - /// (`to_strict_schema`) so OpenAI strict-mode requirements hold — - /// `additionalProperties: false` on every object schema and all properties - /// listed in `required`. Mirrors apcore-python `exporter.py:70` and - /// apcore-typescript `exporter.ts:59`. - #[allow(clippy::unused_self)] // consistent method signature for dispatch through export() - #[allow(clippy::unnecessary_wraps)] // consistent Result return for dispatch through export() - fn export_openai(&self, schema: &serde_json::Value) -> Result { - let name = schema - .get("name") - .cloned() - .unwrap_or(serde_json::Value::Null); - let description = schema - .get("description") - .cloned() - .unwrap_or(serde_json::Value::String(String::new())); - let parameters = schema - .get("input_schema") - .or_else(|| schema.get("inputSchema")) - .or_else(|| schema.get("parameters")) - .cloned() - .unwrap_or(serde_json::json!({})); - - // Apply Algorithm A23 strict transform so the envelope satisfies - // OpenAI's strict-mode contract. - let strict_parameters = to_strict_schema(&apply_llm_descriptions(¶meters)); - - Ok(serde_json::json!({ - "type": "function", - "function": { - "name": name, - "description": description, - "parameters": strict_parameters, - "strict": true, - } - })) - } - - /// Anthropic format: { name, description, `input_schema` } - #[allow(clippy::unused_self)] // consistent method signature for dispatch through export() - #[allow(clippy::unnecessary_wraps)] // consistent Result return for dispatch through export() - fn export_anthropic( - &self, - schema: &serde_json::Value, - ) -> Result { - let name = schema - .get("name") - .cloned() - .unwrap_or(serde_json::Value::Null); - let description = schema - .get("description") - .cloned() - .unwrap_or(serde_json::Value::String(String::new())); - let input_schema = schema - .get("input_schema") - .or_else(|| schema.get("inputSchema")) - .cloned() - .unwrap_or(serde_json::json!({})); - - Ok(serde_json::json!({ - "name": name, - "description": description, - "input_schema": strip_extension_keywords(&apply_llm_descriptions(&input_schema)), - })) - } - - /// Generic format: return schema as-is. - #[allow(clippy::unused_self)] // consistent method signature for dispatch through export() - #[allow(clippy::unnecessary_wraps)] // consistent Result return for dispatch through export() - fn export_generic(&self, schema: &serde_json::Value) -> Result { - Ok(schema.clone()) - } -} -impl Default for SchemaExporter { - fn default() -> Self { - Self::new() - } +/// Export a module's generic schema with its JSON Schema extensions intact. +#[must_use] +pub fn export_generic(schema: &SchemaDefinition) -> Value { + json!({ + "module_id": schema.module_id, + "description": schema.description, + "input_schema": schema.input_schema, + "output_schema": schema.output_schema, + "definitions": schema.definitions, + }) } diff --git a/rust/src/schema/mod.rs b/rust/src/schema/mod.rs index 2595d63b..1513ab37 100644 --- a/rust/src/schema/mod.rs +++ b/rust/src/schema/mod.rs @@ -3,16 +3,20 @@ pub mod exporter; pub mod hardening; +#[cfg(feature = "config")] pub mod loader; pub mod openai_strict; +#[cfg(feature = "config")] pub mod ref_resolver; pub mod strict; pub mod validator; -pub use exporter::{ExportOptions, ExportProfile, SchemaExporter}; +pub use exporter::export_generic; pub use hardening::{content_hash, format_warnings, FormatWarning}; +#[cfg(feature = "config")] pub use loader::{SchemaLoader, SchemaStrategy}; pub use openai_strict::{assert_openai_strict_compatible, detect_openai_strict_incompatibilities}; +#[cfg(feature = "config")] pub use ref_resolver::RefResolver; pub use strict::to_strict_schema; pub use validator::{DetailedValidationResult, SchemaValidator}; diff --git a/rust/src/schema/strict.rs b/rust/src/schema/strict.rs index 72673535..d2fee110 100644 --- a/rust/src/schema/strict.rs +++ b/rust/src/schema/strict.rs @@ -17,29 +17,11 @@ use serde_json::{Map, Value}; #[must_use] pub fn to_strict_schema(schema: &Value) -> Value { let mut result = schema.clone(); - strip_extensions(&mut result, false, true); + strip_extensions(&mut result, false); convert_to_strict(&mut result); result } -/// Replace `description` with `x-llm-description` (when present) at every -/// node in the schema tree. Returns a deep clone with the substitution -/// applied; the original schema is unmodified. -/// -/// Sync finding A-D-030: spec §schema-system says adapters SHOULD prefer -/// `x-llm-description` over `description` when exporting. apcore-python's -/// `_apply_llm_descriptions` and apcore-typescript's `applyLlmDescriptions` -/// both run this substitution before `to_strict_schema` / `strip_extensions` -/// in the OpenAI/Anthropic export paths so the LLM-tuned description -/// survives the strip. Rust previously had no equivalent step — the x-* -/// keys were silently dropped without copy-down. -#[must_use] -pub fn apply_llm_descriptions(schema: &Value) -> Value { - let mut result = schema.clone(); - apply_llm_descriptions_in_place(&mut result, false); - result -} - fn schema_name_map(key: &str) -> bool { matches!( key, @@ -47,45 +29,15 @@ fn schema_name_map(key: &str) -> bool { ) } -fn apply_llm_descriptions_in_place(node: &mut Value, names: bool) { - if let Some(obj) = node.as_object_mut() { - // Both keys present: substitute description with x-llm-description. - // (Apcore-python parity — Python requires both to be present; - // apcore-typescript injects description even if absent. We follow - // Python's stricter rule to avoid silently fabricating descriptions - // that the spec did not declare.) - if !names && obj.contains_key("description") && obj.contains_key("x-llm-description") { - if let Some(llm_desc) = obj.get("x-llm-description").cloned() { - obj.insert("description".to_string(), llm_desc); - } - } - // Recurse into all nested values. - for (key, v) in obj.iter_mut() { - apply_llm_descriptions_in_place(v, !names && schema_name_map(key)); - } - } else if let Some(arr) = node.as_array_mut() { - for v in arr.iter_mut() { - apply_llm_descriptions_in_place(v, false); - } - } -} - -/// Strip extension keywords without deleting property or definition names. -pub(crate) fn strip_extension_keywords(schema: &Value) -> Value { - let mut result = schema.clone(); - strip_extensions(&mut result, false, false); - result -} - /// Named schema maps contain identifiers, not schema keywords. -fn strip_extensions(node: &mut Value, names: bool, remove_defaults: bool) { +fn strip_extensions(node: &mut Value, names: bool) { let Some(obj) = node.as_object_mut() else { return; }; let keys_to_remove: Vec = obj .keys() - .filter(|k| !names && (k.starts_with("x-") || (remove_defaults && *k == "default"))) + .filter(|k| !names && (k.starts_with("x-") || *k == "default")) .cloned() .collect(); @@ -99,12 +51,12 @@ fn strip_extensions(node: &mut Value, names: bool, remove_defaults: bool) { if let Some(val) = obj.get_mut(&key) { match val { Value::Object(_) => { - strip_extensions(val, !names && schema_name_map(&key), remove_defaults); + strip_extensions(val, !names && schema_name_map(&key)); } Value::Array(arr) => { for item in arr.iter_mut() { if item.is_object() { - strip_extensions(item, false, remove_defaults); + strip_extensions(item, false); } } } diff --git a/rust/src/sys_modules/audit.rs b/rust/src/sys_modules/audit.rs index aa73a7d9..0e6dba53 100644 --- a/rust/src/sys_modules/audit.rs +++ b/rust/src/sys_modules/audit.rs @@ -7,6 +7,7 @@ use parking_lot::Mutex; use serde::{Deserialize, Serialize}; use std::sync::Arc; +#[cfg(feature = "sys-modules")] use crate::context::Context; use crate::errors::ModuleError; @@ -148,6 +149,7 @@ impl AuditStore for InMemoryAuditStore { /// /// Falls back to `"unknown"` when the context has no identity attached, so /// audit records are always emitted even for anonymous callers. +#[cfg(feature = "sys-modules")] pub(crate) fn build_audit_entry( action: AuditAction, target_module_id: &str, @@ -158,6 +160,7 @@ pub(crate) fn build_audit_entry( } /// [`build_audit_entry`] with an explicit correlation id (D-111). +#[cfg(feature = "sys-modules")] pub(crate) fn build_correlated_audit_entry( action: AuditAction, target_module_id: &str, @@ -184,6 +187,7 @@ pub(crate) fn build_correlated_audit_entry( /// Append an `AuditEntry` to the store if configured; otherwise log at /// INFO level and discard. The `Arc` is cheap to clone, so /// callers can hold a single instance and pass references freely. +#[cfg(feature = "sys-modules")] pub(crate) async fn record_audit(store: Option<&Arc>, entry: AuditEntry) { if let Some(store) = store { if let Err(e) = store.append(entry.clone()).await { @@ -201,7 +205,7 @@ pub(crate) async fn record_audit(store: Option<&Arc>, entry: Aud } } -#[cfg(test)] +#[cfg(all(test, feature = "sys-modules"))] mod tests { use super::*; use crate::context::Identity; diff --git a/rust/src/sys_modules/control.rs b/rust/src/sys_modules/control.rs index 32ffd8d5..15f163c9 100644 --- a/rust/src/sys_modules/control.rs +++ b/rust/src/sys_modules/control.rs @@ -455,13 +455,6 @@ pub struct ReloadModule { executor_baseline: Option>, overrides_path: Option, overrides_store: Option>, - /// Once per INSTANCE, not per process (D-121). `reload` is called by - /// hot-reload loops and watchers, so an advisory whose volume is - /// proportional to traffic is one operators learn to filter out — the - /// cadence reasoning D-89 settled. Per instance rather than per process for - /// the reason D-90's notice is per token: a process-wide one-shot tells the - /// first caller and leaves every later one to discover it in production. - reload_dependents_warned: std::sync::atomic::AtomicBool, } impl ReloadModule { @@ -474,7 +467,6 @@ impl ReloadModule { executor_baseline: None, overrides_path: None, overrides_store: None, - reload_dependents_warned: std::sync::atomic::AtomicBool::new(false), } } @@ -483,39 +475,6 @@ impl ReloadModule { self } - /// Warn once that `reload_dependents` is ignored and will be removed (D-121). - /// - /// The field was declared in all three SDKs' input schemas and read by - /// none — a spec MUST that no implementation satisfied, which is the - /// §9.1.3 "declared surface reaches no mechanism" shape applied to a module - /// input field. Three independent implementations skipping it is the - /// evidence the maintainer decision rests on. - /// - /// Deprecated rather than removed now, because the input schema sets - /// `additionalProperties: false`: at 2.0 the same call stops being a silent - /// no-op and becomes a validation error, so a caller passing it today needs - /// a release in which they are told. - fn warn_reload_dependents(&self, inputs: &serde_json::Value) { - if inputs - .get("reload_dependents") - .and_then(serde_json::Value::as_bool) - != Some(true) - { - return; - } - if self - .reload_dependents_warned - .swap(true, std::sync::atomic::Ordering::SeqCst) - { - return; - } - tracing::warn!( - "system.control.reload: 'reload_dependents' is ignored and will be removed at 2.0 \ - (spec D-121). No SDK has ever implemented it. Use a 'path_filter' that also matches \ - the dependents; after removal this field becomes a validation error, not a no-op." - ); - } - /// A failed reload restores only those registrations that were removed /// but were not replaced. The original error remains the public failure. async fn restore_after_failed_reload( @@ -1136,20 +1095,11 @@ impl Module for ReloadModule { fn input_schema(&self) -> serde_json::Value { json!({ "type": "object", + "additionalProperties": false, "required": ["reason"], "properties": { "module_id": {"type": "string"}, "path_filter": {"type": "string"}, - "reload_dependents": { - "type": "boolean", - "default": false, - "deprecated": true, - "description": "DEPRECATED (spec v1.51.0, D-121) — ignored, and removed at 2.0. \ - Declared in all three SDKs and implemented by none, so no caller could ever rely on it. Use an \ - explicit path_filter that also matches the dependents. At 2.0 this field is REMOVED and, because \ - this schema sets additionalProperties: false, passing it becomes a validation error rather than a \ - silent no-op." - }, "reload_config": {"type": "boolean", "default": false}, "lifecycle": { "type": "object", @@ -1179,7 +1129,6 @@ impl Module for ReloadModule { inputs: serde_json::Value, ctx: &Context, ) -> Result { - self.warn_reload_dependents(&inputs); let reason = require_string(&inputs, "reason")?; let module_id_input = inputs diff --git a/rust/src/sys_modules/health.rs b/rust/src/sys_modules/health.rs index 4f29af7a..4af949db 100644 --- a/rust/src/sys_modules/health.rs +++ b/rust/src/sys_modules/health.rs @@ -172,11 +172,18 @@ impl Module for HealthSummaryModule { let module_ids = self.registry.get()?.list(None, None, None); - let project_name = { - let cfg = self.config.lock().await; - cfg.get("project.name") - .and_then(|v| v.as_str().map(std::string::ToString::to_string)) - .unwrap_or_else(|| "apcore".to_string()) + let project = { + let config = self.config.lock().await; + let mut project = json!({"name": config.get("project.name") + .filter(serde_json::Value::is_string) + .unwrap_or_else(|| json!("apcore"))}); + if let Some(version) = config + .get("project.version") + .filter(serde_json::Value::is_string) + { + project["version"] = version; + } + project }; let snapshot = self @@ -233,7 +240,7 @@ impl Module for HealthSummaryModule { } Ok(json!({ - "project": { "name": project_name }, + "project": project, "summary": { "total_modules": module_ids.len(), "healthy": healthy, diff --git a/rust/src/sys_modules/mod.rs b/rust/src/sys_modules/mod.rs index 5efb96b8..289d4459 100644 --- a/rust/src/sys_modules/mod.rs +++ b/rust/src/sys_modules/mod.rs @@ -3,42 +3,68 @@ // system-modules.md §1.1–§1.5 hardening (Issue #45). pub mod audit; +#[cfg(feature = "sys-modules")] pub mod control; +#[cfg(feature = "sys-modules")] pub mod health; +#[cfg(feature = "sys-modules")] pub mod manifest; +#[cfg(feature = "sys-modules")] pub mod overrides; +#[cfg(feature = "sys-modules")] pub mod usage; use std::collections::{HashMap, HashSet}; +#[cfg(feature = "sys-modules")] use std::path::PathBuf; -use std::sync::{Arc, OnceLock, Weak}; +#[cfg(feature = "sys-modules")] +use std::sync::Weak; +use std::sync::{Arc, OnceLock}; use parking_lot::RwLock; +#[cfg(feature = "sys-modules")] use serde_json::json; use thiserror::Error; +#[cfg(feature = "sys-modules")] use tokio::sync::Mutex; +#[cfg(feature = "sys-modules")] use crate::config::Config; use crate::errors::{ErrorCode, ModuleError}; +#[cfg(feature = "sys-modules")] use crate::events::circuit_breaker::{CircuitBreakerWrapper, CircuitEventSink}; -use crate::events::emitter::{ApCoreEvent, EventEmitter}; -use crate::events::subscribers::create_subscriber; +#[cfg(feature = "sys-modules")] +use crate::events::emitter::ApCoreEvent; +use crate::events::emitter::EventEmitter; +#[cfg(feature = "sys-modules")] +use crate::events::subscribers::SubscriberRegistry; +#[cfg(feature = "sys-modules")] use crate::executor::Executor; +#[cfg(feature = "sys-modules")] use crate::middleware::PlatformNotifyMiddleware; +#[cfg(feature = "sys-modules")] use crate::module::Module; -use crate::observability::error_history::{ErrorHistory, ErrorHistoryMiddleware}; +use crate::observability::error_history::ErrorHistory; +#[cfg(feature = "sys-modules")] +use crate::observability::error_history::ErrorHistoryMiddleware; +#[cfg(feature = "sys-modules")] use crate::observability::metrics::MetricsCollector; -use crate::observability::usage::{UsageCollector, UsageMiddleware}; +use crate::observability::usage::UsageCollector; +#[cfg(feature = "sys-modules")] +use crate::observability::usage::UsageMiddleware; +#[cfg(feature = "sys-modules")] use crate::registry::registry::{is_ephemeral_module_id, ModuleDescriptor, Registry}; // Standalone system modules own the registry given to their public constructors. // Bootstrap modules are registered inside that same registry and borrow it weakly. +#[cfg(feature = "sys-modules")] enum SystemRegistry { Owned(Arc), Registered(Weak), } +#[cfg(feature = "sys-modules")] impl SystemRegistry { fn release_ownership(&mut self) { if let Self::Owned(registry) = self { @@ -60,14 +86,20 @@ impl SystemRegistry { } pub use audit::{AuditAction, AuditChange, AuditEntry, AuditStore, InMemoryAuditStore}; +#[cfg(feature = "sys-modules")] pub use control::{ReloadModule, ToggleFeatureModule, UpdateConfigModule}; +#[cfg(feature = "sys-modules")] pub use health::{HealthModule, HealthSummaryModule}; +#[cfg(feature = "sys-modules")] pub use manifest::{ManifestFullModule, ManifestModule}; +#[cfg(feature = "sys-modules")] pub use usage::{UsageModule, UsageSummaryModule}; #[derive(Debug)] +#[cfg(feature = "sys-modules")] struct EmitterCircuitSink(std::sync::Weak); +#[cfg(feature = "sys-modules")] impl CircuitEventSink for EmitterCircuitSink { fn emit_circuit_event(&self, event: ApCoreEvent) { if let Some(emitter) = self.0.upgrade() { @@ -167,9 +199,11 @@ pub fn check_module_disabled(module_id: &str) -> Result<(), ModuleError> { // Sensitive key detection // --------------------------------------------------------------------------- +#[cfg(feature = "sys-modules")] pub(crate) const SENSITIVE_SEGMENTS: &[&str] = &["token", "secret", "key", "password", "auth", "credential"]; +#[cfg(feature = "sys-modules")] pub(crate) fn is_sensitive_key(key: &str) -> bool { let lower = key.to_lowercase(); // W-6: Match exact segments ("key") or underscore-compound segments ("api_key", @@ -188,12 +222,14 @@ pub(crate) fn is_sensitive_key(key: &str) -> bool { // W-7: Lists keys that must not be changed at runtime via update_config. // Scope: runtime-safety critical keys only. Schema-level immutability is // enforced at load time; this list protects against inadvertent runtime mutations. +#[cfg(feature = "sys-modules")] pub(crate) const RESTRICTED_KEYS: &[&str] = &["sys_modules.enabled"]; // --------------------------------------------------------------------------- // Shared helpers (used by control.rs) // --------------------------------------------------------------------------- +#[cfg(feature = "sys-modules")] pub(crate) fn require_string( inputs: &serde_json::Value, field: &str, @@ -211,6 +247,7 @@ pub(crate) fn require_string( }) } +#[cfg(feature = "sys-modules")] pub(crate) fn missing_field_error(field: &str) -> ModuleError { ModuleError::new( ErrorCode::GeneralInvalidInput, @@ -219,6 +256,7 @@ pub(crate) fn missing_field_error(field: &str) -> ModuleError { } /// Emit an event; errors are logged and not propagated (error isolation). +#[cfg(feature = "sys-modules")] pub(crate) async fn emit_event( emitter: &Arc, event_type: &str, @@ -245,6 +283,7 @@ pub(crate) async fn emit_event( /// an audit record shows for a context-less call and the value the ACL matched /// to produce that record are the same identity, and two independent literals /// are how they drift apart. +#[cfg(feature = "sys-modules")] pub(crate) const DEFAULT_EXTERNAL_CALLER: &str = crate::acl::EXTERNAL_CALLER; /// Identity attribute names whose values are replaced with `` in @@ -253,6 +292,7 @@ pub(crate) const DEFAULT_EXTERNAL_CALLER: &str = crate::acl::EXTERNAL_CALLER; /// `obs.redaction.sensitive_keys` so bearer tokens, signed cookies, and /// credentials can never leak through the contextual-audit channel even when /// global redaction is disabled. +#[cfg(feature = "sys-modules")] const IDENTITY_SENSITIVE_SUBSTRINGS: &[&str] = &[ "token", "secret", @@ -266,8 +306,10 @@ const IDENTITY_SENSITIVE_SUBSTRINGS: &[&str] = &[ "bearer", ]; +#[cfg(feature = "sys-modules")] const IDENTITY_REDACTED_TOKEN: &str = ""; +#[cfg(feature = "sys-modules")] fn redact_identity_attr(name: &str, value: &serde_json::Value) -> serde_json::Value { let lower = name.to_lowercase(); if IDENTITY_SENSITIVE_SUBSTRINGS @@ -291,6 +333,7 @@ fn redact_identity_attr(name: &str, value: &serde_json::Value) -> serde_json::Va /// compatibility with pre-D-31 consumers. /// /// The `data` argument is mutated in place and returned for ergonomic chaining. +#[cfg(feature = "sys-modules")] pub(crate) fn augment_with_context_identity( mut data: serde_json::Value, ctx: &crate::context::Context, @@ -380,7 +423,9 @@ pub struct SysModulesContext { /// Startup results for the client, alongside the public registration context. #[derive(Default)] -pub(crate) struct SysModulesStartup { +#[cfg(feature = "sys-modules")] +pub(crate) struct SysModulesStartup<'a> { + pub(crate) subscribers: Option<&'a SubscriberRegistry>, pub(crate) events_enabled: bool, pub(crate) errors: Vec, } @@ -396,6 +441,7 @@ pub(crate) struct SysModulesStartup { /// `overrides_path`, and `fail_on_error` parameters in the Python and /// TypeScript SDKs. #[derive(Default, Clone)] +#[cfg(feature = "sys-modules")] pub struct SysModulesOptions { /// When set, runtime overrides are loaded from this YAML path on startup /// and persisted on every `update_config` / `toggle_feature` call. Use @@ -446,6 +492,7 @@ pub struct SysModulesOptions { /// 4. Create `UsageCollector` + `UsageMiddleware`. /// 5. Register health, manifest, and usage modules. /// 6. If `sys_modules.events.enabled`: register control modules + `EventEmitter`. +#[cfg(feature = "sys-modules")] pub fn register_sys_modules( registry: Arc, executor: &Executor, @@ -463,6 +510,7 @@ pub fn register_sys_modules( /// Variant of [`register_sys_modules`] accepting hardening options. See /// [`SysModulesOptions`] for details. +#[cfg(feature = "sys-modules")] pub fn register_sys_modules_with_options( registry: Arc, executor: &Executor, @@ -481,15 +529,45 @@ pub fn register_sys_modules_with_options( ) } +#[cfg(feature = "sys-modules")] +fn configured_usage_collector(config: &Config) -> Result { + let invalid = |message| SysModuleError::RegistrationFailed { + module_id: "system.usage.summary".to_owned(), + source: ModuleError::new(ErrorCode::ConfigInvalid, message), + }; + + if config + .get_declared("sys_modules.usage.bucketing_strategy") + .is_some_and(|strategy| strategy.as_str() != Some("hourly")) + { + return Err(invalid( + "sys_modules.usage.bucketing_strategy must be 'hourly'", + )); + } + + let Some(hours) = config.get_declared("sys_modules.usage.retention_hours") else { + return Ok(UsageCollector::new()); + }; + let retention = hours + .as_i64() + .filter(|hours| *hours > 0) + .and_then(chrono::Duration::try_hours) + .ok_or_else(|| { + invalid("sys_modules.usage.retention_hours must be a positive number of hours") + })?; + Ok(UsageCollector::with_retention(retention)) +} + #[allow(clippy::too_many_lines)] // complex orchestration; extraction would obscure the registration flow #[allow(clippy::needless_pass_by_value)] // Arc and Option consumed by sub-modules +#[cfg(feature = "sys-modules")] pub(crate) fn register_sys_modules_for_client( registry: Arc, executor: &Executor, config: &Config, metrics_collector: Option, options: SysModulesOptions, - startup: &mut SysModulesStartup, + startup: &mut SysModulesStartup<'_>, executor_supplied: bool, ) -> Result { let SysModulesOptions { @@ -561,6 +639,8 @@ pub(crate) fn register_sys_modules_for_client( ); } + let usage_collector = configured_usage_collector(&effective_config)?; + // --- Step 2: ErrorHistory + middleware --- #[allow(clippy::cast_possible_truncation)] // config value won't exceed platform usize limits let max_per_module = effective_config @@ -579,7 +659,6 @@ pub(crate) fn register_sys_modules_for_client( } // --- Step 3: UsageCollector + middleware --- - let usage_collector = UsageCollector::new(); let usage_middleware = UsageMiddleware::new(usage_collector.clone()); if let Err(e) = executor.use_middleware(Box::new(usage_middleware)) { tracing::error!(error = %e, middleware = "UsageMiddleware", "sys middleware registration failed"); @@ -619,11 +698,18 @@ pub(crate) fn register_sys_modules_for_client( } if events_enabled { + let builtins; + let subscribers = if let Some(registry) = startup.subscribers { + registry + } else { + builtins = SubscriberRegistry::new(); + &builtins + }; // Configured subscribers share the bootstrap emitter through weak circuit sinks. if let Some(subs) = effective_config.get("sys_modules.events.subscribers") { if let Some(arr) = subs.as_array() { for sub_config in arr { - match create_subscriber(sub_config) { + match subscribers.create(sub_config) { Ok(subscriber) => { let circuit = sub_config.get("circuit_breaker"); let value = |key: &str, default: u64| { diff --git a/rust/src/version.rs b/rust/src/version.rs index 5e70ab19..f1f7cad4 100644 --- a/rust/src/version.rs +++ b/rust/src/version.rs @@ -5,7 +5,9 @@ use std::cmp::Ordering; use crate::errors::{ErrorCode, ModuleError, VersionIncompatibleError}; +#[cfg(feature = "config")] const CURRENT_DOCUMENT_VERSION: &str = "2.1.0"; +#[cfg(feature = "config")] const LEGACY_DOCUMENT_VERSION: &str = "1.66.0"; const DEPRECATION_THRESHOLD: u64 = 2; @@ -176,6 +178,7 @@ pub fn negotiate_version(declared_version: &str, sdk_version: &str) -> Result Result<(), ModuleError> { let declared = declared.trim(); // Early configuration examples used a short major.minor version. diff --git a/rust/tests/apcore_client_spec.rs b/rust/tests/apcore_client_spec.rs index f47128cf..3fde13c2 100644 --- a/rust/tests/apcore_client_spec.rs +++ b/rust/tests/apcore_client_spec.rs @@ -896,7 +896,12 @@ async fn disable_error_sys_modules_disabled() { // clause: apcore_client.disable.input.reason.default #[tokio::test] async fn disable_input_reason_default() { - let client = APCore::with_config(sys_config()); + let client = APCore::try_start(apcore::APCoreOptions { + config: Some(sys_config()), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); client .register("risky.module", Box::new(EchoModule)) .expect("register risky.module"); @@ -912,7 +917,12 @@ async fn disable_input_reason_default() { // clause: apcore_client.disable.property.idempotent_true #[tokio::test] async fn disable_property_idempotent_true() { - let client = APCore::with_config(sys_config()); + let client = APCore::try_start(apcore::APCoreOptions { + config: Some(sys_config()), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); client .register("risky.dup", Box::new(EchoModule)) .expect("register risky.dup"); @@ -955,7 +965,12 @@ async fn enable_error_sys_modules_disabled() { // clause: apcore_client.enable.input.reason.default #[tokio::test] async fn enable_input_reason_default() { - let client = APCore::with_config(sys_config()); + let client = APCore::try_start(apcore::APCoreOptions { + config: Some(sys_config()), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); client .register("risky.enable", Box::new(EchoModule)) .expect("register risky.enable"); @@ -975,7 +990,12 @@ async fn enable_input_reason_default() { // clause: apcore_client.enable.property.idempotent_true #[tokio::test] async fn enable_property_idempotent_true() { - let client = APCore::with_config(sys_config()); + let client = APCore::try_start(apcore::APCoreOptions { + config: Some(sys_config()), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); client .register("risky.reenable", Box::new(EchoModule)) .expect("register risky.reenable"); diff --git a/rust/tests/conformance_test.rs b/rust/tests/conformance_test.rs index c74da840..5949dff7 100644 --- a/rust/tests/conformance_test.rs +++ b/rust/tests/conformance_test.rs @@ -2035,6 +2035,11 @@ async fn conformance_approval_gate() { let resume_arguments = Arc::new(std::sync::Mutex::new(None)); let resume = tc.get("resume"); let mut executor = Executor::new(Arc::clone(®istry), Arc::new(Config::default())); + if let Some(policy) = tc.get("execution_policy") { + executor.set_policy(Some( + apcore::ExecutionPolicy::from_value(policy.clone()).unwrap(), + )); + } if tc["approval_handler_configured"].as_bool().unwrap() { let raw = &tc["approval_result"]; let mut result = ApprovalResult::default(); @@ -3677,7 +3682,7 @@ async fn conformance_toggle_state_isolation() { use apcore::context::Context; use apcore::errors::ModuleError; use apcore::module::Module; - use apcore::APCore; + use apcore::{APCore, APCoreOptions, AutoApproveHandler}; use async_trait::async_trait; use serde_json::json; use std::collections::{HashMap, HashSet}; @@ -3748,7 +3753,12 @@ async fn conformance_toggle_state_isolation() { let mut instances: HashMap = HashMap::new(); for name in tc["instances"].as_array().unwrap() { let name = name.as_str().unwrap().to_string(); - let client = APCore::with_config(sys_config()); + let client = APCore::try_start(APCoreOptions { + config: Some(sys_config()), + approval_handler: Some(Box::new(AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); register_modules(&client); instances.insert(name, client); } diff --git a/rust/tests/core_profile.rs b/rust/tests/core_profile.rs new file mode 100644 index 00000000..12362802 --- /dev/null +++ b/rust/tests/core_profile.rs @@ -0,0 +1,194 @@ +//! Public in-memory assembly exercised independently of optional extensions. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use apcore::{ + ACLRule, APCore, APCoreOptions, ApprovalRequirement, ChunkStream, Config, Context, + ExecutionPolicy, Executor, Module, ModuleAnnotations, ModuleError, Registry, StreamEndReason, + ACL, +}; +use async_trait::async_trait; +use futures_util::{stream, StreamExt}; +use serde_json::{json, Value}; + +#[path = "conformance_env.rs"] +mod conformance_env; + +#[derive(Default)] +struct Report { + annotations: ModuleAnnotations, + executions: Arc, +} + +#[async_trait] +impl Module for Report { + fn description(&self) -> &'static str { + "Return a synthetic report" + } + + fn input_schema(&self) -> Value { + json!({"type": "object"}) + } + + fn output_schema(&self) -> Value { + json!({"type": "object", "required": ["report"]}) + } + + fn annotations(&self) -> ModuleAnnotations { + self.annotations.clone() + } + + async fn execute( + &self, + inputs: Value, + _context: &Context, + ) -> Result { + self.executions.fetch_add(1, Ordering::Relaxed); + Ok(json!({"report": inputs})) + } + + fn stream(&self, _inputs: Value, _context: &Context) -> Option { + Some(Box::pin(stream::iter([ + Ok(json!({"report": 1})), + Ok(json!({"report": 2})), + ]))) + } +} + +#[tokio::test] +async fn in_memory_assembly_invokes_streams_and_shuts_down() { + let client = APCore::new(); + assert_eq!(client.config.project_root(), std::path::Path::new(".")); + assert_eq!(client.list_modules(None, None), Vec::::new()); + assert!(!client.executor().governance_state().acl_configured); + client + .register("demo.report", Box::new(Report::default())) + .unwrap(); + + let value = client + .call("demo.report", json!({"value": 1}), None, None) + .await + .unwrap(); + assert_eq!(value, json!({"report": {"value": 1}})); + + let (mut chunks, completion) = client.stream_with_completion("demo.report", None, None, None); + assert_eq!(chunks.next().await.unwrap().unwrap(), json!({"report": 1})); + assert_eq!(chunks.next().await.unwrap().unwrap(), json!({"report": 2})); + assert!(chunks.next().await.is_none()); + let completed = completion.await; + assert_eq!(completed.reason, StreamEndReason::Completed); + assert_eq!(completed.output.unwrap(), json!({"report": 2})); + + client.shutdown().await.unwrap(); + assert_eq!(client.list_modules(None, None), Vec::::new()); +} + +#[cfg(not(feature = "config"))] +#[tokio::test] +async fn missing_file_configuration_feature_disables_configured_acl_calls() { + use apcore::{APCoreStartupError, ErrorCode}; + + let mut options = Config::in_memory(); + options.set("acl.root", json!("acl.yaml")); + let startup = APCore::try_start(APCoreOptions { + config: Some(options.clone()), + ..APCoreOptions::default() + }); + assert!(matches!( + startup, + Err(APCoreStartupError::AclLoadFailed { .. }) + )); + + let client = APCore::with_config(options); + client + .register("demo.report", Box::new(Report::default())) + .unwrap(); + let result = client.call("demo.report", json!({}), None, None).await; + assert_eq!(result.unwrap_err().code, ErrorCode::ConfigInvalid); +} + +#[tokio::test] +async fn core_profile_governance_matches_shared_fixture() { + let path = conformance_env::find_fixtures_root().join("core_profile_governance.json"); + let fixture: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + for case in fixture["test_cases"].as_array().unwrap() { + let id = case["id"].as_str().unwrap(); + let input = &case["input"]; + let expected = &case["expected"]; + let client = governance_client(input); + let executions = Arc::new(AtomicUsize::new(0)); + client + .register( + "demo.report", + Box::new(Report { + annotations: ModuleAnnotations { + requires_approval: input["approval_source"] == "annotation", + destructive: input["approval_source"] == "destructive", + ..ModuleAnnotations::default() + }, + executions: Arc::clone(&executions), + }), + ) + .unwrap(); + + let preflight = client.validate("demo.report", None, None).await.unwrap(); + let result = client.call("demo.report", json!({}), None, None).await; + let code = result.err().map_or(Value::Null, |error| json!(error.code)); + assert_eq!( + json!(preflight.requires_approval), + expected["requires_approval"], + "{id}" + ); + assert_eq!(code, expected["error_code"], "{id}"); + assert_eq!( + json!(executions.load(Ordering::Relaxed)), + expected["executions"], + "{id}" + ); + } +} + +fn governance_client(input: &Value) -> APCore { + let mut config = Config::in_memory(); + config.set("acl.root", Value::Null); + let policy = if input["approval_source"] == "policy_rule" { + Some(json!({"rules": [{"pattern": "demo.report", "requires_approval": true}]})) + } else { + input.get("execution_policy").cloned() + } + .map(|policy| ExecutionPolicy::from_value(policy).unwrap()); + let acl = (input["approval_source"] == "acl").then(|| { + let mut rule = ACLRule::new(vec!["*".into()], vec!["demo.report".into()], "allow"); + rule.approval = Some(ApprovalRequirement::Required); + ACL::try_new(vec![rule], "deny", None).unwrap() + }); + + if acl.is_some() || input["client"] == "injected_executor" { + let executor = Executor::with_options(Registry::new(), config.clone(), None, acl, None); + APCore::with_options(None, Some(executor), Some(config), None) + } else if policy.is_some() { + APCore::try_start(APCoreOptions { + config: Some(config), + policy, + ..APCoreOptions::default() + }) + .unwrap() + } else { + APCore::new() + } +} + +#[test] +fn a_custom_strategy_without_the_builtin_gate_reports_that_boundary() { + use apcore::build_minimal_strategy; + + let executor = Executor::with_strategy( + Registry::new(), + Config::in_memory(), + build_minimal_strategy(), + ); + let state = executor.governance_state(); + assert!(state.policy_strict); + assert!(!state.builtin_approval_gate_wired); +} diff --git a/rust/tests/event_system_spec.rs b/rust/tests/event_system_spec.rs index 434b57c2..7500e68e 100644 --- a/rust/tests/event_system_spec.rs +++ b/rust/tests/event_system_spec.rs @@ -17,7 +17,6 @@ // - SubscriberCircuitBreaker.on_failure (Rust: CircuitBreakerWrapper) // - EventEmitter.unsubscribe // - EventEmitter.flush -// - A2ASubscriber.deliver // // Symbol-reality notes (drive the skip / ignore decisions below): // - `EventEmitter::emit` takes `&ApCoreEvent` and is fire-and-forget; it @@ -25,7 +24,7 @@ // `input.event_type.not_empty` rule is not enforced. // - The Rust `EventEmitter::emit` is `async` (unlike Python's sync emit), so // `property.async` for emit asserts the async, non-blocking contract. -// - `WebhookSubscriber` / `A2ASubscriber` deliver via `on_event` (not a +// - `WebhookSubscriber` delivers via `on_event` (not a // `deliver` method). The HTTP path is gated behind the `events` cargo // feature. The emitter owns retries and dead-letter delivery. // - The circuit-breaker contract names `SubscriberCircuitBreaker.on_failure` @@ -924,132 +923,6 @@ async fn flush_property_idempotent() { assert_eq!((after_first, after_second), (1, 1)); } -// =========================================================================== -// Contract: A2ASubscriber.deliver -// =========================================================================== - -// clause: event_system.deliver.error.ImportError_a2a -#[test] -#[ignore = "event_system.deliver.error.ImportError_a2a: Python-only ImportError when aiohttp is absent; Rust gates the HTTP path behind the `events` cargo feature at compile time, so there is no runtime missing-dependency error to assert"] -fn a2a_deliver_error_import_error_without_aiohttp() { - // Python raises ImportError synchronously if aiohttp is not installed. Rust - // resolves the HTTP dependency at compile time via the `events` feature, so - // there is no equivalent runtime contract. See ignore reason. - unreachable!(); -} - -// The remaining A2ASubscriber.deliver clauses exercise the real HTTP path, -// gated behind the `events` cargo feature. -#[cfg(feature = "events")] -mod a2a_deliver { - use super::webhook_deliver::MockServer; - use super::*; - use apcore::events::subscribers::{A2AAuth, A2ASubscriber}; - use std::collections::HashMap; - - // clause: event_system.deliver.input.event.required_a2a - #[tokio::test(flavor = "multi_thread")] - async fn a2a_deliver_input_event_required() { - // A2A delivery POSTs a {skillId, event} wrapper carrying the event. - let server = MockServer::spawn("200 OK").await; - let sub = A2ASubscriber::new("a2a", &server.url, "*"); - let event = make_event_with("apcore.health.recovered", json!({})); - sub.on_event(&event).await.expect("2xx must be Ok"); - assert_eq!(server.request_count(), 1); - let body = server.last_json(); - assert_eq!(body["skillId"], "apevo.event_receiver"); - assert_eq!(body["event"]["event_type"], "apcore.health.recovered"); - } - - // clause: event_system.deliver.property.async_a2a - #[tokio::test(flavor = "multi_thread")] - async fn a2a_deliver_property_async() { - // A2A delivery is awaitable and resolves to Ok(()). - let server = MockServer::spawn("200 OK").await; - let sub = A2ASubscriber::new("a2a", &server.url, "*"); - let result = sub.on_event(&make_event()).await; - assert!(result.is_ok()); - } - - // clause: event_system.deliver.property.thread_safe_a2a - #[tokio::test(flavor = "multi_thread")] - async fn a2a_deliver_property_thread_safe() { - // >=8 concurrent A2A deliveries with distinct events all resolve; each - // issues its own POST. - let server = MockServer::spawn("200 OK").await; - let sub = Arc::new(A2ASubscriber::new("a2a", &server.url, "*")); - let mut handles = Vec::new(); - for i in 0..8usize { - let s = Arc::clone(&sub); - handles.push(tokio::spawn(async move { - let event = make_event_with("apcore.test.event", json!({ "i": i })); - s.on_event(&event).await - })); - } - for h in handles { - h.await.unwrap().expect("delivery must resolve Ok"); - } - assert_eq!(server.request_count(), 8); - } - - // clause: event_system.deliver.property.pure_a2a - #[tokio::test(flavor = "multi_thread")] - async fn a2a_deliver_property_pure() { - // Delivery is NOT pure: it performs an outbound HTTP POST to the URL. - let server = MockServer::spawn("200 OK").await; - let sub = A2ASubscriber::new("a2a", &server.url, "*"); - sub.on_event(&make_event()).await.unwrap(); - assert_eq!(server.request_count(), 1); - } - - // clause: event_system.deliver.side_effect.1.auth_modes_a2a - #[tokio::test(flavor = "multi_thread")] - async fn a2a_deliver_side_effect_1_auth_modes() { - // Observable auth policy: Bearer auth -> 'Authorization: Bearer '; - // Headers auth -> keys merged into headers; None -> no auth header. - // The mock server here counts requests and confirms each auth mode - // delivers successfully (the auth header is applied client-side before - // send; a 200 reply confirms the request was well-formed). - let server_bearer = MockServer::spawn("200 OK").await; - let mut sub_bearer = A2ASubscriber::new("a2a", &server_bearer.url, "*"); - sub_bearer.auth = Some(A2AAuth::Bearer("tok123".to_string())); - sub_bearer.on_event(&make_event()).await.expect("bearer ok"); - assert_eq!(server_bearer.request_count(), 1); - - let server_dict = MockServer::spawn("200 OK").await; - let mut headers = HashMap::new(); - headers.insert("X-Api-Key".to_string(), "k".to_string()); - let mut sub_dict = A2ASubscriber::new("a2a", &server_dict.url, "*"); - sub_dict.auth = Some(A2AAuth::Headers(headers)); - sub_dict.on_event(&make_event()).await.expect("dict ok"); - assert_eq!(server_dict.request_count(), 1); - - let server_none = MockServer::spawn("200 OK").await; - let sub_none = A2ASubscriber::new("a2a", &server_none.url, "*"); - // auth defaults to None. - assert!(sub_none.auth.is_none()); - sub_none.on_event(&make_event()).await.expect("none ok"); - assert_eq!(server_none.request_count(), 1); - } - - // clause: event_system.deliver.side_effect.2.retry_on_5xx_a2a - #[tokio::test(flavor = "multi_thread")] - async fn a2a_deliver_side_effect_2_retry_on_5xx() { - // Observable HTTP-status policy for A2A: 5xx returns Err (emitter - // retries); 4xx returns Ok (no retry). - let server_5xx = MockServer::spawn("502 Bad Gateway").await; - let sub5 = A2ASubscriber::new("a2a", &server_5xx.url, "*"); - let res5 = sub5.on_event(&make_event()).await; - assert!(res5.is_err(), "5xx must surface as Err for emitter retry"); - assert_eq!(res5.unwrap_err().code, ErrorCode::GeneralInternalError); - - let server_4xx = MockServer::spawn("403 Forbidden").await; - let sub4 = A2ASubscriber::new("a2a", &server_4xx.url, "*"); - let res4 = sub4.on_event(&make_event()).await; - assert!(res4.is_ok(), "4xx is permanent: Ok, not retried"); - } -} - // --------------------------------------------------------------------------- // sync-2026-08-26 A-D-025: removal must be able to name exactly one subscriber. // --------------------------------------------------------------------------- diff --git a/rust/tests/it.rs b/rust/tests/it.rs index b731d7bd..7e1dee91 100644 --- a/rust/tests/it.rs +++ b/rust/tests/it.rs @@ -191,8 +191,6 @@ mod test_context_key; mod test_context_key_promotion; #[path = "test_context_keys.rs"] mod test_context_keys; -#[path = "test_context_logger_deprecation.rs"] -mod test_context_logger_deprecation; #[path = "test_context_logger_schema.rs"] mod test_context_logger_schema; #[path = "test_crate_root_exports.rs"] diff --git a/rust/tests/observability_spec.rs b/rust/tests/observability_spec.rs index 0bc57934..60051fc8 100644 --- a/rust/tests/observability_spec.rs +++ b/rust/tests/observability_spec.rs @@ -9,7 +9,7 @@ //! 2. `MetricsEmitter.record` — MISSING SYMBOL in apcore-rust (no //! `MetricsEmitter` type; the SDK exposes `MetricsCollector` instead). //! Ignored. -//! 3. `PrometheusExporter.export`— PRESENT and fully exercised. +//! 3. `render_prometheus_metrics` — PRESENT and fully exercised. //! //! Each test fn name is the clause-id flattened to snake_case and carries the //! verbatim clause-id in a leading `// clause:` comment so cross-language diffs @@ -17,19 +17,12 @@ //! //! These tests are READ-ONLY contract verification — they never modify src/. -use apcore::observability::{MetricsCollector, PrometheusExporter}; +use apcore::observability::{render_prometheus_metrics, MetricsCollector}; -// --------------------------------------------------------------------------- -// Helper: build an exporter over a collector carrying a single known counter. -// -// Note (Rust-actual): `PrometheusExporter::new(collector)` takes the collector -// BY VALUE. `MetricsCollector` is `Clone` and internally `Arc`-shared, so a -// clone retained before the move is a live handle onto the same state. -// --------------------------------------------------------------------------- -fn exporter_with_one_counter() -> PrometheusExporter { +fn collector_with_one_counter() -> MetricsCollector { let collector = MetricsCollector::new(); collector.increment_calls("math.add", "success"); - PrometheusExporter::new(collector) + collector } // =========================================================================== @@ -99,23 +92,16 @@ fn observability_record_property_pure() { } // =========================================================================== -// Contract 3: PrometheusExporter.export (PRESENT — fully exercised) -// -// Rust-actual: the `collector` from the contract's ### Inputs is supplied at -// construction (`PrometheusExporter::new(collector)`), and `export()` takes no -// arguments and returns the Prometheus text `String`. +// Contract 3: Prometheus text rendering // =========================================================================== // clause: observability.export.input.collector.required #[test] fn observability_export_input_collector_required() { - // Rust enforces the required `collector` at compile time: `new()` cannot be - // called without it (no runtime negative path exists). Positive: a supplied - // collector's data is what `export()` renders. + // The renderer reads metrics from the collector supplied by the caller. let collector = MetricsCollector::new(); collector.increment_calls("math.add", "success"); - let exporter = PrometheusExporter::new(collector); - let text = exporter.export(); + let text = render_prometheus_metrics(&collector, None); assert!(text.contains("apcore_module_calls_total")); assert!(text.contains("module_id=\"math.add\"")); assert!(text.contains("status=\"success\"")); @@ -127,8 +113,7 @@ fn observability_export_error_none() { // ### Errors: None — export errors MUST NOT propagate. `export()` returns a // plain `String` (no `Result`); exporting over an empty collector must not // panic and must yield a string. - let exporter = PrometheusExporter::new(MetricsCollector::new()); - let text = exporter.export(); + let text = render_prometheus_metrics(&MetricsCollector::new(), None); // A `String` is always returned; the three required metric names are present // even on a cold/empty collector (spec §1.6). assert!(text.contains("apcore_module_calls_total")); @@ -139,8 +124,8 @@ fn observability_export_error_none() { fn observability_export_returns_prometheus_text() { // ### Returns: Prometheus text exposition format, UTF-8. A Rust `String` is // UTF-8 by construction; assert the canonical HELP/TYPE comment lines. - let exporter = exporter_with_one_counter(); - let text = exporter.export(); + let collector = collector_with_one_counter(); + let text = render_prometheus_metrics(&collector, None); // Round-trips through UTF-8 without loss (String is valid UTF-8 by type). assert_eq!(String::from_utf8(text.clone().into_bytes()).unwrap(), text); assert!(text.contains("# HELP apcore_module_calls_total")); @@ -153,8 +138,8 @@ fn observability_export_property_async() { // ### Properties: async: false. `export()` is a plain synchronous call // returning a concrete `String` (not a Future). If it were async this would // not type-check as a direct `String`. - let exporter = exporter_with_one_counter(); - let result: String = exporter.export(); + let collector = collector_with_one_counter(); + let result: String = render_prometheus_metrics(&collector, None); assert!(result.contains("apcore_module_calls_total")); } @@ -164,12 +149,14 @@ async fn observability_export_property_thread_safe() { // ### Properties: thread_safe: true. Launch N (>=8) concurrent exports over // a shared exporter; assert no panic and every snapshot is identical. use std::sync::Arc; - let exporter = Arc::new(exporter_with_one_counter()); + let collector = Arc::new(collector_with_one_counter()); let mut handles = Vec::new(); for _ in 0..12 { - let ex = exporter.clone(); - handles.push(tokio::spawn(async move { ex.export() })); + let collector = Arc::clone(&collector); + handles.push(tokio::spawn(async move { + render_prometheus_metrics(&collector, None) + })); } let mut results = Vec::new(); @@ -190,24 +177,19 @@ fn observability_export_property_pure() { // must NOT mutate the collector (a query), yet MUST reflect subsequent // mutations of the live collector — proving it reads live state. // - // Rust-actual: the exporter takes the collector by value, but - // `MetricsCollector` is `Clone` + `Arc`-shared, so a retained clone is a - // live handle onto the same internal state. let collector = MetricsCollector::new(); collector.increment_calls("math.add", "success"); - let live = collector.clone(); - let exporter = PrometheusExporter::new(collector); - let before = live.snapshot(); - let first = exporter.export(); - let after = live.snapshot(); + let before = collector.snapshot(); + let first = render_prometheus_metrics(&collector, None); + let after = collector.snapshot(); // export() is a query: it does not mutate collector state. assert_eq!(before, after); assert!(first.contains("math.add")); // Live-state coupling: a new module appears on the next export. - live.increment_calls("math.sub", "success"); - let second = exporter.export(); + collector.increment_calls("math.sub", "success"); + let second = render_prometheus_metrics(&collector, None); assert!(second.contains("module_id=\"math.sub\"")); assert!(!first.contains("module_id=\"math.sub\"")); } @@ -217,9 +199,9 @@ fn observability_export_property_pure() { fn observability_export_property_idempotent() { // ### Properties: idempotent: true. Two successive calls with unchanged // collector state MUST produce identical output and leave state identical. - let exporter = exporter_with_one_counter(); - let first = exporter.export(); - let second = exporter.export(); + let collector = collector_with_one_counter(); + let first = render_prometheus_metrics(&collector, None); + let second = render_prometheus_metrics(&collector, None); assert_eq!(first, second); assert!(!first.is_empty()); } diff --git a/rust/tests/policy_governance.rs b/rust/tests/policy_governance.rs index 419d372c..7be0ffb0 100644 --- a/rust/tests/policy_governance.rs +++ b/rust/tests/policy_governance.rs @@ -298,10 +298,9 @@ async fn strict_policy_without_gated_modules_executes() { } #[tokio::test] -async fn no_handler_skips_but_still_executes() { - // Fail-loud default: requires_approval without a handler skips per spec §7.4 - // (warns once, not asserted here — Rust has no caplog) but still executes. - let exec = executor(make_registry()); +async fn nonstrict_policy_without_handler_skips_but_still_executes() { + let mut exec = executor(make_registry()); + exec.set_policy(Some(ExecutionPolicy::default().with_strict(false))); for _ in 0..2 { let out = exec .call("admin.reset", json!({}), None, None) @@ -312,8 +311,11 @@ async fn no_handler_skips_but_still_executes() { } #[tokio::test] -async fn destructive_ungated_still_executes() { - let exec = executor(make_registry()); +async fn destructive_opt_out_still_executes() { + let mut exec = executor(make_registry()); + exec.set_policy(Some( + ExecutionPolicy::default().with_gate_destructive(false), + )); let out = exec .call("orders.delete_order", json!({}), None, None) .await @@ -342,7 +344,9 @@ async fn gate_destructive_covers_destructive_module() { async fn set_policy_at_runtime() { let mut exec = executor(make_registry()); exec.set_approval_handler(Box::new(AlwaysDenyHandler)); - // No policy yet: orders.delete_order declares requires_approval=false, executes. + exec.set_policy(Some( + ExecutionPolicy::default().with_gate_destructive(false), + )); assert_eq!( exec.call("orders.delete_order", json!({}), None, None) .await @@ -362,12 +366,11 @@ async fn set_policy_at_runtime() { assert_eq!(err.code, ErrorCode::ApprovalDenied); exec.set_policy(None); - assert_eq!( - exec.call("orders.delete_order", json!({}), None, None) - .await - .unwrap()["status"], - "executed" - ); + let err = exec + .call("orders.delete_order", json!({}), None, None) + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::ApprovalDenied); } #[tokio::test] @@ -529,7 +532,8 @@ async fn no_events_when_gate_not_involved() { #[tokio::test] async fn no_decision_event_when_gate_skipped_without_handler() { // Non-strict skip (spec §7.4) emits no decision event. - let (exec, events, emitter) = executor_with_emitter(make_registry()); + let (mut exec, events, emitter) = executor_with_emitter(make_registry()); + exec.set_policy(Some(ExecutionPolicy::default().with_strict(false))); exec.call("admin.reset", json!({}), None, None) .await .unwrap(); diff --git a/rust/tests/test_client.rs b/rust/tests/test_client.rs index c4f4bd03..a2dc2b07 100644 --- a/rust/tests/test_client.rs +++ b/rust/tests/test_client.rs @@ -67,6 +67,38 @@ async fn test_apcore_register_and_call_round_trip() { assert_eq!(result["echoed"]["hello"], "world"); } +#[test] +fn test_system_startup_uses_its_own_subscriber_registry_in_nested_filters() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use apcore::{EventSubscriber, StdoutSubscriber, SubscriberRegistry}; + + let calls = Arc::new(AtomicUsize::new(0)); + let mut subscribers = SubscriberRegistry::new(); + let registered_calls = Arc::clone(&calls); + subscribers.register("fixture", move |_| { + registered_calls.fetch_add(1, Ordering::Relaxed); + Ok(Box::new(StdoutSubscriber::new()) as Box) + }); + let filter = json!({"type": "filter", "delegate_type": "fixture"}); + assert!(SubscriberRegistry::new().create(&filter).is_err()); + + let mut config = Config::default(); + config.set("sys_modules.enabled", json!(true)); + config.set("sys_modules.events.enabled", json!(true)); + config.set("sys_modules.events.subscribers", json!([filter])); + let client = APCore::try_start_with_subscribers( + APCoreOptions { + config: Some(config), + ..Default::default() + }, + &subscribers, + ) + .unwrap(); + assert!(client.sys_modules_errors().is_empty()); + assert_eq!(calls.load(Ordering::Relaxed), 1); +} + #[tokio::test] async fn test_supplied_executor_keeps_its_toggle_state() { let state = Arc::new(apcore::sys_modules::ToggleState::new()); @@ -224,7 +256,12 @@ async fn test_apcore_disable_enable_signature_takes_reason() { let mut config = Config::default(); config.set("sys_modules.enabled", json!(true)); config.set("sys_modules.events.enabled", json!(true)); - let apcore = APCore::with_config(config); + let apcore = APCore::try_start(apcore::APCoreOptions { + config: Some(config), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); // Unique id: the disabled-set is a process-global ToggleState (A-D-12). let module_id = "demo.toggle.signature_test"; diff --git a/rust/tests/test_compute_delay_ms.rs b/rust/tests/test_compute_delay_ms.rs index 449f167d..dd2797bf 100644 --- a/rust/tests/test_compute_delay_ms.rs +++ b/rust/tests/test_compute_delay_ms.rs @@ -1,11 +1,10 @@ //! Sync alignment (D-08): the canonical retry-delay method is named -//! `compute_delay_ms`. The legacy `delay_for_attempt` is retained as a -//! `#[deprecated]` alias for one minor version. +//! `compute_delay_ms`. use apcore::async_task::RetryConfig; #[test] -fn compute_delay_ms_method_exists_and_matches_legacy() { +fn compute_delay_ms_applies_backoff_and_cap() { let mut cfg = RetryConfig::default(); cfg.max_retries = 5; cfg.retry_delay_ms = 1000; @@ -18,15 +17,3 @@ fn compute_delay_ms_method_exists_and_matches_legacy() { assert_eq!(cfg.compute_delay_ms(4), 16_000); assert_eq!(cfg.compute_delay_ms(5), 30_000); // cap } - -#[test] -#[allow(deprecated)] -fn delay_for_attempt_legacy_alias_still_works() { - let mut cfg = RetryConfig::default(); - cfg.max_retries = 3; - cfg.retry_delay_ms = 500; - cfg.backoff_multiplier = 2.0; - cfg.max_retry_delay_ms = 10_000; - assert_eq!(cfg.delay_for_attempt(0), cfg.compute_delay_ms(0)); - assert_eq!(cfg.delay_for_attempt(2), cfg.compute_delay_ms(2)); -} diff --git a/rust/tests/test_context_logger_deprecation.rs b/rust/tests/test_context_logger_deprecation.rs deleted file mode 100644 index 5aa1ad43..00000000 --- a/rust/tests/test_context_logger_deprecation.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! `Context::logger` is deprecated (apcore#121), removed at v2.0. -//! -//! The decision is D-67's boundary applied to an API surface rather than a -//! configuration key: apcore does not own the host's logging policy, and this -//! method's output is fixed at stderr / `info` / JSON — notably NOT going -//! through `tracing`, so a host that configured a subscriber never sees it. -//! `ObsLoggingMiddleware` is deliberately NOT the migration target; it emits -//! apcore's execution events, a different facility. -//! -//! Rust states the notice in the type system rather than at runtime, so these -//! cases read the attribute and the call sites rather than a log line. - -/// The `#[deprecated]` attribute is the notice here, and it must say the three -/// things a caller needs: when it goes, where to go instead, and why the -/// obvious substitute is not it. -#[test] -fn the_deprecation_attribute_names_the_version_the_target_and_the_issue() { - let src = std::fs::read_to_string( - std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/context.rs"), - ) - .expect("context.rs is readable"); - let start = src - .find("#[deprecated(") - .expect("Context::logger must carry a #[deprecated] attribute"); - let attr = &src[start..start + 600.min(src.len() - start)]; - - assert!(attr.contains("since = \"0.31.0\""), "attribute: {attr}"); - assert!( - attr.contains("host application's logger"), - "attribute: {attr}" - ); - assert!(attr.contains("apcore#121"), "attribute: {attr}"); - assert!(attr.contains("Removed at v2.0"), "attribute: {attr}"); - // The one substitution a reader would otherwise reach for, ruled out where - // they will read it rather than only in the changelog. - assert!( - attr.contains("ObsLoggingMiddleware"), - "the note must say what ObsLoggingMiddleware is FOR, so a reader does \ - not treat it as a drop-in replacement: {attr}" - ); -} - -/// The premise of deprecating rather than wiring: nothing inside the crate uses -/// it. Written as a test rather than left as a claim in the issue, because it -/// is what makes removal at v2.0 safe for the framework itself — a future -/// caller inside `src/` fails here and has to argue for itself. -#[test] -fn no_apcore_code_path_reaches_it() { - fn walk(dir: &std::path::Path, hits: &mut Vec) { - for entry in std::fs::read_dir(dir).expect("readable dir").flatten() { - let path = entry.path(); - if path.is_dir() { - walk(&path, hits); - } else if path.extension().is_some_and(|e| e == "rs") { - let text = std::fs::read_to_string(&path).unwrap_or_default(); - for (n, line) in text.lines().enumerate() { - let calls = line.contains("ctx.logger()") || line.contains("context.logger()"); - // The definition itself, and prose about it, are not calls. - let is_prose = line.trim_start().starts_with("//"); - if calls && !is_prose { - hits.push(format!("{}:{}", path.display(), n + 1)); - } - } - } - } - } - let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - let mut hits = Vec::new(); - walk(&src, &mut hits); - assert!( - hits.is_empty(), - "apcore's own code now reaches Context::logger: {hits:?}" - ); -} - -/// A deprecation is a notice, not a removal — §13.2's two-minor floor. The -/// method keeps returning a logger carrying this context's correlation fields -/// until v2.0, so a project that has not migrated yet still runs. -#[test] -#[allow(deprecated)] -fn it_still_works_through_the_1_x_line() { - let identity = apcore::Identity::new( - "api.probe".to_string(), - "service".to_string(), - Vec::new(), - std::collections::HashMap::new(), - ); - let ctx: apcore::Context = apcore::Context::create( - Some(identity), - None, - None, - None, - serde_json::Value::Null, - None, - ); - let logger = ctx.logger(); - // Asserted against the CONTEXT's own fields rather than literals: carrying - // this context's correlation values is the whole contract of the accessor, - // and a literal would pin how `Context::create` derives them instead — - // which is a different question and one this case has no business fixing. - assert_eq!(logger.trace_id.as_deref(), Some(ctx.trace_id.as_str())); - assert_eq!(logger.caller_id, ctx.caller_id); - assert_eq!(logger.module_id, ctx.call_chain.last().cloned()); -} diff --git a/rust/tests/test_crate_root_exports.rs b/rust/tests/test_crate_root_exports.rs index ae61e976..927c2bba 100644 --- a/rust/tests/test_crate_root_exports.rs +++ b/rust/tests/test_crate_root_exports.rs @@ -129,6 +129,7 @@ fn test_other_required_exports_at_crate_root() { // Parity sweep — every symbol Python/TypeScript expose at the package root // should also be reachable from `apcore::*`. use apcore::{ + export_generic, // Bindings AutoSchemaValue, BindingEntry, @@ -147,7 +148,6 @@ fn test_other_required_exports_at_crate_root() { OTLPExporter, // Schema RefResolver, - SchemaExporter, SchemaLoader, SchemaValidator, Span, @@ -205,32 +205,20 @@ fn test_execution_cancelled_error_at_crate_root() { fn test_event_subscriber_types_at_crate_root() { // D1-001/D1-002: EventSubscriber trait and concrete subscriber types must be // accessible from the crate root without navigating internal module paths. - use apcore::{A2ASubscriber, EventSubscriber, WebhookSubscriber}; + use apcore::{EventSubscriber, WebhookSubscriber}; // Compile-time — constructing a concrete subscriber confirms the types resolve. let sub = WebhookSubscriber::new("wh1", "https://example.com/hook", "*"); - let _sub2 = A2ASubscriber::new("a2a1", "https://platform.example.com", "module.*"); // Verify trait object coercion works from crate root type path. let _: &dyn EventSubscriber = ⊂ } #[test] -fn test_subscriber_registry_functions_at_crate_root() { - // D1-002: create_subscriber, register_subscriber_type, unregister_subscriber_type, - // reset_subscriber_registry must all be accessible from the crate root, matching - // apcore-python create_subscriber_from_config/register_subscriber_factory and - // apcore-typescript createSubscriberFromConfig/registerSubscriberType at root. - use apcore::{ - create_subscriber, register_subscriber_type, reset_subscriber_registry, - unregister_subscriber_type, - }; - // reset_subscriber_registry restores built-ins — safe to call in tests. - reset_subscriber_registry(); - // Confirm the function signatures are callable with expected argument types. - let result = unregister_subscriber_type("nonexistent_type_xyz"); - assert!(result.is_err()); - // create_subscriber resolves at the crate root; an unknown type errors. - let made = create_subscriber(&serde_json::json!({"type": "nonexistent_type_xyz"})); - assert!(made.is_err()); +fn test_subscriber_registry_is_available_at_crate_root() { + use apcore::SubscriberRegistry; + + let registry = SubscriberRegistry::new(); + let made = registry.create(&serde_json::json!({"type": "stdout"})); + assert_eq!(made.unwrap().subscriber_type(), "stdout"); } #[test] diff --git a/rust/tests/test_event_delivery_conformance.rs b/rust/tests/test_event_delivery_conformance.rs index 03469744..609c2e2d 100644 --- a/rust/tests/test_event_delivery_conformance.rs +++ b/rust/tests/test_event_delivery_conformance.rs @@ -82,6 +82,7 @@ impl EventSubscriber for FailNSubscriber { #[derive(Debug)] struct AlwaysFailSubscriber { id: String, + subscriber_type: String, pattern: String, attempt_count: Arc, on_failure_count: Arc, @@ -90,6 +91,9 @@ struct AlwaysFailSubscriber { #[async_trait] impl EventSubscriber for AlwaysFailSubscriber { + fn subscriber_type(&self) -> &str { + &self.subscriber_type + } fn subscriber_id(&self) -> &str { &self.id } @@ -278,6 +282,10 @@ async fn conformance_permanent_failure_emits_dlq_event() { .unwrap() .to_string(); let sub = AlwaysFailSubscriber { + subscriber_type: case["setup"]["subscriber"]["type"] + .as_str() + .expect("subscriber type") + .to_string(), id: case["setup"]["subscriber"]["id"] .as_str() .unwrap() @@ -352,6 +360,10 @@ async fn conformance_permanent_failure_emits_dlq_event() { // Verify specific data values let data_contains = &case["expected"]["dlq_event"]["data_contains"]; + assert_eq!( + dlq.data["subscriber_type"], + data_contains["subscriber_type"] + ); assert_eq!( dlq.data["subscriber_id"].as_str(), data_contains["subscriber_id"].as_str(), @@ -390,6 +402,10 @@ async fn conformance_dlq_event_subscriber_failure_is_not_retried() { let primary_max = primary_cfg["max_attempts"].as_u64().unwrap() as u32; let primary_attempts = Arc::new(AtomicU32::new(0)); let primary_sub = AlwaysFailSubscriber { + subscriber_type: case["setup"]["primary_subscriber"]["type"] + .as_str() + .expect("subscriber type") + .to_string(), id: case["setup"]["primary_subscriber"]["id"] .as_str() .unwrap() @@ -410,6 +426,7 @@ async fn conformance_dlq_event_subscriber_failure_is_not_retried() { let dlq_cfg = &case["setup"]["dlq_subscriber"]["retry"]; let dlq_attempts = Arc::new(AtomicU32::new(0)); let dlq_sub = AlwaysFailSubscriber { + subscriber_type: "test_dlq".to_string(), id: case["setup"]["dlq_subscriber"]["id"] .as_str() .unwrap() @@ -535,6 +552,10 @@ async fn conformance_dlq_subscriber_failure_logs_at_error() { let primary_cfg = &case["setup"]["primary_subscriber"]["retry"]; let primary_sub = AlwaysFailSubscriber { + subscriber_type: case["setup"]["primary_subscriber"]["type"] + .as_str() + .expect("subscriber type") + .to_string(), id: case["setup"]["primary_subscriber"]["id"] .as_str() .unwrap() @@ -550,6 +571,7 @@ async fn conformance_dlq_subscriber_failure_logs_at_error() { }, }; let broken_dlq = AlwaysFailSubscriber { + subscriber_type: "test_dlq".to_string(), id: case["setup"]["dlq_subscriber"]["id"] .as_str() .unwrap() @@ -760,7 +782,7 @@ async fn conformance_declared_retry_policy_is_read_for_every_subscriber_type() { // The fixture's `every_type_or_the_case_is_half_done` contract: the defect // was NOT uniform — `webhook` parsed a different (flat) spelling while // `file` / `stdout` / `filter` had no `retry` field at all here, so a - // webhook-only assertion was green while four types ignored their config. + // webhook-only assertion would miss the other built-in types. let declared = case["subscribers"] .as_array() .expect("subscribers is an array"); diff --git a/rust/tests/test_event_management_hardening_conformance.rs b/rust/tests/test_event_management_hardening_conformance.rs index f9379631..5ce082c4 100644 --- a/rust/tests/test_event_management_hardening_conformance.rs +++ b/rust/tests/test_event_management_hardening_conformance.rs @@ -14,10 +14,6 @@ use std::sync::Arc; use async_trait::async_trait; use chrono::{DateTime, Utc}; -// parking_lot::Mutex is preferred over std::sync::Mutex in async tests because -// it sidesteps clippy's `await_holding_lock` warning while still being safe to -// hold during await points (we only need the lock for registry hygiene, never -// for cross-await coordination). use parking_lot::Mutex; use regex::Regex; use serde_json::{json, Value}; @@ -25,9 +21,7 @@ use serde_json::{json, Value}; use apcore::errors::{ErrorCode, ModuleError}; use apcore::events::circuit_breaker::{CircuitBreakerWrapper, CircuitEventSink, CircuitState}; use apcore::events::emitter::ApCoreEvent; -use apcore::events::subscribers::{ - create_subscriber, register_subscriber_type, reset_subscriber_registry, EventSubscriber, -}; +use apcore::events::subscribers::{create_subscriber, EventSubscriber, SubscriberRegistry}; // --------------------------------------------------------------------------- // Fixture loading (mirrors other conformance tests) @@ -68,14 +62,6 @@ fn parse_event(value: &Value) -> ApCoreEvent { // Test helpers — recording subscriber and circuit-event sink // --------------------------------------------------------------------------- -/// Tests that mutate the global subscriber-factory registry hold this lock to -/// avoid cross-test races. Mirrors the convention used in -/// `src/events/subscribers.rs`. -fn registry_lock() -> &'static Mutex<()> { - static LOCK: Mutex<()> = Mutex::new(()); - &LOCK -} - #[derive(Debug, Default)] struct CallRecord { received: Mutex>, @@ -210,9 +196,6 @@ impl EventSubscriber for AlwaysOk { #[test] fn conformance_subscriber_factory_registered_type() { - let _guard = registry_lock().lock(); - reset_subscriber_registry(); - let fixture = load_fixture(); let case = fixture_case(&fixture, "subscriber_factory_registered_type"); let subscriber_config = &case["input"]["subscriber_config"]; @@ -224,27 +207,25 @@ fn conformance_subscriber_factory_registered_type() { .collect(); assert_eq!(registered_types, vec!["slack".to_string()]); - register_subscriber_type( - "slack", - Box::new(|config| { - let webhook_url = config - .get("webhook_url") - .and_then(|v| v.as_str()) - .unwrap_or(""); - let id = format!("slack-{webhook_url}"); - Ok(Box::new(RecordingSubscriber { - id, - record: Arc::new(CallRecord::default()), - }) as Box) - }), - ); - - let sub = create_subscriber(subscriber_config).expect("slack subscriber must be created"); + let mut registry = SubscriberRegistry::new(); + registry.register("slack", |config| { + let webhook_url = config + .get("webhook_url") + .and_then(|v| v.as_str()) + .unwrap_or(""); + let id = format!("slack-{webhook_url}"); + Ok(Box::new(RecordingSubscriber { + id, + record: Arc::new(CallRecord::default()), + }) as Box) + }); + + let sub = registry + .create(subscriber_config) + .expect("slack subscriber must be created"); assert!(sub.subscriber_id().starts_with("slack-")); assert_eq!(case["expected"]["subscriber_created"].as_bool(), Some(true)); assert_eq!(case["expected"]["subscriber_type"].as_str(), Some("slack")); - - reset_subscriber_registry(); } // --------------------------------------------------------------------------- @@ -253,9 +234,6 @@ fn conformance_subscriber_factory_registered_type() { #[test] fn conformance_builtin_stdout_type() { - let _guard = registry_lock().lock(); - reset_subscriber_registry(); - let fixture = load_fixture(); let case = fixture_case(&fixture, "builtin_stdout_type"); let subscriber_config = &case["input"]["subscriber_config"]; @@ -276,9 +254,6 @@ fn conformance_builtin_stdout_type() { #[test] fn conformance_builtin_file_type() { - let _guard = registry_lock().lock(); - reset_subscriber_registry(); - let fixture = load_fixture(); let case = fixture_case(&fixture, "builtin_file_type"); let subscriber_config = &case["input"]["subscriber_config"]; @@ -300,38 +275,29 @@ fn conformance_builtin_file_type() { /// delegate so we can observe whether the event reached the inner sink. /// The fixture references `delegate_type: "webhook"`, but we register a stub /// under that name during the test to avoid real HTTP traffic. -fn install_recording_webhook(record: Arc) { - register_subscriber_type( - "webhook", - Box::new(move |_config| { - let id = format!("webhook-{}", uuid::Uuid::new_v4()); - Ok(Box::new(RecordingSubscriber { - id, - record: record.clone(), - }) as Box) - }), - ); +fn recording_webhook_registry(record: Arc) -> SubscriberRegistry { + let mut registry = SubscriberRegistry::new(); + registry.register("webhook", move |_config| { + let id = format!("webhook-{}", uuid::Uuid::new_v4()); + Ok(Box::new(RecordingSubscriber { + id, + record: Arc::clone(&record), + }) as Box) + }); + registry } #[tokio::test] async fn conformance_builtin_filter_passes_matching() { - // Lock is held only while we mutate the global registry and create the - // subscriber instance. Once `sub` owns its (already-built) delegate, the - // registry can be safely reset and the lock dropped before we await. let record = Arc::new(CallRecord::default()); let fixture = load_fixture(); let case = fixture_case(&fixture, "builtin_filter_passes_matching"); let subscriber_config = case["input"]["subscriber_config"].clone(); let event = parse_event(&case["input"]["event"]); - let sub = { - let _guard = registry_lock().lock(); - reset_subscriber_registry(); - install_recording_webhook(record.clone()); - let s = create_subscriber(&subscriber_config).expect("filter built-in must be available"); - reset_subscriber_registry(); - s - }; + let sub = recording_webhook_registry(Arc::clone(&record)) + .create(&subscriber_config) + .expect("filter built-in must be available"); sub.on_event(&event).await.unwrap(); @@ -356,14 +322,9 @@ async fn conformance_builtin_filter_discards_nonmatching() { let subscriber_config = case["input"]["subscriber_config"].clone(); let event = parse_event(&case["input"]["event"]); - let sub = { - let _guard = registry_lock().lock(); - reset_subscriber_registry(); - install_recording_webhook(record.clone()); - let s = create_subscriber(&subscriber_config).expect("filter built-in must be available"); - reset_subscriber_registry(); - s - }; + let sub = recording_webhook_registry(Arc::clone(&record)) + .create(&subscriber_config) + .expect("filter built-in must be available"); sub.on_event(&event).await.unwrap(); @@ -452,14 +413,9 @@ async fn drive_filter_case(id: &str) { let subscriber_config = case["input"]["subscriber_config"].clone(); let event = parse_event(&case["input"]["event"]); - let sub = { - let _guard = registry_lock().lock(); - reset_subscriber_registry(); - install_recording_webhook(record.clone()); - let s = create_subscriber(&subscriber_config).expect("filter built-in must be available"); - reset_subscriber_registry(); - s - }; + let sub = recording_webhook_registry(Arc::clone(&record)) + .create(&subscriber_config) + .expect("filter built-in must be available"); sub.on_event(&event).await.unwrap(); diff --git a/rust/tests/test_events.rs b/rust/tests/test_events.rs index 6b624ba5..20f4c853 100644 --- a/rust/tests/test_events.rs +++ b/rust/tests/test_events.rs @@ -7,10 +7,7 @@ use serde_json::json; use apcore::errors::{ErrorCode, ModuleError}; use apcore::events::emitter::{ApCoreEvent, EventEmitter}; -use apcore::events::subscribers::{ - create_subscriber, register_subscriber_type, reset_subscriber_registry, - unregister_subscriber_type, A2ASubscriber, EventSubscriber, WebhookSubscriber, -}; +use apcore::events::subscribers::{EventSubscriber, SubscriberRegistry, WebhookSubscriber}; // --------------------------------------------------------------------------- // Test subscriber — records received events for assertions @@ -393,7 +390,7 @@ async fn test_pattern_no_match() { } // --------------------------------------------------------------------------- -// WebhookSubscriber and A2ASubscriber unit tests (construction only) +// WebhookSubscriber unit tests (construction only) // --------------------------------------------------------------------------- #[test] @@ -406,17 +403,8 @@ fn test_webhook_subscriber_defaults() { assert!(ws.headers.is_empty()); } -#[test] -fn test_a2a_subscriber_defaults() { - let a2a = A2ASubscriber::new("a2a-1", "https://platform.example.com", "*"); - assert_eq!(a2a.subscriber_id(), "a2a-1"); - assert_eq!(a2a.event_pattern(), "*"); - assert_eq!(a2a.timeout_ms, 5000); - assert!(a2a.auth.is_none()); -} - // --------------------------------------------------------------------------- -// Subscriber factory tests — single sequential test to avoid global state races +// Subscriber factory tests // --------------------------------------------------------------------------- // ModuleError is a protocol-level domain type whose rich field set is spec-required; @@ -424,68 +412,58 @@ fn test_a2a_subscriber_defaults() { #[allow(clippy::result_large_err)] #[test] fn test_subscriber_factory_operations() { - reset_subscriber_registry(); + let mut registry = SubscriberRegistry::new(); // Create webhook subscriber let config = json!({ "type": "webhook", "url": "https://example.com/hook" }); - let sub = create_subscriber(&config).expect("should create webhook subscriber"); + let sub = registry + .create(&config) + .expect("should create webhook subscriber"); assert!(sub.subscriber_id().starts_with("webhook-")); assert_eq!(sub.event_pattern(), "*"); - // Create a2a subscriber - let config = json!({ "type": "a2a", "platform_url": "https://platform.example.com" }); - let sub = create_subscriber(&config).expect("should create a2a subscriber"); - assert!(sub.subscriber_id().starts_with("a2a-")); - // Missing type field let config = json!({ "url": "https://example.com" }); - let err = create_subscriber(&config).unwrap_err(); + let err = registry.create(&config).unwrap_err(); assert_eq!(err.code, ErrorCode::ConfigInvalid); // Unknown type let config = json!({ "type": "unknown" }); - let err = create_subscriber(&config).unwrap_err(); + let err = registry.create(&config).unwrap_err(); assert_eq!(err.code, ErrorCode::ConfigInvalid); // Webhook missing url let config = json!({ "type": "webhook" }); - let err = create_subscriber(&config).unwrap_err(); - assert_eq!(err.code, ErrorCode::ConfigInvalid); - - // A2A missing platform_url - let config = json!({ "type": "a2a" }); - let err = create_subscriber(&config).unwrap_err(); + let err = registry.create(&config).unwrap_err(); assert_eq!(err.code, ErrorCode::ConfigInvalid); // Register custom type - register_subscriber_type( - "custom", - Box::new(|config| { - let id = config - .get("id") - .and_then(|v| v.as_str()) - .unwrap_or("custom-default") - .to_string(); - Ok(Box::new(RecordingSubscriber::new(&id, "*")) as Box) - }), - ); + registry.register("custom", |config| { + let id = config + .get("id") + .and_then(|v| v.as_str()) + .unwrap_or("custom-default") + .to_string(); + Ok(Box::new(RecordingSubscriber::new(&id, "*")) as Box) + }); let config = json!({ "type": "custom", "id": "my-custom" }); - let sub = create_subscriber(&config).expect("should create custom subscriber"); + let sub = registry + .create(&config) + .expect("should create custom subscriber"); assert_eq!(sub.subscriber_id(), "my-custom"); // Unregister webhook - assert!(unregister_subscriber_type("webhook").is_ok()); + assert!(registry.unregister("webhook")); let config = json!({ "type": "webhook", "url": "https://example.com" }); - assert!(create_subscriber(&config).is_err()); + assert!(registry.create(&config).is_err()); // Unregister nonexistent type - let err = unregister_subscriber_type("nonexistent").unwrap_err(); - assert_eq!(err.code, ErrorCode::GeneralInternalError); + assert!(!registry.unregister("nonexistent")); - // Reset restores built-ins - reset_subscriber_registry(); + // A second instance keeps the default factories. + let registry = SubscriberRegistry::new(); let config = json!({ "type": "webhook", "url": "https://restored.com" }); - assert!(create_subscriber(&config).is_ok()); + assert!(registry.create(&config).is_ok()); } // --------------------------------------------------------------------------- diff --git a/rust/tests/test_executor.rs b/rust/tests/test_executor.rs index b45f4388..deab1639 100644 --- a/rust/tests/test_executor.rs +++ b/rust/tests/test_executor.rs @@ -318,7 +318,12 @@ async fn test_apcore_disable_enable() { let mut config = apcore::config::Config::default(); config.set("sys_modules.enabled", json!(true)); config.set("sys_modules.events.enabled", json!(true)); - let client = APCore::with_config(config); + let client = APCore::try_start(apcore::APCoreOptions { + config: Some(config), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); // Unique module id: the disabled-set is a process-global ToggleState (sync // finding A-D-12), so a shared id could leak into other tests in this // binary while this test transiently disables it. @@ -353,7 +358,12 @@ async fn test_apcore_disable_nonexistent_module() { let mut config = apcore::config::Config::default(); config.set("sys_modules.enabled", json!(true)); config.set("sys_modules.events.enabled", json!(true)); - let client = APCore::with_config(config); + let client = APCore::try_start(apcore::APCoreOptions { + config: Some(config), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); let err = client .disable("nonexistent.module", None) diff --git a/rust/tests/test_governance_state.rs b/rust/tests/test_governance_state.rs index 54d49c46..1ca40f3b 100644 --- a/rust/tests/test_governance_state.rs +++ b/rust/tests/test_governance_state.rs @@ -104,11 +104,12 @@ fn read_modules_only_is_not_a_control_surface() { #[test] fn control_modules_with_no_gates() { - let state = executor(registry_with( + let mut ex = executor(registry_with( &[("system.control.reload_module", true)], true, - )) - .governance_state(); + )); + ex.set_policy(Some(ExecutionPolicy::default().with_strict(false))); + let state = ex.governance_state(); assert!(state.control_modules_registered); assert!(state.unprotected_control_surface); } diff --git a/rust/tests/test_governance_state_conformance.rs b/rust/tests/test_governance_state_conformance.rs index 6a626e8e..80fda40e 100644 --- a/rust/tests/test_governance_state_conformance.rs +++ b/rust/tests/test_governance_state_conformance.rs @@ -162,8 +162,8 @@ fn build(setup: &Value) -> Executor { { executor.set_approval_handler(Box::new(NeverCalledHandler)); } - if setup["policy_strict"].as_bool().unwrap_or(false) { - executor.set_policy(Some(ExecutionPolicy::new(vec![]).with_strict(true))); + if let Some(strict) = setup["policy_strict"].as_bool() { + executor.set_policy(Some(ExecutionPolicy::new(vec![]).with_strict(strict))); } executor } diff --git a/rust/tests/test_issue_123_conformance.rs b/rust/tests/test_issue_123_conformance.rs index b957dfdd..335e75bc 100644 --- a/rust/tests/test_issue_123_conformance.rs +++ b/rust/tests/test_issue_123_conformance.rs @@ -1,4 +1,4 @@ -//! Public-path drivers for apcore#123: §2.5.1, §4.17, §5.12, §9.8.2, +//! Public-path drivers for apcore#123: §2.5.1, §5.12, §9.8.2, //! §12.7.5 and §12.8. Canonical fixtures remain the source of expectations. use std::collections::{BTreeSet, HashMap}; @@ -11,9 +11,7 @@ use apcore::cancel::CancelToken; use apcore::config::{Config, EnvStyle, NamespaceRegistration}; use apcore::errors::ModuleError; use apcore::module::{Change, ChunkStream, ModuleAnnotations, PreviewResult, StreamingModule}; -use apcore::registry::{DefaultDiscoverer, ModuleDescriptor}; -use apcore::schema::exporter::{ExportProfile, SchemaExporter}; -use apcore::schema::SchemaDefinition; +use apcore::registry::DefaultDiscoverer; use apcore::{ACLRule, Context, Executor, Module, Registry, ACL}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -63,11 +61,11 @@ fn test_conformance_declaration_matches_current_version_and_fixture_scope() { assert_eq!(declaration["implementation"]["spec_version"], "1.65.0"); let results = &declaration["conformance"]["fixture_results"]; let names = strings(&results["fixture_names"]); - assert_eq!(names.len(), 9); + assert_eq!(names.len(), 8); assert!(names.iter().any(|name| name == "canonicalize_name")); assert_eq!(json!(names.len()), results["fixtures"]); let count: usize = names.iter().map(|name| cases(&fixture(name)).len()).sum(); - assert_eq!(count, 79); + assert_eq!(count, 74); assert_eq!(json!(count), results["cases"]); assert_eq!(results["passed"], results["cases"]); assert_eq!(results["failed"], 0); @@ -227,149 +225,6 @@ fn conformance_binding_file_validation() { }); } -#[test] -fn conformance_export_profiles() { - let fx = fixture("export_profiles"); - run_cases!(fx, case, { - keys( - &case["expected"], - &["paths", "absent_paths", "no_x_keywords_under"], - ); - let mut contract = fx["module_contract"].clone(); - contract["annotations"] = case["input"]["annotations"].clone(); - let descriptor: ModuleDescriptor = serde_json::from_value(contract.clone()).unwrap(); - let registry = Registry::new(); - let id = contract["module_id"].as_str().unwrap(); - registry - .register( - id, - Box::new(FixtureModule { - contract: contract.clone(), - options: json!({}), - }), - descriptor, - ) - .unwrap(); - let descriptor = registry.get_definition(id).unwrap().unwrap(); - let definition = SchemaDefinition { - module_id: descriptor.module_id, - description: descriptor.description, - input_schema: descriptor.input_schema, - output_schema: descriptor.output_schema, - error_schema: None, - definitions: None, - version: None, - }; - let profile: ExportProfile = - serde_json::from_value(case["input"]["profile"].clone()).unwrap(); - let typed = SchemaExporter::new() - .export_def( - &definition, - profile, - descriptor.annotations.as_ref(), - None, - None, - ) - .unwrap(); - let mut raw = contract.clone(); - raw["name"] = json!(if profile == ExportProfile::Mcp { - id.to_string() - } else { - id.replace('.', "_") - }); - let raw = SchemaExporter::new().export(&raw, profile, None).unwrap(); - for exported in [typed, raw] { - if let Some(paths) = case["expected"].get("paths") { - for (path, expected) in paths.as_object().unwrap() { - assert_eq!(exported.pointer(path), Some(expected), "{path}"); - } - } - if let Some(paths) = case["expected"].get("absent_paths") { - for path in strings(paths) { - assert!(exported.pointer(&path).is_none(), "{path}"); - } - } - if let Some(path) = case["expected"].get("no_x_keywords_under") { - fn check(value: &Value, properties: bool) { - match value { - Value::Object(object) => { - for (key, value) in object { - assert!( - properties || !key.starts_with("x-"), - "unexpected extension keyword {key}" - ); - check(value, key == "properties"); - } - } - Value::Array(array) => { - for value in array { - check(value, false); - } - } - _ => {} - } - } - check( - exported - .pointer(path.as_str().unwrap()) - .expect("export schema"), - false, - ); - } - } - }); -} - -#[test] -fn export_preserves_property_and_definition_names() { - let input = json!({ - "type": "object", - "description": "Ordinary description", "x-llm-description": "LLM description", - "x-owner": "private", - "properties": { - "x-trace": {"type": "string", "x-sensitive": true}, - "default": {"type": "string"}, - "value": {"$ref": "#/$defs/x-item"} - }, - "required": ["x-trace", "default", "value"], - "$defs": {"x-item": {"type": "string", "x-owner": "private"}} - }); - let definition = SchemaDefinition { - module_id: "demo.send".into(), - description: "Send a message".into(), - input_schema: input.clone(), - output_schema: json!({}), - error_schema: None, - definitions: None, - version: None, - }; - let raw = json!({"name": "demo_send", "description": "Send a message", "input_schema": input}); - let exporter = SchemaExporter::new(); - for profile in [ExportProfile::Anthropic, ExportProfile::OpenAi] { - for exported in [ - exporter.export(&raw, profile, None).unwrap(), - exporter - .export_def(&definition, profile, None, None, None) - .unwrap(), - ] { - let schema = exported - .pointer(if profile == ExportProfile::Anthropic { - "/input_schema" - } else { - "/function/parameters" - }) - .unwrap(); - assert_eq!(schema["properties"]["x-trace"]["type"], "string"); - assert_eq!(schema["properties"]["default"]["type"], "string"); - assert_eq!(schema["$defs"]["x-item"]["type"], "string"); - assert_eq!(schema["description"], "LLM description"); - assert!(schema.get("x-owner").is_none()); - assert!(schema["properties"]["x-trace"].get("x-sensitive").is_none()); - assert!(schema["$defs"]["x-item"].get("x-owner").is_none()); - } - } -} - #[tokio::test] async fn conformance_error_details_shape() { let fx = fixture("error_details_shape"); @@ -1083,10 +938,10 @@ impl apcore::events::EventSubscriber for FailingSubscriber { async fn test_configured_subscriber_circuit_breaker_uses_standard_bootstrap() { let calls = Arc::new(AtomicUsize::new(0)); let factory_calls = calls.clone(); - apcore::register_subscriber_type( - "issue123-failing", - Box::new(move |_| Ok(Box::new(FailingSubscriber(factory_calls.clone())))), - ); + let mut subscribers = apcore::SubscriberRegistry::new(); + subscribers.register("issue123-failing", move |_| { + Ok(Box::new(FailingSubscriber(Arc::clone(&factory_calls)))) + }); let mut config = Config::default(); config.set("sys_modules.enabled", json!(true)); config.set("sys_modules.events.enabled", json!(true)); @@ -1098,7 +953,14 @@ async fn test_configured_subscriber_circuit_breaker_uses_standard_bootstrap() { }, }]), ); - let mut client = apcore::APCore::with_config(config); + let mut client = apcore::APCore::try_start_with_subscribers( + apcore::APCoreOptions { + config: Some(config), + ..Default::default() + }, + &subscribers, + ) + .unwrap(); let transitions = Arc::new(Mutex::new(Vec::new())); let recording = transitions.clone(); client diff --git a/rust/tests/test_observability_hardening_conformance.rs b/rust/tests/test_observability_hardening_conformance.rs index c761aa3e..c1a4d88e 100644 --- a/rust/tests/test_observability_hardening_conformance.rs +++ b/rust/tests/test_observability_hardening_conformance.rs @@ -20,8 +20,9 @@ use serde_json::Value; use apcore::errors::{ErrorCode, ModuleError}; use apcore::observability::{ - compute_fingerprint, normalize_message, BatchSpanProcessor, ErrorHistory, InMemoryExporter, - MetricsCollector, PrometheusExporter, RedactionConfig, Span, SpanExporter, SpanProcessor, + compute_fingerprint, normalize_message, render_prometheus_metrics, BatchSpanProcessor, + ErrorHistory, InMemoryExporter, MetricsCollector, RedactionConfig, Span, SpanExporter, + SpanProcessor, }; // --------------------------------------------------------------------------- @@ -430,8 +431,7 @@ fn case_prometheus_format_includes_required_metrics() { } } - let exporter = PrometheusExporter::new(collector); - let body = exporter.export(); + let body = render_prometheus_metrics(&collector, None); for required in case["expected"]["output_contains"].as_array().unwrap() { let name = required.as_str().unwrap(); diff --git a/rust/tests/test_reload_dependents_deprecation.rs b/rust/tests/test_reload_dependents_deprecation.rs index 56f277c8..64b2f951 100644 --- a/rust/tests/test_reload_dependents_deprecation.rs +++ b/rust/tests/test_reload_dependents_deprecation.rs @@ -1,172 +1,38 @@ -//! D-121 — `reload_dependents` is deprecated for removal. -//! -//! Declared in all three SDKs' input schemas and read by none: a spec MUST -//! ("also reload modules that depend on matched modules") that no -//! implementation satisfied. That is the §9.1.3 "declared surface reaches no -//! mechanism" shape the spec forbids for configuration keys, here applied to a -//! module INPUT FIELD, and three independent implementations skipping it is the -//! evidence the maintainer decision rests on — deprecate now, remove at 2.0, do -//! NOT implement. -//! -//! Deprecated rather than removed today because the input schema sets -//! `additionalProperties: false`: at 2.0 the same call stops being a silent -//! no-op and becomes a VALIDATION ERROR, so a caller passing it needs a release -//! in which they are told. +//! D-121 removal through the configured reload module's public call path. -use apcore::config::Config; -use apcore::context::Context; -use apcore::events::emitter::EventEmitter; -use apcore::module::Module; -use apcore::registry::registry::Registry; -use apcore::sys_modules::control::ReloadModule; -use serde_json::{json, Value}; -use std::sync::{Arc, Mutex}; - -#[derive(Clone, Default)] -struct WarnCapture(Arc>>); - -impl std::io::Write for WarnCapture { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0 - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } -} - -impl tracing_subscriber::fmt::MakeWriter<'_> for WarnCapture { - type Writer = Self; - fn make_writer(&self) -> Self::Writer { - self.clone() - } -} - -/// Install a capturing subscriber for the current thread. -/// -/// `tracing::subscriber::with_default` takes a SYNC closure, and the calls -/// under test are async. `set_default` returns a guard instead, and the default -/// subscriber is thread-local — a `#[tokio::test]` runs its future on one -/// thread, so the guard covers everything awaited inside it. -fn start_capture() -> (WarnCapture, tracing::subscriber::DefaultGuard) { - let buf = WarnCapture::default(); - let subscriber = tracing_subscriber::fmt() - .with_writer(buf.clone()) - .with_ansi(false) - .with_max_level(tracing::Level::TRACE) - .finish(); - let guard = tracing::subscriber::set_default(subscriber); - (buf, guard) -} - -/// Lines mentioning `reload_dependents` captured so far. -fn captured(buf: &WarnCapture) -> Vec { - let bytes = buf - .0 - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - String::from_utf8_lossy(&bytes) - .lines() - .filter(|l| l.contains("reload_dependents")) - .map(ToString::to_string) - .collect() -} - -fn reload_module() -> ReloadModule { - ReloadModule::new(Arc::new(Registry::new()), Arc::new(EventEmitter::new())) -} - -/// Drive the module the way the executor does: through `execute`. The reload -/// itself fails (no such module), which is fine — the warning is emitted before -/// any of that, and asserting on `execute` rather than a private helper is what -/// makes this a test of the door a caller comes through. -async fn call(module: &ReloadModule, inputs: Value) { - let ctx = Context::::anonymous(); - let _ = module.execute(inputs, &ctx).await; -} +use apcore::{APCore, APCoreOptions, AutoApproveHandler, Config, ErrorCode}; +use serde_json::json; #[tokio::test] -async fn passing_it_warns_and_names_the_replacement_and_the_removal() { - // A deprecation notice that does not say what to do instead, or when the - // field stops being ignored, leaves the caller to discover both. - let module = reload_module(); - let (buf, _guard) = start_capture(); - call( - &module, - json!({"module_id": "a.b", "reason": "x", "reload_dependents": true}), - ) - .await; - let warnings = captured(&buf); - assert_eq!(warnings.len(), 1, "{warnings:?}"); - assert!(warnings[0].contains("path_filter"), "{}", warnings[0]); - assert!(warnings[0].contains("2.0"), "{}", warnings[0]); - assert!(warnings[0].contains("validation error"), "{}", warnings[0]); -} - -#[tokio::test] -async fn it_warns_once_per_instance() { - // `reload` is called by hot-reload loops and watchers, so an advisory whose - // volume is proportional to traffic is one operators learn to filter out — - // the cadence D-89 settled. - let module = reload_module(); - let (buf, _guard) = start_capture(); - for _ in 0..5 { - call( - &module, - json!({"module_id": "a.b", "reason": "x", "reload_dependents": true}), - ) - .await; - } - assert_eq!(captured(&buf).len(), 1, "{:?}", captured(&buf)); -} - -#[tokio::test] -async fn the_cadence_is_per_instance_not_per_process() { - // A process-wide one-shot tells the FIRST caller and leaves every later one - // to discover it in production — the reason D-90's notice is per token and - // D-89's dedupe is per registry instance. - let (buf, _guard) = start_capture(); - for _ in 0..2 { - let module = reload_module(); - call( - &module, - json!({"module_id": "a.b", "reason": "x", "reload_dependents": true}), +async fn removed_reload_dependents_is_rejected_by_the_module_input_schema() { + let mut config = Config::in_memory(); + config.set("sys_modules.enabled", json!(true)); + config.set("sys_modules.events.enabled", json!(true)); + let client = APCore::try_start(APCoreOptions { + config: Some(config), + approval_handler: Some(Box::new(AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); + let module_id = "system.control.reload_module"; + let descriptor = client + .registry() + .get_definition(module_id) + .unwrap() + .unwrap(); + assert_eq!(descriptor.input_schema["additionalProperties"], false); + assert!(descriptor.input_schema["properties"] + .get("reload_dependents") + .is_none()); + + let error = client + .call( + module_id, + json!({"path_filter": "demo.*", "reason": "test reload", "reload_dependents": true}), + None, + None, ) - .await; - } - assert_eq!(captured(&buf).len(), 2, "{:?}", captured(&buf)); -} - -#[tokio::test] -async fn control_omitting_it_or_passing_false_says_nothing() { - // Without this, "it warns" is also satisfied by warning on every reload, - // which is noise for the ordinary call the method exists for. - for inputs in [ - json!({"module_id": "a.b", "reason": "x"}), - json!({"module_id": "a.b", "reason": "x", "reload_dependents": false}), - ] { - let module = reload_module(); - let (buf, _guard) = start_capture(); - call(&module, inputs.clone()).await; - let warnings = captured(&buf); - assert!(warnings.is_empty(), "{inputs} -> {warnings:?}"); - } -} - -#[test] -fn the_schema_marks_it_deprecated_and_says_what_replaces_it() { - // The notice has to be readable WITHOUT triggering it: a host reading the - // input schema — which is what `describe` / `get_definition` hand an agent - // — must see the deprecation without having to call with the field. - let schema = reload_module().input_schema(); - let field = &schema["properties"]["reload_dependents"]; - assert_eq!(field["deprecated"], json!(true), "{field}"); - let description = field["description"].as_str().expect("description"); - assert!(description.contains("path_filter"), "{description}"); - assert!(description.contains("2.0"), "{description}"); - let _ = Config::default(); + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::SchemaValidationError); } diff --git a/rust/tests/test_reload_path_filter_conformance.rs b/rust/tests/test_reload_path_filter_conformance.rs index 50a4c524..af82a0f1 100644 --- a/rust/tests/test_reload_path_filter_conformance.rs +++ b/rust/tests/test_reload_path_filter_conformance.rs @@ -51,7 +51,12 @@ async fn config_only_reload_matches_canonical_response_schema() { "version: \"1.0\"\nproject:\n name: reload-test\nsys_modules:\n enabled: true\n events:\n enabled: true\n", ) .expect("write reload config"); - let client = APCore::with_config(Config::from_yaml_file(&path).expect("load config")); + let client = APCore::try_start(apcore::APCoreOptions { + config: Some(Config::from_yaml_file(&path).expect("load config")), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); let response = client .call( "system.control.reload_module", diff --git a/rust/tests/test_schema_exporter.rs b/rust/tests/test_schema_exporter.rs index 58d362a8..29caf7f7 100644 --- a/rust/tests/test_schema_exporter.rs +++ b/rust/tests/test_schema_exporter.rs @@ -1,530 +1,78 @@ -//! Tests for SchemaExporter — exporting schemas to MCP, OpenAI, Anthropic, and Generic formats. -#![allow(clippy::similar_names)] // `exporter`/`exported` and `schema`/`schemas` are intentionally distinct - -use apcore::schema::{ - to_strict_schema, ExportOptions, ExportProfile, SchemaExporter, SchemaLoader, -}; +use apcore::{export_generic, to_strict_schema, SchemaDefinition}; use serde_json::json; -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -fn sample_schema() -> serde_json::Value { - json!({ - "name": "get_weather", - "description": "Get the current weather for a location", - "input_schema": { - "type": "object", - "properties": { - "location": { "type": "string" } - }, - "required": ["location"] - } - }) -} - -// --------------------------------------------------------------------------- -// MCP export -// --------------------------------------------------------------------------- - -#[test] -fn test_schema_exporter_mcp_format() { - let exporter = SchemaExporter::new(); - let parsed = exporter - .export(&sample_schema(), ExportProfile::Mcp, None) - .unwrap(); - assert_eq!(parsed["name"], "get_weather"); - assert!(parsed["inputSchema"].is_object()); - assert_eq!(parsed["inputSchema"]["required"][0], "location"); - // Sync SCHEMA-004: MCP envelope MUST carry description, annotations, and - // _meta blocks aligned with apcore-python and apcore-typescript. - assert_eq!( - parsed["description"], - "Get the current weather for a location" - ); - assert!(parsed["annotations"].is_object()); - assert!(parsed["_meta"].is_object()); - assert_eq!(parsed["_meta"]["paginationStyle"], "cursor"); -} - -#[test] -fn test_schema_exporter_mcp_missing_name() { - let exporter = SchemaExporter::new(); - let schema = json!({ "input_schema": { "type": "object" } }); - let parsed = exporter.export(&schema, ExportProfile::Mcp, None).unwrap(); - assert!(parsed["name"].is_null()); -} - -#[test] -fn test_schema_exporter_mcp_fallback_input_schema_key() { - let exporter = SchemaExporter::new(); - let schema = json!({ - "name": "tool", - "inputSchema": { "type": "string" } - }); - let parsed = exporter.export(&schema, ExportProfile::Mcp, None).unwrap(); - assert_eq!(parsed["inputSchema"]["type"], "string"); -} - #[test] -fn test_schema_exporter_mcp_no_input_schema_defaults_empty_object() { - let exporter = SchemaExporter::new(); - let schema = json!({ "name": "tool" }); - let parsed = exporter.export(&schema, ExportProfile::Mcp, None).unwrap(); - assert_eq!(parsed["inputSchema"], json!({})); -} - -// --------------------------------------------------------------------------- -// OpenAI export -// --------------------------------------------------------------------------- +fn generic_export_preserves_module_id_and_json_schema_extensions() { + let schema = SchemaDefinition { + module_id: "demo.weather".into(), + description: "Get the weather".into(), + input_schema: json!({ + "type": "object", + "properties": {"x-location": {"type": "string", "x-sensitive": true}}, + "x-extension": {"source": "module"}, + }), + output_schema: json!({"type": "object", "properties": {"temperature": {"type": "number"}}}), + error_schema: None, + definitions: Some(json!({"coordinates": {"type": "array"}})), + version: None, + }; -#[test] -fn test_schema_exporter_openai_format() { - let exporter = SchemaExporter::new(); - let parsed = exporter - .export(&sample_schema(), ExportProfile::OpenAi, None) - .unwrap(); - assert_eq!(parsed["type"], "function"); - assert_eq!(parsed["function"]["name"], "get_weather"); assert_eq!( - parsed["function"]["description"], - "Get the current weather for a location" + export_generic(&schema), + json!({ + "module_id": schema.module_id, + "description": schema.description, + "input_schema": schema.input_schema, + "output_schema": schema.output_schema, + "definitions": schema.definitions, + }) ); - assert!(parsed["function"]["parameters"].is_object()); - assert_eq!(parsed["function"]["strict"], true); } #[test] -fn test_schema_exporter_openai_missing_description_defaults_empty() { - let exporter = SchemaExporter::new(); - let schema = json!({ "name": "tool", "input_schema": {} }); - let parsed = exporter - .export(&schema, ExportProfile::OpenAi, None) - .unwrap(); - assert_eq!(parsed["function"]["description"], ""); -} +fn strict_schema_hardens_optional_nested_objects() { + let hardened = to_strict_schema(&json!({ + "type": "object", + "properties": { + "id": {"type": "string"}, + "details": { + "type": "object", + "properties": {"title": {"type": "string"}, "rank": {"type": "integer"}}, + "required": ["title"] + } + }, + "required": ["id"] + })); -#[test] -fn test_schema_exporter_openai_uses_parameters_key_fallback() { - let exporter = SchemaExporter::new(); - let schema = json!({ - "name": "tool", - "parameters": { "type": "object", "properties": { "x": { "type": "integer" } } } - }); - let parsed = exporter - .export(&schema, ExportProfile::OpenAi, None) - .unwrap(); - // Sync SCHEMA-003: the fallback `parameters` key still feeds A23 strict - // transform; previously-optional properties become nullable arrays. + assert_eq!(hardened["additionalProperties"], false); + assert_eq!(hardened["properties"]["id"]["type"], "string"); + let details = &hardened["properties"]["details"]; + assert_eq!(details["type"], json!(["object", "null"])); + assert_eq!(details["additionalProperties"], false); + assert_eq!(details["required"], json!(["rank", "title"])); assert_eq!( - parsed["function"]["parameters"]["properties"]["x"]["type"], + details["properties"]["rank"]["type"], json!(["integer", "null"]) ); - assert_eq!( - parsed["function"]["parameters"]["additionalProperties"], - json!(false) - ); -} - -// --------------------------------------------------------------------------- -// Anthropic export -// --------------------------------------------------------------------------- - -#[test] -fn test_schema_exporter_anthropic_format() { - let exporter = SchemaExporter::new(); - let parsed = exporter - .export(&sample_schema(), ExportProfile::Anthropic, None) - .unwrap(); - assert_eq!(parsed["name"], "get_weather"); - assert_eq!( - parsed["description"], - "Get the current weather for a location" - ); - assert!(parsed["input_schema"].is_object()); - assert_eq!(parsed["input_schema"]["required"][0], "location"); - // Anthropic format should NOT have "type": "function" wrapper - assert!(parsed.get("type").is_none()); -} - -#[test] -fn test_schema_exporter_anthropic_missing_fields_use_defaults() { - let exporter = SchemaExporter::new(); - let schema = json!({}); - let parsed = exporter - .export(&schema, ExportProfile::Anthropic, None) - .unwrap(); - assert!(parsed["name"].is_null()); - assert_eq!(parsed["description"], ""); - assert_eq!(parsed["input_schema"], json!({})); -} - -// --------------------------------------------------------------------------- -// Generic export -// --------------------------------------------------------------------------- - -#[test] -fn test_schema_exporter_generic_returns_schema_as_is() { - let exporter = SchemaExporter::new(); - let schema = sample_schema(); - let parsed = exporter - .export(&schema, ExportProfile::Generic, None) - .unwrap(); - assert_eq!(parsed, schema); -} - -#[test] -fn test_schema_exporter_generic_preserves_arbitrary_fields() { - let exporter = SchemaExporter::new(); - let schema = json!({ "custom_field": 42, "nested": { "a": true } }); - let parsed = exporter - .export(&schema, ExportProfile::Generic, None) - .unwrap(); - assert_eq!(parsed["custom_field"], 42); - assert_eq!(parsed["nested"]["a"], true); -} - -// --------------------------------------------------------------------------- -// export_all — now returns HashMap -// --------------------------------------------------------------------------- - -#[test] -fn test_schema_exporter_export_all_empty_loader() { - let exporter = SchemaExporter::new(); - let loader = SchemaLoader::new(); - let result = exporter - .export_all(&loader, ExportProfile::Generic) - .unwrap(); - assert!(result.is_empty()); -} - -#[test] -fn test_schema_exporter_export_all_multiple_schemas() { - let exporter = SchemaExporter::new(); - let mut loader = SchemaLoader::new(); - loader - .load_from_value( - "tool_a", - json!({ "name": "tool_a", "input_schema": { "type": "object" } }), - ) - .unwrap(); - loader - .load_from_value( - "tool_b", - json!({ "name": "tool_b", "input_schema": { "type": "string" } }), - ) - .unwrap(); - - let result = exporter - .export_all(&loader, ExportProfile::Anthropic) - .unwrap(); - assert_eq!(result.len(), 2); - assert!(result.contains_key("tool_a")); - assert!(result.contains_key("tool_b")); - - // Verify each exported schema is a JSON object with a name field - for exported_value in result.values() { - assert!(exported_value.get("name").is_some()); - } -} - -// --------------------------------------------------------------------------- -// ExportProfile equality -// --------------------------------------------------------------------------- - -#[test] -fn test_export_profile_equality() { - assert_eq!(ExportProfile::Mcp, ExportProfile::Mcp); - assert_ne!(ExportProfile::Mcp, ExportProfile::OpenAi); - assert_ne!(ExportProfile::OpenAi, ExportProfile::Anthropic); - assert_ne!(ExportProfile::Anthropic, ExportProfile::Generic); -} - -// --------------------------------------------------------------------------- -// Default impl -// --------------------------------------------------------------------------- - -#[test] -fn test_schema_exporter_default() { - let exporter = SchemaExporter; - let parsed = exporter - .export(&json!({"name": "x"}), ExportProfile::Generic, None) - .unwrap(); - assert_eq!(parsed["name"], "x"); -} - -// --------------------------------------------------------------------------- -// export_serialized — pretty-printed JSON string (legacy behaviour) -// --------------------------------------------------------------------------- - -#[test] -fn test_schema_exporter_output_is_pretty_printed() { - let exporter = SchemaExporter::new(); - let exported = exporter - .export_serialized(&json!({"name": "test"}), ExportProfile::Generic, None) - .unwrap(); - // Pretty-printed JSON contains newlines - assert!(exported.contains('\n')); -} - -// --------------------------------------------------------------------------- -// ExportOptions — optional parameters (spec-compatible) -// --------------------------------------------------------------------------- - -#[test] -fn test_schema_exporter_export_with_name_override() { - let exporter = SchemaExporter::new(); - let schema = json!({ "name": "original", "input_schema": {} }); - let opts = ExportOptions { - name: Some("overridden".to_string()), - ..Default::default() - }; - let parsed = exporter - .export(&schema, ExportProfile::Generic, Some(&opts)) - .unwrap(); - assert_eq!(parsed["name"], "overridden"); -} - -#[test] -fn test_schema_exporter_export_with_examples() { - let exporter = SchemaExporter::new(); - let schema = json!({ "name": "tool", "input_schema": {} }); - let opts = ExportOptions { - examples: Some(json!([{"location": "London"}])), - ..Default::default() - }; - let parsed = exporter - .export(&schema, ExportProfile::Generic, Some(&opts)) - .unwrap(); - assert_eq!(parsed["examples"][0]["location"], "London"); -} - -#[test] -fn test_schema_exporter_export_with_annotations() { - let exporter = SchemaExporter::new(); - let schema = json!({ "name": "tool", "input_schema": {} }); - let opts = ExportOptions { - annotations: Some(json!({ "x-custom": "value" })), - ..Default::default() - }; - let parsed = exporter - .export(&schema, ExportProfile::Generic, Some(&opts)) - .unwrap(); - assert_eq!(parsed["x-custom"], "value"); -} - -// --------------------------------------------------------------------------- -// SCHEMA-003 — A23 strict transform on OpenAI envelope -// --------------------------------------------------------------------------- - -#[test] -fn test_schema_exporter_openai_strict_transform_marks_additional_properties_false() { - let exporter = SchemaExporter::new(); - let schema = json!({ - "name": "weather", - "description": "Get weather", - "input_schema": { - "type": "object", - "properties": { - "location": { "type": "string" } - }, - "required": ["location"] - } - }); - let parsed = exporter - .export(&schema, ExportProfile::OpenAi, None) - .unwrap(); - // After A23: additionalProperties:false on the parameters object - assert_eq!( - parsed["function"]["parameters"]["additionalProperties"], - json!(false) - ); - // All properties become required - let required = parsed["function"]["parameters"]["required"] - .as_array() - .expect("required must be an array"); - assert!(required.iter().any(|v| v == "location")); -} - -#[test] -fn test_schema_exporter_openai_strict_transform_makes_optional_nullable() { - let exporter = SchemaExporter::new(); - let schema = json!({ - "name": "tool", - "input_schema": { - "type": "object", - "properties": { - "name": { "type": "string" }, - "comment": { "type": "string" } - }, - "required": ["name"] - } - }); - let parsed = exporter - .export(&schema, ExportProfile::OpenAi, None) - .unwrap(); - let parameters = &parsed["function"]["parameters"]; - // "name" stayed required → unchanged type. - assert_eq!(parameters["properties"]["name"]["type"], "string"); - // "comment" was optional → becomes nullable array. - assert_eq!( - parameters["properties"]["comment"]["type"], - json!(["string", "null"]) - ); -} - -#[test] -fn test_schema_exporter_openai_strict_transform_hardens_optional_nested_object() { - // An optional nested object is made nullable first (`type` becomes - // ["object", "null"]), so a string-only `type == "object"` test skips it and - // the node keeps neither `additionalProperties: false` nor a complete - // `required` list — which OpenAI strict mode rejects. - let exporter = SchemaExporter::new(); - let schema = json!({ - "name": "tool", - "input_schema": { - "type": "object", - "properties": { - "id": { "type": "string" }, - "sub": { - "type": "object", - "properties": { - "x": { "type": "string" }, - "y": { "type": "integer" } - }, - "required": ["x"] - } - }, - "required": ["id"] - } - }); - let parsed = exporter - .export(&schema, ExportProfile::OpenAi, None) - .unwrap(); - - let sub = &parsed["function"]["parameters"]["properties"]["sub"]; - // Optional → nullable, and still hardened as an object node. - assert_eq!(sub["type"], json!(["object", "null"])); - assert_eq!(sub["additionalProperties"], json!(false)); - assert_eq!(sub["required"], json!(["x", "y"])); - // "y" was optional inside the nested object → nullable. - assert_eq!(sub["properties"]["y"]["type"], json!(["integer", "null"])); } #[test] -fn test_strict_schema_hardens_object_declared_as_type_array() { - // Same rule reached directly: a `type` array containing "object" is an - // object node, whoever wrote it that way. +fn strict_schema_preserves_property_and_definition_names() { let hardened = to_strict_schema(&json!({ "type": ["object", "null"], - "properties": { "x": { "type": "string" } } + "x-owner": "private", + "properties": { + "x-trace": {"type": "string", "x-sensitive": true}, + "default": {"type": "string", "default": "sample"}, + "value": {"$ref": "#/$defs/x-item"} + }, + "required": ["x-trace", "default", "value"], + "$defs": {"x-item": {"type": "string", "x-owner": "private"}} })); - assert_eq!(hardened["additionalProperties"], json!(false)); - assert_eq!(hardened["required"], json!(["x"])); -} - -// --------------------------------------------------------------------------- -// SCHEMA-004 — MCP / Anthropic envelope completeness via SchemaDefinition -// --------------------------------------------------------------------------- - -#[test] -fn test_schema_exporter_export_def_mcp_includes_full_envelope() { - use apcore::module::ModuleAnnotations; - use apcore::schema::SchemaDefinition; - - let exporter = SchemaExporter::new(); - let def = SchemaDefinition { - module_id: "weather.get".to_string(), - description: "Get the current weather".to_string(), - input_schema: json!({ - "type": "object", - "properties": { "location": { "type": "string" } } - }), - output_schema: json!({}), - error_schema: None, - definitions: None, - version: None, - }; - let ann = ModuleAnnotations { - cacheable: true, - cache_ttl: 60, - idempotent: true, - paginated: true, - pagination_style: "cursor".to_string(), - ..ModuleAnnotations::default() - }; - - let envelope = exporter - .export_def(&def, ExportProfile::Mcp, Some(&ann), None, None) - .unwrap(); - assert_eq!(envelope["name"], "weather.get"); - assert_eq!(envelope["description"], "Get the current weather"); - assert!(envelope["inputSchema"].is_object()); - // annotations block - assert_eq!(envelope["annotations"]["idempotentHint"], true); - assert_eq!(envelope["annotations"]["readOnlyHint"], false); - assert_eq!(envelope["annotations"]["openWorldHint"], true); - // _meta block - assert_eq!(envelope["_meta"]["cacheable"], true); - assert_eq!(envelope["_meta"]["cacheTtl"], 60); - assert_eq!(envelope["_meta"]["paginated"], true); - assert_eq!(envelope["_meta"]["paginationStyle"], "cursor"); -} - -#[test] -fn test_schema_exporter_export_def_anthropic_includes_input_examples() { - use apcore::module::ModuleExample; - use apcore::schema::SchemaDefinition; - - let exporter = SchemaExporter::new(); - let def = SchemaDefinition { - module_id: "tools.echo".to_string(), - description: "Echo".to_string(), - input_schema: json!({"type": "object"}), - output_schema: json!({}), - error_schema: None, - definitions: None, - version: None, - }; - let mut ex = ModuleExample::default(); - ex.title = "hello".to_string(); - ex.inputs = json!({"text": "hi"}); - ex.output = json!({"text": "hi"}); - let examples = vec![ex]; - let envelope = exporter - .export_def(&def, ExportProfile::Anthropic, None, Some(&examples), None) - .unwrap(); - assert_eq!(envelope["name"], "tools_echo"); - assert!(envelope["input_examples"].is_array()); - assert_eq!(envelope["input_examples"][0]["text"], "hi"); -} - -#[test] -fn test_schema_exporter_export_def_openai_uses_strict_transform() { - use apcore::schema::SchemaDefinition; - - let exporter = SchemaExporter::new(); - let def = SchemaDefinition { - module_id: "ns.tool".to_string(), - description: "desc".to_string(), - input_schema: json!({ - "type": "object", - "properties": { "x": { "type": "integer" } }, - "required": ["x"] - }), - output_schema: json!({}), - error_schema: None, - definitions: None, - version: None, - }; - let envelope = exporter - .export_def(&def, ExportProfile::OpenAi, None, None, None) - .unwrap(); - assert_eq!(envelope["function"]["name"], "ns_tool"); - assert_eq!( - envelope["function"]["parameters"]["additionalProperties"], - json!(false) - ); + assert_eq!(hardened["additionalProperties"], false); + assert_eq!(hardened["properties"]["x-trace"], json!({"type": "string"})); + assert_eq!(hardened["properties"]["default"], json!({"type": "string"})); + assert_eq!(hardened["$defs"]["x-item"], json!({"type": "string"})); + assert!(hardened.get("x-owner").is_none()); } diff --git a/rust/tests/test_serde_wire_format.rs b/rust/tests/test_serde_wire_format.rs index e8352fb1..b07c2511 100644 --- a/rust/tests/test_serde_wire_format.rs +++ b/rust/tests/test_serde_wire_format.rs @@ -4,7 +4,6 @@ // expected by the Python and TypeScript SDKs on the wire. use apcore::registry::conflicts::{ConflictSeverity, ConflictType}; -use apcore::schema::exporter::ExportProfile; use apcore::schema::loader::SchemaStrategy; // --------------------------------------------------------------------------- @@ -105,35 +104,6 @@ fn task_status_cancelled_serializes_to_snake_case() { assert_eq!(json, r#""cancelled""#); } -// --------------------------------------------------------------------------- -// ExportProfile — snake_case wire format (matches Python: "mcp", "openai", etc.) -// --------------------------------------------------------------------------- - -#[test] -fn export_profile_mcp_serializes_to_snake_case() { - let json = serde_json::to_string(&ExportProfile::Mcp).unwrap(); - assert_eq!(json, r#""mcp""#); -} - -#[test] -fn export_profile_openai_serializes_to_openai() { - // Python ExportProfile.OPENAI = "openai" — explicit rename overrides snake_case - let json = serde_json::to_string(&ExportProfile::OpenAi).unwrap(); - assert_eq!(json, r#""openai""#); -} - -#[test] -fn export_profile_anthropic_serializes_to_snake_case() { - let json = serde_json::to_string(&ExportProfile::Anthropic).unwrap(); - assert_eq!(json, r#""anthropic""#); -} - -#[test] -fn export_profile_generic_serializes_to_snake_case() { - let json = serde_json::to_string(&ExportProfile::Generic).unwrap(); - assert_eq!(json, r#""generic""#); -} - // --------------------------------------------------------------------------- // SchemaStrategy — snake_case wire format (matches Python: "yaml_first", etc.) // --------------------------------------------------------------------------- diff --git a/rust/tests/test_single_sdk_defects.rs b/rust/tests/test_single_sdk_defects.rs index bc086f6c..14f47edd 100644 --- a/rust/tests/test_single_sdk_defects.rs +++ b/rust/tests/test_single_sdk_defects.rs @@ -981,6 +981,19 @@ fn sys_config(dir: &std::path::Path, extra: &str) -> Config { Config::from_yaml_file(&path).expect("config loads") } +fn apcore_with_control_approval(config: Config, mut executor: Option) -> APCore { + if let Some(executor) = &mut executor { + executor.set_approval_handler(Box::new(apcore::AutoApproveHandler)); + } + APCore::try_start(apcore::APCoreOptions { + config: Some(config), + executor, + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap() +} + #[tokio::test] async fn apcore_persists_a_toggle_to_the_configured_overrides_path() { let dir = tempfile::tempdir().unwrap(); @@ -992,7 +1005,7 @@ async fn apcore_persists_a_toggle_to_the_configured_overrides_path() { serde_json::to_string(&overrides.to_string_lossy()).unwrap() ), ); - let client = APCore::with_config(config); + let client = apcore_with_control_approval(config, None); client.register("probe.toggled", fixed(json!({}))).unwrap(); client.disable("probe.toggled", Some("test")).await.unwrap(); @@ -1003,7 +1016,7 @@ async fn apcore_persists_a_toggle_to_the_configured_overrides_path() { #[tokio::test] async fn reload_module_can_reload_the_config_of_an_apcore_client() { let dir = tempfile::tempdir().unwrap(); - let client = APCore::with_config(sys_config(dir.path(), "")); + let client = apcore_with_control_approval(sys_config(dir.path(), ""), None); let out = client .call( "system.control.reload_module", @@ -1019,10 +1032,13 @@ async fn reload_module_can_reload_the_config_of_an_apcore_client() { #[tokio::test] async fn test_update_config_rejects_empty_path_without_persisting_or_emitting() { let dir = tempfile::tempdir().unwrap(); - let mut client = APCore::with_config(sys_config( - dir.path(), - " control:\n overrides_path: overrides.yaml\nextensions:\n root: original\n", - )); + let mut client = apcore_with_control_approval( + sys_config( + dir.path(), + " control:\n overrides_path: overrides.yaml\nextensions:\n root: original\n", + ), + None, + ); let changes = Arc::new(AtomicUsize::new(0)); let observed = Arc::clone(&changes); client @@ -1104,8 +1120,7 @@ async fn test_control_reload_refreshes_the_supplied_executor_and_rolls_back_on_f let executor_source = dir.path().join("executor.yaml"); let executor = apcore::Executor::new(Registry::new(), read_executor_config(&executor_source, 40)); - let mut client = - APCore::with_options(None, Some(executor), Some(sys_config(dir.path(), "")), None); + let mut client = apcore_with_control_approval(sys_config(dir.path(), ""), Some(executor)); client .register("probe.timeout", Box::new(TimeoutProbe)) .unwrap(); @@ -1164,7 +1179,7 @@ async fn test_control_reload_reapplies_persisted_config_overrides() { dir.path(), " control:\n overrides_path: overrides.yaml\nexecutor:\n default_timeout: 45\n", ); - let client = APCore::with_config(config); + let client = apcore_with_control_approval(config, None); client .register("probe.timeout", Box::new(TimeoutProbe)) .unwrap(); @@ -1214,7 +1229,7 @@ async fn test_control_reload_removes_a_persisted_override_from_the_source_less_e let mut executor_config = Config::from_defaults(); executor_config.set("executor.default_timeout", json!(35)); let executor = apcore::Executor::new(Registry::new(), executor_config); - let client = APCore::with_options(None, Some(executor), Some(config), None); + let client = apcore_with_control_approval(config, Some(executor)); client .register("probe.timeout", Box::new(TimeoutProbe)) .unwrap(); @@ -1252,7 +1267,7 @@ async fn test_control_update_reports_the_bare_value_for_a_qualified_path() { "apcore:\n version: '1.0'\n project:\n name: path-probe\n sys_modules:\n enabled: true\n events:\n enabled: true\n", ) .unwrap(); - let client = APCore::with_config(Config::from_yaml_file(&path).unwrap()); + let client = apcore_with_control_approval(Config::from_yaml_file(&path).unwrap(), None); let key = "apcore.extensions.root"; let result = client .call( @@ -1286,11 +1301,9 @@ async fn test_control_update_reports_the_supplied_executor_value_for_a_qualified Registry::new(), read_executor_config(&dir.path().join("executor.yaml"), 45), ); - let mut client = APCore::with_options( - None, + let mut client = apcore_with_control_approval( + sys_config(dir.path(), "executor:\n default_timeout: 72\n"), Some(executor), - Some(sys_config(dir.path(), "executor:\n default_timeout: 72\n")), - None, ); client .register("probe.timeout", Box::new(TimeoutProbe)) @@ -1329,10 +1342,13 @@ async fn test_control_update_reports_the_supplied_executor_value_for_a_qualified #[tokio::test] async fn test_control_update_redacts_the_canonical_path_of_a_qualified_key() { let dir = tempfile::tempdir().unwrap(); - let mut client = APCore::with_config(sys_config( - dir.path(), - "obs:\n redaction:\n sensitive_keys: ['executor.default_*']\n", - )); + let mut client = apcore_with_control_approval( + sys_config( + dir.path(), + "obs:\n redaction:\n sensitive_keys: ['executor.default_*']\n", + ), + None, + ); let changes = Arc::new(StdMutex::new(Vec::new())); let observed = Arc::clone(&changes); client diff --git a/rust/tests/test_subscriber_retry_config.rs b/rust/tests/test_subscriber_retry_config.rs index 32f98a84..fbb0222a 100644 --- a/rust/tests/test_subscriber_retry_config.rs +++ b/rust/tests/test_subscriber_retry_config.rs @@ -64,18 +64,6 @@ fn webhook_reads_nested_retry_block() { assert_non_default_policy(sub.retry()); } -#[test] -fn a2a_reads_nested_retry_block() { - let sub = create_subscriber(&json!({ - "type": "a2a", - "platform_url": "https://platform.example.com", - "retry": non_default_retry_json() - })) - .unwrap(); - assert_eq!(sub.subscriber_type(), "a2a"); - assert_non_default_policy(sub.retry()); -} - #[test] fn file_reads_nested_retry_block() { let dir = tempfile::tempdir().unwrap(); diff --git a/rust/tests/test_system_modules_hardening_conformance.rs b/rust/tests/test_system_modules_hardening_conformance.rs index 77362f13..b925d779 100644 --- a/rust/tests/test_system_modules_hardening_conformance.rs +++ b/rust/tests/test_system_modules_hardening_conformance.rs @@ -1961,3 +1961,90 @@ async fn health_status_for(case: &Value) -> String { .expect("status") .to_string() } + +#[tokio::test] +async fn configured_health_summary_reports_optional_project_version() { + let mut config = Config::in_memory(); + config.set("sys_modules.enabled", json!(true)); + config.set("project.name", json!("metrics-test")); + for version in [None, Some("1.2.3")] { + if let Some(version) = version { + config.set("project.version", json!(version)); + } + let client = APCore::try_start(APCoreOptions { + config: Some(config.clone()), + fail_on_error: true, + ..Default::default() + }) + .unwrap(); + let result = client + .call("system.health.summary", json!({}), None, None) + .await + .unwrap(); + assert_eq!(result["project"]["name"], "metrics-test"); + assert_eq!( + result["project"].get("version").cloned(), + version.map(|version| json!(version)) + ); + assert_wire_response("sys-health-summary", &result); + } +} + +#[test] +fn explicit_usage_retention_expires_older_hourly_buckets() { + use chrono::{Duration, Utc}; + + let now = Utc::now(); + let mut config = Config::in_memory(); + config.set("sys_modules.enabled", json!(true)); + config.set("sys_modules.usage.bucketing_strategy", json!("hourly")); + + for (hours, expected) in [(None, 2), (Some(2), 1)] { + if let Some(hours) = hours { + config.set("sys_modules.usage.retention_hours", json!(hours)); + } + let registry = Arc::new(Registry::new()); + let executor = Executor::new(Arc::clone(®istry), config.clone()); + let context = register_sys_modules(registry, &executor, &config, None).unwrap(); + let collector = context.usage_collector; + collector.record_at("demo.metrics", None, 10.0, true, now - Duration::hours(4)); + collector.record_at("demo.metrics", None, 20.0, true, now); + assert_eq!( + collector + .get_module_summary("demo.metrics") + .unwrap() + .call_count, + expected + ); + } +} + +#[test] +fn invalid_usage_configuration_fails_strict_system_startup() { + use apcore::APCoreStartupError; + + for (key, invalid) in [ + ("sys_modules.usage.bucketing_strategy", json!("daily")), + ("sys_modules.usage.retention_hours", json!(0)), + ] { + let mut config = Config::in_memory(); + config.set("sys_modules.enabled", json!(true)); + config.set(key, invalid); + let error = APCore::try_start(APCoreOptions { + config: Some(config), + fail_on_error: true, + ..Default::default() + }) + .unwrap_err(); + let APCoreStartupError::SystemModule(SysModuleError::RegistrationFailed { + module_id, + source, + }) = error + else { + panic!("expected usage configuration registration error for {key}"); + }; + assert_eq!(module_id, "system.usage.summary"); + assert_eq!(source.code, ErrorCode::ConfigInvalid); + assert!(source.message.contains(key)); + } +} diff --git a/rust/tests/test_unified_registry.rs b/rust/tests/test_unified_registry.rs index c6824f2a..0193f9df 100644 --- a/rust/tests/test_unified_registry.rs +++ b/rust/tests/test_unified_registry.rs @@ -89,7 +89,12 @@ async fn apcore_toggle_feature_is_reachable_from_executor_when_events_enabled() // When events are enabled, control modules including // `system.control.toggle_feature` should be registered into the same // registry the executor consults. - let apcore = APCore::with_config(enable_events_config()); + let apcore = APCore::try_start(apcore::APCoreOptions { + config: Some(enable_events_config()), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); let registered = apcore.list_modules(None, None); assert!( @@ -129,7 +134,12 @@ async fn apcore_toggle_feature_is_reachable_from_executor_when_events_enabled() async fn disable_through_pipeline_is_observed_by_executor() { // Unique module id avoids collisions in the process-global ToggleState. let module_id = "demo.module.disable_observed"; - let apcore = APCore::with_config(enable_events_config()); + let apcore = APCore::try_start(apcore::APCoreOptions { + config: Some(enable_events_config()), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); apcore .register(module_id, Box::new(Dummy)) .expect("register should succeed"); @@ -150,7 +160,12 @@ async fn disable_through_pipeline_is_observed_by_executor() { async fn enable_through_pipeline_restores_execution() { // Unique module id avoids collisions in the process-global ToggleState. let module_id = "demo.module.enable_restores"; - let apcore = APCore::with_config(enable_events_config()); + let apcore = APCore::try_start(apcore::APCoreOptions { + config: Some(enable_events_config()), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); apcore .register(module_id, Box::new(Dummy)) .expect("register should succeed"); @@ -231,7 +246,12 @@ async fn concurrent_register_and_list_no_deadlock() { #[tokio::test] async fn toggle_feature_on_nonexistent_module_does_not_pollute_toggle_state() { - let apcore = APCore::with_config(enable_events_config()); + let apcore = APCore::try_start(apcore::APCoreOptions { + config: Some(enable_events_config()), + approval_handler: Some(Box::new(apcore::AutoApproveHandler)), + ..Default::default() + }) + .unwrap(); // Attempt to disable a non-existent module — must fail. let result = apcore.disable("does.not.exist", Some("testing")).await; diff --git a/rust/tests/test_webhook_http_retry_contract.rs b/rust/tests/test_webhook_http_retry_contract.rs index a6618d39..59e1ec0a 100644 --- a/rust/tests/test_webhook_http_retry_contract.rs +++ b/rust/tests/test_webhook_http_retry_contract.rs @@ -24,7 +24,7 @@ use apcore::errors::ModuleError; use apcore::events::emitter::{ApCoreEvent, EventEmitter}; use apcore::events::retry::EventRetryConfig; -use apcore::events::subscribers::{A2ASubscriber, EventSubscriber, WebhookSubscriber}; +use apcore::events::subscribers::{EventSubscriber, WebhookSubscriber}; use async_trait::async_trait; use parking_lot::Mutex; use serde_json::json; @@ -267,88 +267,3 @@ async fn test_webhook_5xx_is_retried_to_exhaustion_then_dlq() { "DLQ payload must report 3 exhausted attempts" ); } - -// --------------------------------------------------------------------------- -// A2ASubscriber — same 4xx/5xx contract (apcore issue #69) -// --------------------------------------------------------------------------- - -/// A2A 4xx (400) with max_attempts=3: the endpoint must receive EXACTLY 1 -/// request. A 4xx is a permanent client error and must NOT be retried, mirroring -/// WebhookSubscriber. No DLQ event is emitted. -#[tokio::test] -async fn test_a2a_4xx_is_not_retried_single_request() { - let server = MockServer::spawn("400 Bad Request").await; - - let a2a = A2ASubscriber::new("a2a-4xx", &server.url, "*").with_retry(fast_retry(3)); - - let (dlq, dlq_events) = DlqSubscriber::new("dlq-a2a-4xx"); - - let emitter = EventEmitter::new(); - emitter.subscribe(Box::new(a2a)); - emitter.subscribe(Box::new(dlq)); - - let event = ApCoreEvent::new("test.event", json!({"hello": "world"})); - emitter.emit_delivery_semantics(event); - emitter.flush(5000).await.unwrap(); - - assert_eq!( - server.request_count(), - 1, - "A2A 4xx must NOT be retried: endpoint should receive exactly 1 request" - ); - assert!( - dlq_events.lock().is_empty(), - "A2A 4xx is a non-retryable client error reported as success: no DLQ event expected" - ); -} - -/// A2A 5xx (503) with max_attempts=3: the endpoint must receive EXACTLY 3 -/// requests (retried to exhaustion), and a single `apcore.event.delivery_failed` -/// DLQ event must be emitted with `subscriber_type == "a2a"`. -#[tokio::test] -async fn test_a2a_5xx_is_retried_to_exhaustion_then_dlq() { - let server = MockServer::spawn("503 Service Unavailable").await; - - let a2a = A2ASubscriber::new("a2a-5xx", &server.url, "*").with_retry(fast_retry(3)); - - let (dlq, dlq_events) = DlqSubscriber::new("dlq-a2a-5xx"); - - let emitter = EventEmitter::new(); - emitter.subscribe(Box::new(a2a)); - emitter.subscribe(Box::new(dlq)); - - let event = ApCoreEvent::new("test.event", json!({"hello": "world"})); - emitter.emit_delivery_semantics(event); - emitter.flush(5000).await.unwrap(); - - assert_eq!( - server.request_count(), - 3, - "A2A 5xx must be retried per max_attempts=3: endpoint should receive 3 requests" - ); - - let events = dlq_events.lock(); - assert_eq!( - events.len(), - 1, - "exactly one apcore.event.delivery_failed DLQ event expected on exhaustion" - ); - let dlq_event = &events[0]; - assert_eq!(dlq_event.event_type, "apcore.event.delivery_failed"); - assert_eq!( - dlq_event - .data - .get("subscriber_type") - .and_then(serde_json::Value::as_str), - Some("a2a"), - "DLQ payload must identify the a2a subscriber type" - ); - assert_eq!( - dlq_event - .data - .get("attempt_count") - .and_then(serde_json::Value::as_u64), - Some(3), - "DLQ payload must report 3 exhausted attempts" - ); -} From 86cf3a55316bf0c24cdd7f6ef939bb00aacc7dd5 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:18:02 +0800 Subject: [PATCH 03/10] refactor(typescript): assemble isolated runtime profiles Signed-off-by: tercel --- typescript/CHANGELOG.md | 13 + typescript/README.md | 74 +-- typescript/apcore-conformance.yaml | 11 +- typescript/examples/acl-config-driven.ts | 4 +- .../examples/bindings/format-date/run.ts | 3 +- typescript/examples/events.ts | 7 +- typescript/examples/feature-toggle.ts | 5 +- typescript/examples/modules/send-email.ts | 3 +- typescript/examples/v022-tour.ts | 7 +- typescript/package.json | 48 +- typescript/src/{acl-file.ts => acl-yaml.ts} | 29 +- typescript/src/acl.ts | 100 +--- typescript/src/async-task.ts | 2 +- typescript/src/browser/index.ts | 30 +- typescript/src/builtin-steps.ts | 65 +-- typescript/src/client.ts | 100 ++-- typescript/src/config-entry.ts | 11 + typescript/src/context.ts | 2 +- typescript/src/core.ts | 8 + typescript/src/discovery.ts | 22 + typescript/src/events/emitter.ts | 10 +- typescript/src/events/entry.ts | 17 + typescript/src/events/index.ts | 2 +- typescript/src/events/subscribers.ts | 106 ---- typescript/src/executor.ts | 29 +- typescript/src/full.ts | 44 ++ typescript/src/index.ts | 461 +----------------- typescript/src/install-lifecycle-context.ts | 4 - typescript/src/lifecycle-node.ts | 12 + typescript/src/lifecycle.ts | 98 ++-- typescript/src/node-api.ts | 425 ++++++++++++++++ typescript/src/observability/index.ts | 36 +- typescript/src/observability/portable.ts | 34 ++ .../src/observability/prometheus-exporter.ts | 155 ------ typescript/src/observability/prometheus.ts | 72 +++ typescript/src/observability/usage.ts | 1 + typescript/src/policy.ts | 19 +- typescript/src/registry/install-filesystem.ts | 33 -- typescript/src/registry/managed-drain.ts | 7 +- typescript/src/registry/node-filesystem.ts | 34 ++ typescript/src/registry/registry.ts | 124 +++-- typescript/src/registry/schema-export.ts | 83 +--- typescript/src/registry/schema-query.ts | 29 ++ typescript/src/schema/exporter.ts | 88 +--- typescript/src/schema/strict.ts | 40 -- typescript/src/schema/types.ts | 3 - typescript/src/sys-modules/control.ts | 49 +- typescript/src/sys-modules/entry.ts | 17 + typescript/src/sys-modules/health.ts | 15 +- typescript/src/sys-modules/index.ts | 2 +- typescript/src/sys-modules/install.ts | 15 - typescript/src/sys-modules/overrides-file.ts | 30 -- .../src/sys-modules/read-overrides-file.ts | 16 + typescript/src/sys-modules/registration.ts | 118 ++--- typescript/src/utils/uuid.ts | 11 + .../tests/acl-argument-approval_spec.test.ts | 2 +- .../tests/acl-effect-closure_spec.test.ts | 3 +- .../tests/acl-pattern-arity_spec.test.ts | 3 +- typescript/tests/acl-system_spec.test.ts | 3 +- typescript/tests/apcore-client_spec.test.ts | 7 +- typescript/tests/browser-entry.test.ts | 41 +- .../conformance-acl-audit-delivery.test.ts | 4 +- ...nformance-acl-effect-value-closure.test.ts | 2 +- .../conformance-acl-pattern-arity.test.ts | 3 +- .../conformance-acl-root-discovery.test.ts | 11 +- .../conformance-acl-rule-key-closure.test.ts | 2 +- ...onformance-bindings-dir-resolution.test.ts | 4 +- .../conformance-config-project-root.test.ts | 2 +- .../conformance-gate-provider-binding.test.ts | 2 +- .../conformance-governance-state.test.ts | 4 +- .../conformance-id-map-from-config.test.ts | 2 +- typescript/tests/conformance-issue123.test.ts | 51 +- .../conformance-module-lifecycle.test.ts | 2 +- .../conformance-multi-root-discovery.test.ts | 2 +- ...onformance-pipeline-section-wiring.test.ts | 2 +- ...conformance-registry-load-ordering.test.ts | 3 +- .../conformance-reload-path-filter.test.ts | 9 +- .../conformance-schema-keyword-parity.test.ts | 2 +- .../conformance-toggle-isolation.test.ts | 7 +- .../conformance-tracing-from-config.test.ts | 2 +- .../tests/conformance-usage-contract.test.ts | 2 +- typescript/tests/conformance.test.ts | 102 ++-- typescript/tests/event-system_spec.test.ts | 123 ----- .../integration/test-module-lifecycle.test.ts | 2 +- .../test-concurrent-calls.test.ts | 2 +- .../test-prometheus-exporter-server.test.ts | 165 ------- .../test-prometheus-renderer.test.ts | 48 ++ typescript/tests/observability_spec.test.ts | 51 +- typescript/tests/policy.test.ts | 16 +- .../test-discover-default-stages.test.ts | 2 +- .../registry/test-ephemeral-namespace.test.ts | 7 +- .../test-registry-load-ordering.test.ts | 2 +- .../tests/registry/test-registry.test.ts | 21 +- .../tests/registry/test-schema-export.test.ts | 72 +-- typescript/tests/schema/test-exporter.test.ts | 193 +------- typescript/tests/schema/test-strict.test.ts | 105 +--- typescript/tests/setup-node-installers.ts | 15 - .../test-overrides-path-round-trip.test.ts | 5 +- ...test-reload-dependents-deprecation.test.ts | 106 ---- .../tests/test-acl-audit-delivery.test.ts | 4 +- typescript/tests/test-acl-discovery.test.ts | 6 +- .../test-acl-unevaluable-conditions.test.ts | 2 +- typescript/tests/test-acl.test.ts | 2 +- .../tests/test-approval-executor.test.ts | 16 +- .../tests/test-approval-integration.test.ts | 5 +- .../tests/test-assembly-extensions.test.ts | 167 +++++++ .../tests/test-bindings-config-dir.test.ts | 2 +- typescript/tests/test-browser-compat.test.ts | 10 +- .../test-capture-point-redaction.test.ts | 2 +- .../tests/test-client-registry-wiring.test.ts | 7 +- typescript/tests/test-client.test.ts | 9 +- .../tests/test-config-project-root.test.ts | 2 +- typescript/tests/test-control.test.ts | 3 +- .../tests/test-deprecated-inert-keys.test.ts | 2 +- .../tests/test-event-subscribers.test.ts | 156 ------ ...cutor-stream-post-validation-event.test.ts | 2 +- .../tests/test-gate-provider-binding.test.ts | 2 +- .../tests/test-governance-state.test.ts | 7 +- .../tests/test-issue123-edge-cases.test.ts | 32 +- .../test-module-schema-inference.test.ts | 2 +- .../tests/test-package-integrity.test.ts | 76 ++- .../test-pipeline-section-is-applied.test.ts | 2 +- typescript/tests/test-registration.test.ts | 85 ++-- .../tests/test-stream-completion.test.ts | 2 +- .../test-subscriber-retry-config.test.ts | 27 +- .../test-sync-policy-registry-fixes.test.ts | 10 +- .../tests/test-tracing-from-config.test.ts | 2 +- typescript/tsconfig.examples.json | 6 +- typescript/vitest.config.ts | 6 - 129 files changed, 1808 insertions(+), 2845 deletions(-) rename typescript/src/{acl-file.ts => acl-yaml.ts} (92%) create mode 100644 typescript/src/config-entry.ts create mode 100644 typescript/src/core.ts create mode 100644 typescript/src/discovery.ts create mode 100644 typescript/src/events/entry.ts create mode 100644 typescript/src/full.ts delete mode 100644 typescript/src/install-lifecycle-context.ts create mode 100644 typescript/src/lifecycle-node.ts create mode 100644 typescript/src/node-api.ts create mode 100644 typescript/src/observability/portable.ts delete mode 100644 typescript/src/observability/prometheus-exporter.ts create mode 100644 typescript/src/observability/prometheus.ts delete mode 100644 typescript/src/registry/install-filesystem.ts create mode 100644 typescript/src/registry/node-filesystem.ts create mode 100644 typescript/src/registry/schema-query.ts create mode 100644 typescript/src/sys-modules/entry.ts delete mode 100644 typescript/src/sys-modules/install.ts delete mode 100644 typescript/src/sys-modules/overrides-file.ts create mode 100644 typescript/src/sys-modules/read-overrides-file.ts create mode 100644 typescript/src/utils/uuid.ts delete mode 100644 typescript/tests/observability/test-prometheus-exporter-server.test.ts create mode 100644 typescript/tests/observability/test-prometheus-renderer.test.ts delete mode 100644 typescript/tests/setup-node-installers.ts delete mode 100644 typescript/tests/sys-modules/test-reload-dependents-deprecation.test.ts create mode 100644 typescript/tests/test-assembly-extensions.test.ts diff --git a/typescript/CHANGELOG.md b/typescript/CHANGELOG.md index 0133879c..dbcb15fa 100644 --- a/typescript/CHANGELOG.md +++ b/typescript/CHANGELOG.md @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Add portable observability, explicit runtime profiles, and instance-owned Node discovery, lifecycle, and system module assembly. + +### Changed + +- Use in-memory Core at the package root. Import `apcore-js/full` for the Node profile and `apcore-js/config` for YAML configuration. +- Default approval and destructive execution policy to fail closed. Use explicit policy settings for opt-outs. + +### Removed + +- Move the Prometheus network listener to Toolkit, A2A event delivery to Surfaces, and provider schema projections to MCP. Core retains Prometheus text rendering and generic schema transformations. + ## [1.0.0-alpha.1] ### Added diff --git a/typescript/README.md b/typescript/README.md index 8515e0e0..70cb6960 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -53,24 +53,32 @@ npm install apcore-js > **Note:** The npm package is published as `apcore-js` (the `apcore` name is reserved on npm). Python uses `apcore`, Rust uses the `apcore` crate. -## Browser support +## Runtime profiles -`apcore-js` ships dual entry points via `package.json` conditional exports: +- `apcore-js/core` exposes the portable runtime with an in-memory registry and explicit plugin assembly. +- `apcore-js/full` assembles Node filesystem discovery, configuration-driven ACLs, lifecycle callback tracking, and the configured system modules. +- `apcore-js/observability` exports `renderPrometheusMetrics` and its portable collectors, middleware, and storage. -- **Node (default):** `./dist/index.js` — the full surface. -- **Browser:** `./dist/browser/index.js` — auto-selected by tree-shaking bundlers (Vite, Webpack, esbuild, Rollup) through the `"browser"` exports condition. +The package root and the core subpath expose the same portable runtime. Import the full profile when your application needs Node capabilities. -The browser bundle **excludes** Node-only surfaces: +```typescript +import { APCore } from "apcore-js/full"; +import { Config } from "apcore-js/config"; -- `Config` class, `BindingLoader`, `SchemaLoader` (filesystem-bound) -- All `system.*` sys-modules (control, manifest, health, usage, audit) -- Events runtime: `EventEmitter`, all built-in subscribers, `AsyncTaskManager`, `TaskStatus` -- Observability runtime: `TracingMiddleware`, `MetricsCollector`, exporters, `PrometheusExporter` -- `RESERVED_NAMESPACES`, `StreamingInterfaceError`, `DuplicateModuleIdError` +const app = new APCore({ config: Config.load() }); +await app.discover(); +``` -`ACL.load(yamlPath)` throws `ACLRuleError` in the browser because the filesystem is unavailable; ACL programmatic construction still works. +The `config`, `discovery`, `sys-modules`, and `events` subpaths expose the individual Node extensions. Pass `createSysModulesPlugin({ subscriberFactories })` in a client's `plugins` array to supply its own config-driven event subscriber factories. -**Available in the browser:** `Registry` programmatic `register`/`get`/`list`/`iter`/`unregister`, `Executor`, `ACL` programmatic, `Context`, middleware pipeline, schema validation, all error classes, and the utility helpers. +The portable lifecycle tracks synchronous callback scopes. Node applications can use the full profile or pass `createNodeLifecyclePlugin()` from `apcore-js/full` to retain callback ownership across an `await`. + +## Browser support + +The root takes the same portable path in Node and browser builds. It exposes +in-memory registration and invocation, programmatic ACLs, approval, and schema +validation. Use the Node subpaths for configuration files, filesystem discovery, +optional event subscribers, and system modules. ## Canonicalizing a bare name @@ -142,7 +150,8 @@ optional system-modules subsystem. They require a `Config` instance with otherwise the calls throw with a clear "sys_modules must be enabled" message. ```typescript -import { APCore, Config } from 'apcore-js'; +import { APCore } from 'apcore-js/full'; +import { Config } from 'apcore-js/config'; // Inline config (equivalent to writing the same YAML and calling Config.load): const config = new Config({ @@ -208,7 +217,7 @@ const result = await executor.call('example.greet', { name: 'World' }); | `EventEmitter` | Event system — subscribe, emit, flush | | `CircuitBreakerWrapper` | Subscriber-level circuit breaker — protects `EventEmitter` subscribers from cascading failures | | `AsyncTaskManager` | Background task execution — injectable store, retry with backoff, opt-in reaper | -| `PrometheusExporter` | HTTP metrics server — `/metrics`, `/healthz`, `/readyz`; optional `usageCollector` for usage gauges | +| `renderPrometheusMetrics` | Renders Prometheus text from metrics and optional usage data | | `InMemoryAuditStore` | Control module audit log — records actor, action, before/after change for every control call | ## Configuration @@ -218,7 +227,7 @@ const result = await executor.call('example.greet', { name: 'World' }); `Config` acts as an ecosystem-level Config Bus. Any package can register a namespace with optional JSON Schema validation, environment variable prefix, and defaults. ```typescript -import { Config } from 'apcore-js'; +import { Config } from 'apcore-js/config'; // Register a namespace (class-level, shared across all Config instances). // registerNamespace takes a single options object; `name` is a field on it. @@ -369,7 +378,7 @@ too. Only the `audit:` block is called out: every other unrecognised root key in still ignored in silence, exactly as before. Observability and audit logging **do** work — they are wired programmatically, with -`TracingMiddleware` (see **API Overview**), `PrometheusExporter` (see **System Modules**) and the +`TracingMiddleware` and the `ACL` constructor's audit logger. Tracking: [apcore#118](https://github.com/aiperceivable/apcore/issues/118), PROTOCOL_SPEC §9.2.4 / §9.2.4.1. @@ -380,8 +389,8 @@ ignored: | Not a key | Notes | |-----------|-------| -| `observability.prometheus.*` | The Prometheus exporter's port and paths are constructor arguments — see the `PrometheusExporter` example under **System Modules**. Measured: `Unknown key 'observability.prometheus' (strict mode enabled)`. | -| `observability.health.*` | `/healthz` and `/readyz` are served by that same exporter, not configured in YAML. | +| `observability.prometheus.*` | Configure HTTP listener options with `createPrometheusServer` from `apcore-toolkit`. | +| `observability.health.*` | Toolkit's Prometheus listener serves `/healthz` and `/readyz`. | | `observability.redaction.*` | The **legacy** spelling. This SDK still reads `field_patterns` / `value_patterns` / `replacement` under it as a fallback, with a deprecation warning — but the key is undeclared, so strict mode rejects the document before the fallback can run. Write the canonical `obs.redaction.sensitive_keys` / `regex_patterns` / `replacement` instead; apcore-python does not honour the legacy spelling at all. | ### System Modules @@ -389,7 +398,8 @@ ignored: `registerSysModules()` auto-registers the built-in `system.*` modules that let AI agents query, monitor, and control the apcore runtime. Enable them via `sys_modules.enabled: true` in config, and pass the optional hardening options for production use: ```typescript -import { registerSysModules, InMemoryAuditStore } from 'apcore-js'; +import { InMemoryAuditStore } from 'apcore-js/full'; +import { registerSysModules } from 'apcore-js/sys-modules'; const auditStore = new InMemoryAuditStore(); @@ -412,23 +422,19 @@ const entries = auditStore.query({ moduleId: 'system.control.update_config' }); // entries[0] = { timestamp, action, targetModuleId, actorId, actorType, traceId, change } ``` -**Prometheus usage metrics** — wire `PrometheusExporter` with the `UsageCollector` returned by `registerSysModules`: +**Prometheus usage metrics** — use the portable renderer for text output or `createPrometheusServer` from `apcore-toolkit` for HTTP metrics and health endpoints. ```typescript -import { PrometheusExporter, MetricsCollector } from 'apcore-js'; +import { MetricsCollector, renderPrometheusMetrics } from 'apcore-js/observability'; +import { registerSysModules } from 'apcore-js/sys-modules'; -const ctx = registerSysModules(registry, executor, config); -const exporter = new PrometheusExporter({ - collector: new MetricsCollector(), - usageCollector: ctx.usageCollector, // adds apcore_usage_* metrics to /metrics -}); -exporter.start({ port: 9090 }); -// GET /metrics now includes: -// apcore_usage_calls_total{module_id="math.add",status="success"} 5000 -// apcore_usage_error_rate{module_id="math.add"} 0.0004 -// apcore_usage_p99_latency_ms{module_id="math.add"} 45.0 +const collector = new MetricsCollector(); +const { usageCollector } = registerSysModules(registry, executor, config, collector); +const prometheusText = renderPrometheusMetrics(collector, usageCollector); ``` +Use `createSysModulesPlugin({ subscriberFactories })` from `apcore-js/sys-modules` to supply subscriber factories to an individual client. A2A subscribers use `createA2AEventSubscriber` from `apcore-a2a`. + ### Bindings `BindingLoader` registers modules from a YAML file instead of code — the @@ -449,7 +455,8 @@ bindings: ``` ```typescript -import { BindingLoader, Executor, Registry } from 'apcore-js'; +import { Executor, Registry } from 'apcore-js'; +import { BindingLoader } from 'apcore-js/full'; const registry = new Registry(); const loader = new BindingLoader(); @@ -687,7 +694,8 @@ Demonstrates destructive annotations, `ModuleExample` for AI-perceivable documen ```typescript import { Type } from '@sinclair/typebox'; -import { FunctionModule, ContextLogger, createAnnotations } from 'apcore-js'; +import { FunctionModule, createAnnotations } from 'apcore-js'; +import { ContextLogger } from 'apcore-js/observability'; import type { Context } from 'apcore-js'; export const sendEmailModule = new FunctionModule({ diff --git a/typescript/apcore-conformance.yaml b/typescript/apcore-conformance.yaml index 13b8a6f4..0a90f047 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.1" + version: "1.0.0-alpha.2" language: typescript spec_version: "1.65.0" maintainer: AI Perceivable @@ -13,19 +13,18 @@ conformance: date: "2026-10-08" fixture_results: scope: issue-123-and-canonicalize-name - fixtures: 9 + fixtures: 8 fixture_names: - binding_file_validation - env_prefix_dispatch - ephemeral_modules - error_details_shape - - export_profiles - json_input_native_types - preflight_check_reporting - timeout_cancellation - canonicalize_name - cases: 79 - passed: 79 + cases: 74 + passed: 74 failed: 0 skipped: 0 report: @@ -35,7 +34,7 @@ conformance: known_deviations: - feature: Full fixture verification spec: Conformance §5.3 - reason: Only the eight issue-123 fixtures and the bare-name fixture are counted; full Level 1 and Level 2 fixture verification is not certified. + reason: Only the seven issue-123 fixtures and the bare-name fixture are counted; full Level 1 and Level 2 fixture verification is not certified. severity: major - feature: Schema migration spec: §13.4 diff --git a/typescript/examples/acl-config-driven.ts b/typescript/examples/acl-config-driven.ts index 39e05cc0..630c9c69 100644 --- a/typescript/examples/acl-config-driven.ts +++ b/typescript/examples/acl-config-driven.ts @@ -36,7 +36,9 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Type } from '@sinclair/typebox'; -import { ACLDeniedError, APCore, Config, Context, createIdentity } from 'apcore-js'; +import { ACLDeniedError, Context, createIdentity } from 'apcore-js'; +import { Config } from 'apcore-js/config'; +import { APCore } from 'apcore-js/full'; // --------------------------------------------------------------------------- // 1. Lay out a throwaway project: apcore.yaml + co-located acl/global_acl.yaml. diff --git a/typescript/examples/bindings/format-date/run.ts b/typescript/examples/bindings/format-date/run.ts index 1fe6bb66..9d03149b 100644 --- a/typescript/examples/bindings/format-date/run.ts +++ b/typescript/examples/bindings/format-date/run.ts @@ -18,7 +18,8 @@ import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import yaml from 'js-yaml'; -import { BindingLoader, Executor, Registry } from 'apcore-js'; +import { Executor, Registry } from 'apcore-js'; +import { BindingLoader } from 'apcore-js/full'; const here = dirname(fileURLToPath(import.meta.url)); diff --git a/typescript/examples/events.ts b/typescript/examples/events.ts index dd3ebeff..2a1339b8 100644 --- a/typescript/examples/events.ts +++ b/typescript/examples/events.ts @@ -30,8 +30,10 @@ */ import { Type } from '@sinclair/typebox'; -import { APCore, Config } from 'apcore-js'; -import type { ApCoreEvent, EventSubscriber } from 'apcore-js'; +import { AutoApproveHandler } from 'apcore-js'; +import { Config } from 'apcore-js/config'; +import type { ApCoreEvent, EventSubscriber } from 'apcore-js/events'; +import { APCore } from 'apcore-js/full'; // --------------------------------------------------------------------------- // 1. Build an APCore with the event bus enabled. The bus is off by default; @@ -42,6 +44,7 @@ const config = new Config({ sys_modules: { enabled: true, events: { enabled: true } }, }); const client = new APCore({ config }); +client.executor.setApprovalHandler(new AutoApproveHandler()); // --------------------------------------------------------------------------- // 2. Subscribe to canonical lifecycle events; every delivery is collected. diff --git a/typescript/examples/feature-toggle.ts b/typescript/examples/feature-toggle.ts index 3d1b95e6..a97ab277 100644 --- a/typescript/examples/feature-toggle.ts +++ b/typescript/examples/feature-toggle.ts @@ -29,7 +29,9 @@ */ import { Type } from '@sinclair/typebox'; -import { APCore, Config, ModuleDisabledError } from 'apcore-js'; +import { AutoApproveHandler, ModuleDisabledError } from 'apcore-js'; +import { Config } from 'apcore-js/config'; +import { APCore } from 'apcore-js/full'; // --------------------------------------------------------------------------- // Config with sys_modules + events enabled — required for toggle control. @@ -41,6 +43,7 @@ function sysConfig(): Config { /** Build a client with two real CRM tools registered. */ function buildClient(): APCore { const client = new APCore({ config: sysConfig() }); + client.executor.setApprovalHandler(new AutoApproveHandler()); client.module({ id: 'executor.crm.read', description: 'Read a single CRM record', diff --git a/typescript/examples/modules/send-email.ts b/typescript/examples/modules/send-email.ts index 0cde3187..86a667ef 100644 --- a/typescript/examples/modules/send-email.ts +++ b/typescript/examples/modules/send-email.ts @@ -9,7 +9,8 @@ */ import { Type } from '@sinclair/typebox'; -import { FunctionModule, ContextLogger, createAnnotations } from 'apcore-js'; +import { FunctionModule, createAnnotations } from 'apcore-js'; +import { ContextLogger } from 'apcore-js/observability'; import type { Context } from 'apcore-js'; export const sendEmailModule = new FunctionModule({ diff --git a/typescript/examples/v022-tour.ts b/typescript/examples/v022-tour.ts index 3d066a44..af4583aa 100644 --- a/typescript/examples/v022-tour.ts +++ b/typescript/examples/v022-tour.ts @@ -11,21 +11,18 @@ import { Type } from '@sinclair/typebox'; import { APCore, - Config, Context, ContextKey, - type EventSubscriber, - type ApCoreEvent, - EventEmitter, FunctionModule, isStreamingModule, MiddlewareManager, Middleware, Registry, - RESERVED_NAMESPACES, STREAMING_MARKER, type StreamingModule, } from 'apcore-js'; +import { Config, RESERVED_NAMESPACES } from 'apcore-js/config'; +import { EventEmitter, type ApCoreEvent, type EventSubscriber } from 'apcore-js/events'; // --------------------------------------------------------------------------- // 1. ContextKey typed context state (#63) diff --git a/typescript/package.json b/typescript/package.json index a64415d0..00f9a1b7 100644 --- a/typescript/package.json +++ b/typescript/package.json @@ -1,38 +1,54 @@ { "name": "apcore-js", - "version": "1.0.0-alpha.1", + "version": "1.0.0-alpha.2", "description": "Build once, invoke by code or AI — with schema, ACL, approval, and audit enforced at every call", "type": "module", "main": "./dist/index.js", - "browser": "./dist/browser/index.js", + "browser": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": { - "types": { - "browser": "./dist/browser/index.d.ts", - "default": "./dist/index.d.ts" - }, - "browser": "./dist/browser/index.js", - "node": "./dist/index.js", + "types": "./dist/index.d.ts", "default": "./dist/index.js" }, + "./core": { + "types": "./dist/core.d.ts", + "default": "./dist/core.js" + }, + "./full": { + "types": "./dist/full.d.ts", + "node": "./dist/full.js" + }, "./context-keys": { "types": "./dist/context-keys.d.ts", "default": "./dist/context-keys.js" }, + "./config": { + "types": "./dist/config-entry.d.ts", + "node": "./dist/config-entry.js" + }, + "./discovery": { + "types": "./dist/discovery.d.ts", + "node": "./dist/discovery.js" + }, + "./sys-modules": { + "types": "./dist/sys-modules/entry.d.ts", + "node": "./dist/sys-modules/entry.js" + }, + "./events": { + "types": "./dist/events/entry.d.ts", + "node": "./dist/events/entry.js" + }, + "./observability": { + "types": "./dist/observability/portable.d.ts", + "default": "./dist/observability/portable.js" + }, "./compiler": { "types": "./dist/compiler.d.ts", "node": "./dist/compiler.js" } }, - "sideEffects": [ - "./dist/index.js", - "./dist/acl-file.js", - "./dist/install-lifecycle-context.js", - "./dist/registry/install-filesystem.js", - "./dist/sys-modules/install.js", - "./dist/sys-modules/overrides-file.js" - ], + "sideEffects": false, "files": [ "dist", "README.md" diff --git a/typescript/src/acl-file.ts b/typescript/src/acl-yaml.ts similarity index 92% rename from typescript/src/acl-file.ts rename to typescript/src/acl-yaml.ts index 9a81098f..fc794dd9 100644 --- a/typescript/src/acl-file.ts +++ b/typescript/src/acl-yaml.ts @@ -1,14 +1,3 @@ -/** - * Side-effect module: installs the Node-side YAML loader on `ACL.load`. - * - * Imported by the package's Node entry (`src/index.ts`). The browser - * entry intentionally does NOT import this file — `ACL.load(...)` then - * throws a clear runtime error directing the caller to construct ACL - * programmatically. - * - * `node:fs` lives only on this leaf so the browser closure stays clean. - */ - import { existsSync, lstatSync, readFileSync, statSync, type Stats } from 'node:fs'; import { appendFilesystemPath } from './utils/filesystem-path.js'; import yaml from 'js-yaml'; @@ -17,8 +6,6 @@ import { AUDIT_FIELDS, _parseAclRule, _rejectInvalidDefaultEffect, - _setAclFileLoader, - _setAclDiscoverer, } from './acl.js'; import type { AclConfigLike, AuditConfig, AuditLogger } from './acl.js'; import { getDefault } from './config-defaults.js'; @@ -99,7 +86,9 @@ function parseAuditBlock(data: Record, yamlPath: string): Audit } -_setAclFileLoader((yamlPath: string, auditLogger?: AuditLogger | null): ACL => { +export function loadAclFile( + yamlPath: string, auditLogger?: AuditLogger | null, AclClass: typeof ACL = ACL, +): ACL { if (!existsSync(yamlPath)) { throw new ConfigNotFoundError(yamlPath); } @@ -172,10 +161,10 @@ _setAclFileLoader((yamlPath: string, auditLogger?: AuditLogger | null): ACL => { // refuse a later rule for a fault a lower-indexed rule already had. const rules = rawRules.map((raw, i) => _parseAclRule(raw, i)); - const acl = new ACL(rules, defaultEffect, auditLogger ?? null, auditConfig); - acl._setYamlPath(yamlPath); + const acl = new AclClass(rules, defaultEffect, auditLogger ?? null, auditConfig); + acl._setFileReload(() => loadAclFile(yamlPath, undefined, AclClass)); return acl; -}); +} // --------------------------------------------------------------------------- // Config-driven ACL discovery (D-64, Recommendation A — issue #74) @@ -192,7 +181,7 @@ function discoveryStats(path: string): Stats | undefined { } } -_setAclDiscoverer((config: AclConfigLike): ACL | null => { +export function discoverAcl(config: AclConfigLike, load: (path: string) => ACL = loadAclFile): ACL | null { // Read `acl.root`, falling back to the canonical default ("./acl"). const rawRoot = config.get('acl.root', getDefault('acl.root')); if (rawRoot === null || rawRoot === undefined) { @@ -225,5 +214,5 @@ _setAclDiscoverer((config: AclConfigLike): ACL | null => { throw new ConfigError(`ACL path '${policyPath}' is not a regular file`); } - return ACL.load(policyPath); -}); + return load(policyPath); +} diff --git a/typescript/src/acl.ts b/typescript/src/acl.ts index d4030e65..37ab656f 100644 --- a/typescript/src/acl.ts +++ b/typescript/src/acl.ts @@ -25,24 +25,6 @@ import { isOutcomeHandler, } from './acl-handlers.js'; -/** - * Reader for an ACL YAML file. Installed by the Node-only side-effect - * module `./acl-file.ts`; remains `null` in browser bundles so that - * `ACL.load()` throws a clear runtime error instead of silently - * dragging `node:fs` into the browser closure. - */ -type AclFileLoader = (yamlPath: string, auditLogger?: AuditLogger | null) => ACL; -let _aclFileLoader: AclFileLoader | null = null; - -/** - * @internal — used by `./acl-file.ts` to install the Node-side reader. - * Pass `null` to uninstall (used by tests that need to assert the - * browser-side guidance error). - */ -export function _setAclFileLoader(fn: AclFileLoader | null): void { - _aclFileLoader = fn; -} - /** * Minimal structural view of a `Config` used by `ACL.discover()`. * @@ -55,32 +37,6 @@ export interface AclConfigLike { resolvePath(value: string): string; } -/** - * Node-side filesystem discovery for `acl.root`. Installed by the Node-only - * side-effect module `./acl-file.ts`; remains `null` in browser bundles so - * that `ACL.discover()` throws a clear runtime error instead of pulling - * `node:fs` / `node:path` into the browser closure. - */ -type AclDiscoverer = (config: AclConfigLike) => ACL | null; -let _aclDiscoverer: AclDiscoverer | null = null; - -/** - * @internal — used by `./acl-file.ts` to install the Node-side discoverer. - * Pass `null` to uninstall (parity with `_setAclFileLoader`). - */ -export function _setAclDiscoverer(fn: AclDiscoverer | null): void { - _aclDiscoverer = fn; -} - -/** - * @internal — true when the Node-side ACL discoverer has been installed. - * Lets the `APCore` bootstrap skip `ACL.discover()` in browser bundles - * (where the discoverer is never wired) instead of triggering its throw. - */ -export function _isAclDiscovererInstalled(): boolean { - return _aclDiscoverer !== null; -} - /** * A rule's approval requirement (PROTOCOL_SPEC §6.1.6). * @@ -712,7 +668,7 @@ function precheckRule(rule: ACLRule, mode: EvaluationPath): RuleFault[] { return faults; } -/** @internal — exported so `./acl-file.ts` can reuse the parser. */ +/** @internal — exported so `./acl-yaml.ts` can reuse the parser. */ /** * The complete set of keys an ACL rule may carry (PROTOCOL_SPEC §6.1). * @@ -775,7 +731,7 @@ function rejectInvalidEffect(effect: unknown, index: number): void { * rule is what stops `ACL.load()` naming rule 0 while `new ACL([...], 'Allow')` * names `default_effect` for the same content. * - * @internal — exported for `./acl-file.ts`, which must run it *before* parsing + * @internal — exported for `./acl-yaml.ts`, which must run it *before* parsing * any rule. The constructor runs it too, so the check exists once. */ export function _rejectInvalidDefaultEffect(defaultEffect: unknown): void { @@ -1502,7 +1458,7 @@ export class ACL { private _rules: ACLRule[]; private _defaultEffect: string; - private _yamlPath: string | null = null; + private _reloadFromFile: (() => ACL) | null = null; private _auditLogger: AuditLogger | null = null; private _auditConfig: AuditConfig | null = null; private _auditSink: AuditSink = new AuditSink(null, null); @@ -1696,49 +1652,17 @@ export class ACL { } } - static load(yamlPath: string, auditLogger?: AuditLogger | null): ACL { - if (_aclFileLoader === null) { - throw new ACLRuleError( - 'ACL.load(yamlPath) requires the Node entry of apcore-js. The browser ' + - 'build does not bundle the file reader. Construct ACL programmatically ' + - 'with `new ACL([...rules])` instead.', - ); - } - return _aclFileLoader(yamlPath, auditLogger ?? null); + static load(_yamlPath: string, _auditLogger?: AuditLogger | null): ACL { + throw new ACLRuleError('ACL file loading requires the apcore-js/config subpath'); } - /** - * Config-driven ACL discovery (D-64 / issue #74). - * - * Reads `acl.root` from `config` (defaulting to `"./acl"` when unset), - * resolves it against the configuration's project root and loads the ACL - * from that directory if it exists. - * - * Returns `null` when the resolved path does NOT exist. A missing path - * MUST NOT synthesize an empty default-deny ACL: an empty ACL would deny - * every inter-module call in every project lacking an `acl/` directory, a - * silent and severe break. Missing path = no enforcement, identical to a - * project that never configured an ACL. `acl.default_effect` only takes - * effect once an ACL is actually loaded from a file. - * - * Node-only: filesystem access lives on `./acl-file.ts`. In browser - * bundles the discoverer is never installed and this throws a clear - * runtime error (parity with {@link ACL.load}). - */ - static discover(config: AclConfigLike): ACL | null { - if (_aclDiscoverer === null) { - throw new ACLRuleError( - 'ACL.discover(config) requires the Node entry of apcore-js. The browser ' + - 'build does not bundle the filesystem discoverer. Construct ACL ' + - 'programmatically with `new ACL([...rules])` instead.', - ); - } - return _aclDiscoverer(config); + static discover(_config: AclConfigLike): ACL | null { + throw new ACLRuleError('ACL file discovery requires the apcore-js/config subpath'); } - /** @internal — used by `./acl-file.ts` to set `_yamlPath` after parsing. */ - _setYamlPath(yamlPath: string): void { - this._yamlPath = yamlPath; + /** @internal File loader attached by the Node configuration entry point. */ + _setFileReload(reloadFromFile: () => ACL): void { + this._reloadFromFile = reloadFromFile; } /** @@ -2350,14 +2274,14 @@ export class ACL { } reload(): void { - if (this._yamlPath === null) { + if (this._reloadFromFile === null) { throw new ACLRuleError('Cannot reload: ACL was not loaded from a YAML file'); } // The callback is NOT passed here: `reload` preserves the one this // instance already has (requirement 7), and handing it to the temporary // would emit requirement 1's override notice a second time for a // configuration the caller has already been told about. - const reloaded = ACL.load(this._yamlPath); + const reloaded = this._reloadFromFile(); this._rules = reloaded._rules; this._defaultEffect = reloaded._defaultEffect; // §6.3.2 requirement 7: a reload refreshes the `audit:` block and PRESERVES diff --git a/typescript/src/async-task.ts b/typescript/src/async-task.ts index a1fb86d8..4293c9ab 100644 --- a/typescript/src/async-task.ts +++ b/typescript/src/async-task.ts @@ -2,7 +2,7 @@ * Async task manager for background module execution. */ -import { v4 as uuidv4 } from 'uuid'; +import { uuidV4 as uuidv4 } from './utils/uuid.js'; import { CancelToken } from './cancel.js'; import type { Context } from './context.js'; import { ErrorCodes, ModuleError, TaskLimitExceededError } from './errors.js'; diff --git a/typescript/src/browser/index.ts b/typescript/src/browser/index.ts index 82655bac..f61fa042 100644 --- a/typescript/src/browser/index.ts +++ b/typescript/src/browser/index.ts @@ -1,35 +1,11 @@ /** - * Browser-safe subset of apcore-js. - * - * This entry exposes only the runtime symbols whose module-load and - * runtime behaviour do not depend on any Node.js built-in (`node:fs`, - * `node:path`, `node:os`, `node:crypto`, `node:process`). It is selected - * automatically by bundlers via `package.json` `exports.browser`, so - * consumer code keeps writing `import { ... } from 'apcore-js'` regardless - * of target. - * - * The default Node entry (`src/index.ts`) re-exports a strict superset. - * Adding any Node-only symbol here defeats the purpose of this file — - * `tests/browser-entry.test.ts` walks the transitive import graph from - * this file and fails CI if any `node:*` reference leaks in. - * - * Excluded from this entry (call them from the Node entry only): - * - Config / discoverConfigFile / DEFAULTS-aware Config.load (filesystem) - * - BindingLoader (loads YAML from disk) - * - SchemaLoader / RefResolver (load schemas from disk) - * - Registry directory scanning and watching. In-memory registry operations - * such as register, get, has and list are supported. - * - sys-modules `registerSysModules` overridesPath file loader - * - * If you reach for one of those in browser code, expose the equivalent - * data programmatically (e.g. `new Registry()` + `register(...)`, - * `new ACL([...])`, `jsonSchemaToTypeBox(yourSchema)`) — that is the - * supported path for in-browser apcore-js use. + * Portable runtime exports shared by the default entry and the core subpath. + * Filesystem discovery, YAML config, and system modules use explicit Node entry points. */ // ---- Client / runtime core ----------------------------------------------- export { APCore } from '../client.js'; -export type { APCoreOptions, ModuleOptions } from '../client.js'; +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'; diff --git a/typescript/src/builtin-steps.ts b/typescript/src/builtin-steps.ts index 005b6f84..dc58c000 100644 --- a/typescript/src/builtin-steps.ts +++ b/typescript/src/builtin-steps.ts @@ -34,8 +34,8 @@ import { DEFAULT_TOGGLE_STATE, type ToggleState } from './sys-modules/toggle.js' import { redactSensitive } from './executor.js'; import { auditSpan } from './execution-lifetime.js'; import { type EventEmitter, createEvent } from './events/emitter.js'; +import { applyDecisionToAnnotations, DEFAULT_EXECUTION_POLICY } from './policy.js'; import type { ExecutionPolicy, PolicyDecision } from './policy.js'; -import { applyDecisionToAnnotations } from './policy.js'; import { MiddlewareChainError, type MiddlewareManager } from './middleware/manager.js'; import type { Module, ModuleAnnotations } from './module.js'; import { DEFAULT_ANNOTATIONS, isModuleIdempotent } from './module.js'; @@ -430,11 +430,9 @@ export class BuiltinACLCheck implements Step { * audit event (tracing span event + optional event-bus event), and translates * the result into either continued execution or the appropriate ApprovalError. * - * Fail-loud governance (apcore#76): when a module needs approval but no handler - * is configured, the gate keeps the PROTOCOL_SPEC §7.4 skip behavior but warns - * once per module. With `ExecutionPolicy(strict=true)` it fails closed instead. - * A module whose effective `destructive` annotation is true but that no approval - * gate covers is also warned about once per module. + * The default policy requires approval for destructive modules and denies + * approval-required calls that lack a handler. Explicit policy opt-outs + * emit a warning once per affected module. */ export class BuiltinApprovalGate implements Step { readonly name = 'approval_gate'; @@ -447,7 +445,7 @@ export class BuiltinApprovalGate implements Step { readonly [GOVERNANCE_GATE]: GovernanceGateMarker = { pureIsDefault: false }; private _handler: ApprovalHandler | null; - private _policy: ExecutionPolicy | null; + private _policy: ExecutionPolicy; private _eventEmitter: EventEmitter | null; private readonly _warned = new Set(); @@ -457,7 +455,7 @@ export class BuiltinApprovalGate implements Step { eventEmitter: EventEmitter | null = null, ) { this._handler = handler; - this._policy = policy; + this._policy = policy ?? DEFAULT_EXECUTION_POLICY; this._eventEmitter = eventEmitter; } @@ -477,7 +475,7 @@ export class BuiltinApprovalGate implements Step { /** Update the execution policy at runtime. */ setPolicy(policy: ExecutionPolicy | null): void { - this._policy = policy; + this._policy = policy ?? DEFAULT_EXECUTION_POLICY; } /** Set the event emitter for approval decisions and policy overrides. */ @@ -491,7 +489,7 @@ export class BuiltinApprovalGate implements Step { } /** The execution policy this gate applies (PROTOCOL_SPEC 6.6.5.5, D-129). */ - get policy(): ExecutionPolicy | null { + get policy(): ExecutionPolicy { return this._policy; } @@ -505,8 +503,7 @@ export class BuiltinApprovalGate implements Step { // a module-scoped override cancel a caller-scoped decision is a privilege // escalation: a policy rule written for `orders.*` would silently strip a // requirement an ACL author attached to one untrusted caller. Union is the - // only safe composition, which is why this term is OR-ed into both - // branches below rather than folded into the policy's own resolution. + // only safe composition, so this term is OR-ed with the policy's resolution. const aclApprovalRequired = ctx.aclApprovalRequired === true; // PROTOCOL_SPEC §7.4 (D-96): governance is the UNION of the live module @@ -519,33 +516,18 @@ export class BuiltinApprovalGate implements Step { // fail-OPEN. const governance = governanceUnion(mod?.['annotations'], ctx.declaredAnnotations); - let decision: PolicyDecision | null = null; - let needs: boolean; - let effectiveDestructive: boolean; - if (this._policy !== null) { - // §7.9.6: policy resolution receives the call site — the invocation - // arguments and the Context — alongside the module ID and annotations. - // These arguments have NOT been schema-validated: this gate is Step 5 - // and input validation is Step 7 (§12.8). - // - // The executor isolates the credential before the pipeline starts. - decision = this._policy.resolve(ctx.moduleId, governance, { - arguments: ctx.inputs ?? null, - context: ctx.context ?? null, - }); - needs = decision.needsApproval || aclApprovalRequired; - effectiveDestructive = decision.destructive; - if (decision.overridden) { - this._emitPolicyAudit(decision, ctx.context); - } - } else { - // §6.9 rows 3 and 5: governance union ∪ ACL decision ∪ gate_destructive. - needs = Boolean(governance?.requiresApproval) || aclApprovalRequired; - effectiveDestructive = Boolean(governance?.destructive); + // §7.9.6: policy resolution receives arguments before schema validation. + // The executor isolates the credential before the pipeline starts. + const decision = this._policy.resolve(ctx.moduleId, governance, { + arguments: ctx.inputs ?? null, + context: ctx.context ?? null, + }); + if (decision.overridden) { + this._emitPolicyAudit(decision, ctx.context); } - if (!needs) { - if (effectiveDestructive) { + if (!decision.needsApproval && !aclApprovalRequired) { + if (decision.destructive) { this._warnOnce( `destructive_ungated:${ctx.moduleId}`, `[apcore:approval] Module '${ctx.moduleId}' is annotated destructive=true but is not ` + @@ -558,7 +540,7 @@ export class BuiltinApprovalGate implements Step { } if (this._handler === null) { - if (this._policy !== null && this._policy.strict) { + if (this._policy.strict) { const result = createApprovalResult({ status: 'rejected', reason: @@ -571,14 +553,13 @@ export class BuiltinApprovalGate implements Step { this._warnOnce( `no_handler:${ctx.moduleId}`, `[apcore:approval] Module '${ctx.moduleId}' requires approval but no ApprovalHandler ` + - 'is configured; the approval gate is skipped per PROTOCOL_SPEC §7.4. Configure an ' + - 'approval handler, or ExecutionPolicy(strict=true) to fail closed. (apcore#76)', + 'is configured; explicit ExecutionPolicy(strict=false) lets the call continue ' + + 'per PROTOCOL_SPEC §7.4.', ); return { action: 'continue' }; } - let annotations: ModuleAnnotations = governance ?? DEFAULT_ANNOTATIONS; - if (decision !== null) annotations = applyDecisionToAnnotations(annotations, decision); + let annotations = applyDecisionToAnnotations(governance ?? DEFAULT_ANNOTATIONS, decision); if (!annotations.requiresApproval) annotations = Object.freeze({ ...annotations, requiresApproval: true }); const request = createApprovalRequest({ diff --git a/typescript/src/client.ts b/typescript/src/client.ts index 09a7ac29..d8a50c47 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -2,8 +2,8 @@ * High-level client for apcore to simplify interaction. */ +import type { ACL } from './acl.js'; import type { TSchema } from '@sinclair/typebox'; -import { ACL, _isAclDiscovererInstalled } from './acl.js'; import type { Config } from './config.js'; import type { Context } from './context.js'; import { type FunctionModule, module as createModule } from './decorator.js'; @@ -12,7 +12,7 @@ import { createEvent, type ApCoreEvent, type EventEmitter, type EventSubscriber import { Executor } from './executor.js'; import { freezeLifecycleReport, - lifecycleCallbackWaitError, + type LifecycleCallbacks, lifecycleError, lifecycleHandle, LifecycleCompletion, @@ -29,21 +29,10 @@ import type { Middleware } from './middleware/index.js'; import type { ModuleAnnotations, ModuleExample, PreflightResult, ResourceLimits } from './module.js'; import type { MetricsCollector } from './observability/metrics.js'; import type { StreamExecution } from './stream-completion.js'; -import { buildTracingMiddleware } from './observability/tracing-config.js'; import { Registry } from './registry/registry.js'; import type { RegisterSysModulesOptions, SysModulesContext } from './sys-modules/registration.js'; import { ToggleState } from './sys-modules/toggle.js'; -/** - * Optional Node-side hook that auto-registers system modules when an - * `APCore` is constructed with a non-null `Config`. Installed by the - * Node entry's side-effect import of `./sys-modules/install.ts`. - * - * Browser bundles never import the installer, so `_sysModulesInstaller` - * stays `null` and the constructor skips auto-registration. Browser - * callers either pass `config: undefined` (the recommended path) or - * register sys-modules manually after construction. - */ type SysModulesInstaller = ( registry: Registry, executor: Executor, @@ -51,14 +40,29 @@ type SysModulesInstaller = ( metricsCollector?: MetricsCollector | null, options?: RegisterSysModulesOptions, ) => SysModulesContext; -let _sysModulesInstaller: SysModulesInstaller | null = null; -/** @internal — used by the Node-only `./sys-modules/install.ts` side-effect. */ -export function _setSysModulesInstaller(fn: SysModulesInstaller): void { - _sysModulesInstaller = fn; +/** Optional services used to assemble an APCore instance. */ +export interface APCorePlugin { + readonly createRegistry?: (config: Config | null, callbacks?: LifecycleCallbacks) => Registry; + readonly createLifecycleCallbacks?: () => LifecycleCallbacks; + readonly discoverAcl?: (config: Config) => ACL | null; + readonly registerSysModules?: SysModulesInstaller; + readonly createTracingMiddleware?: (config: Config) => Middleware | null; +} + +function pluginCapability( + plugins: readonly APCorePlugin[] | undefined, key: K, +): APCorePlugin[K] { + const capabilities = (plugins ?? []).map(plugin => plugin[key]).filter(capability => capability !== undefined); + if (capabilities.length > 1) { + throw new InvalidInputError(`Multiple APCore plugins provide '${key}'`); + } + return capabilities[0]; } export interface APCoreOptions { + /** Optional instance-owned services. A supplied executor or registry takes precedence. */ + plugins?: readonly APCorePlugin[]; registry?: Registry; executor?: Executor; config?: Config; @@ -130,10 +134,18 @@ export class APCore { private readonly _sysModulesErrors: Error[] = []; private _shutdown: ClientShutdown | undefined; - constructor(options?: APCoreOptions) { + constructor(options?: APCoreOptions); + /** @internal Profile-specific defaults that do not consult the legacy adapters. */ + constructor(options: APCoreOptions | undefined, profile: APCorePlugin); + constructor(options?: APCoreOptions, profile?: APCorePlugin) { this.config = options?.config ?? null; this.metricsCollector = options?.metricsCollector ?? null; const prebuiltExecutor = options?.executor; + const createRegistry = pluginCapability(options?.plugins, 'createRegistry') ?? profile?.createRegistry; + const discoverAcl = pluginCapability(options?.plugins, 'discoverAcl') ?? profile?.discoverAcl; + const installSysModules = pluginCapability(options?.plugins, 'registerSysModules') ?? profile?.registerSysModules; + const createTracingMiddleware = pluginCapability(options?.plugins, 'createTracingMiddleware') + ?? profile?.createTracingMiddleware; this._toggleState = prebuiltExecutor?.toggleState ?? options?.toggleState ?? new ToggleState(); // CLI-1: a supplied Executor brings its own Registry, and that is the one @@ -156,10 +168,13 @@ export class APCore { // `discover()` scan the hardcoded `./extensions` default whatever the // config said. A Config that declares none of those keys still resolves // to exactly the previous default, so this only ever narrows. - this.registry = - prebuiltExecutor?.registry ?? - options?.registry ?? - new Registry({ config: this.config }); + const suppliedRegistry = prebuiltExecutor?.registry ?? options?.registry; + const callbacks = suppliedRegistry === undefined + ? (pluginCapability(options?.plugins, 'createLifecycleCallbacks') ?? profile?.createLifecycleCallbacks)?.() + : undefined; + this.registry = suppliedRegistry + ?? createRegistry?.(this.config, callbacks) + ?? new Registry({ config: this.config, lifecycleCallbacks: callbacks }); this.executor = prebuiltExecutor ?? new Executor({ @@ -172,19 +187,13 @@ export class APCore { policy: options?.policy ?? null, }); - // Activate config-driven ACL discovery (D-64 / issue #74). When a config - // is present and we built the Executor ourselves, resolve `acl.root` and - // attach the discovered ACL. A missing acl path returns null and attaches - // NOTHING — preserving "no enforcement" for projects without an acl file - // (never a silent empty default-deny). Skipped when a pre-built Executor - // was supplied so the caller's explicit ACL wiring is never clobbered, and - // skipped in browser bundles where the Node-only discoverer is never wired - // (so ACL.discover's browser-guidance throw is never hit). - if (this.config && prebuiltExecutor === undefined && _isAclDiscovererInstalled()) { - const discovered = ACL.discover(this.config); - if (discovered !== null) { - this.executor.setAcl(discovered); + // Respect ACLs already configured on a supplied Executor. + if (this.config && prebuiltExecutor === undefined) { + if (discoverAcl === undefined && this.config.get('acl.root') != null) { + throw new InvalidInputError('Configured ACL paths require an ACL discovery plugin or a configured executor'); } + const discovered = discoverAcl?.(this.config); + if (discovered) this.executor.setAcl(discovered); } // Config-driven tracing (PROTOCOL_SPEC §10.1.1). `observability.tracing.*` @@ -199,21 +208,14 @@ export class APCore { // here has an empty middleware chain, so configuration can never be the // thing that adds a SECOND tracing middleware. A caller who calls // `use(new TracingMiddleware(...))` afterwards is adding one deliberately. - if (this.config && prebuiltExecutor === undefined) { - const tracingMw = buildTracingMiddleware(this.config); - if (tracingMw !== null) { - this.executor.use(tracingMw); - } + if (this.config && prebuiltExecutor === undefined && createTracingMiddleware) { + const tracingMw = createTracingMiddleware(this.config); + if (tracingMw !== null) this.executor.use(tracingMw); } - // Auto-register sys modules if config is provided AND the Node-side - // installer is wired up. In browser bundles `_sysModulesInstaller` - // remains null, so this branch is skipped — keeping the chain to - // `node:fs`/`node:path` (sys-modules/registration.ts and friends) - // out of the browser closure. - if (this.config && _sysModulesInstaller) { + if (this.config && installSysModules) { try { - this._sysModulesContext = _sysModulesInstaller( + this._sysModulesContext = installSysModules( this.registry, this.executor, this.config, @@ -325,6 +327,8 @@ export class APCore { let complete = false; const settled = new LifecycleCompletion(); const callbackOwners = events ? [this.registry, events] : [this.registry]; + const callbackWaitError = () => this.registry.lifecycleCallbacks.waitError(callbackOwners) + ?? events?.lifecycleCallbacks.waitError(callbackOwners); const operation = lifecycleHandle(() => { const report = registry.snapshot(); return freezeLifecycleReport({ @@ -332,7 +336,7 @@ export class APCore { status: complete ? (eventError ? 'failed' : report.status) : 'pending', ...(eventError && report.error === undefined ? { error: eventError } : {}), }); - }, settled, callbackOwners); + }, settled, callbackWaitError); const completion = registryCompletion.finally(async () => { if (!events) return; try { @@ -359,7 +363,7 @@ export class APCore { }); void completion.catch(() => {}); this._shutdown = { operation, completion, eventFlushTimeoutMs, - waitError: () => complete ? undefined : lifecycleCallbackWaitError(callbackOwners), + waitError: () => complete ? undefined : callbackWaitError(), }; return this._shutdown; } diff --git a/typescript/src/config-entry.ts b/typescript/src/config-entry.ts new file mode 100644 index 00000000..19e8385b --- /dev/null +++ b/typescript/src/config-entry.ts @@ -0,0 +1,11 @@ +import { discoverAcl } from './acl-yaml.js'; +import type { APCorePlugin } from './client.js'; + +export { Config, discoverConfigFile, RESERVED_NAMESPACES } from './config.js'; +export { discoverAcl, loadAclFile } from './acl-yaml.js'; +export { buildStrategyFromConfig, buildStrategyFromConfigSync } from './pipeline-config.js'; + +/** Discover an ACL for the executor this client constructs. */ +export function createAclDiscoveryPlugin(): APCorePlugin { + return { discoverAcl }; +} diff --git a/typescript/src/context.ts b/typescript/src/context.ts index 2184a465..89bc353f 100644 --- a/typescript/src/context.ts +++ b/typescript/src/context.ts @@ -2,7 +2,7 @@ * Execution context, identity, and context creation. */ -import { v4 as uuidv4 } from 'uuid'; +import { uuidV4 as uuidv4 } from './utils/uuid.js'; import type { CancelToken } from './cancel.js'; import { ContextBindingError } from './errors.js'; import { copyObservationState, inheritObservationParent, setRemoteSpanParent } from './execution-lifetime.js'; diff --git a/typescript/src/core.ts b/typescript/src/core.ts new file mode 100644 index 00000000..e6cac8a2 --- /dev/null +++ b/typescript/src/core.ts @@ -0,0 +1,8 @@ +export * from './browser/index.js'; +export { SchemaExporter } from './schema/exporter.js'; +export { redactSensitive } from './executor.js'; +export { ExecutionPolicy, PolicyRule } from './policy.js'; +export type { PolicyCallSite, PolicyDecision, PolicyRuleOverrides } from './policy.js'; +export { STREAMING_MARKER, isStreamingModule } from './streaming.js'; +export type { StreamingModule } from './streaming.js'; +export type { RegistryOptions } from './registry/registry.js'; diff --git a/typescript/src/discovery.ts b/typescript/src/discovery.ts new file mode 100644 index 00000000..e3ce7f7e --- /dev/null +++ b/typescript/src/discovery.ts @@ -0,0 +1,22 @@ +import { createNodeLifecycleCallbacks } from './lifecycle-node.js'; +import type { APCorePlugin } from './client.js'; +import { createRegistryFilesystem } from './registry/node-filesystem.js'; +import { Registry, type RegistryOptions } from './registry/registry.js'; + +export type DiscoveryRegistryOptions = Omit; + +/** Create a registry with its own filesystem discovery and watch capability. */ +export function createDiscoveryRegistry(options?: DiscoveryRegistryOptions): Registry { + return new Registry({ + ...options, + filesystem: createRegistryFilesystem(), + lifecycleCallbacks: options?.lifecycleCallbacks ?? createNodeLifecycleCallbacks(), + }); +} + +/** Install filesystem discovery on the registry this client constructs. */ +export function createFilesystemDiscoveryPlugin(options?: Omit): APCorePlugin { + return { + createRegistry: (config, lifecycleCallbacks) => createDiscoveryRegistry({ ...options, config, lifecycleCallbacks }), + }; +} diff --git a/typescript/src/events/emitter.ts b/typescript/src/events/emitter.ts index 1fcb07d1..5591daf1 100644 --- a/typescript/src/events/emitter.ts +++ b/typescript/src/events/emitter.ts @@ -5,7 +5,7 @@ import { resolveRetry, computeDelayMs } from './retry.js'; import type { RetryConfig } from './retry.js'; import { matchGlob } from '../utils/pattern.js'; -import { lifecycleCallback, LifecycleCompletion } from '../lifecycle.js'; +import { LifecycleCallbacks, LifecycleCompletion } from '../lifecycle.js'; export interface ApCoreEvent { readonly eventType: string; @@ -111,8 +111,12 @@ export class EventEmitter { private readonly _maxPending: number; private _shutdown = false; - constructor(maxPending: number = DEFAULT_MAX_PENDING) { + /** @internal Used by the owner when waiting for its own event delivery. */ + readonly lifecycleCallbacks: LifecycleCallbacks; + + constructor(maxPending: number = DEFAULT_MAX_PENDING, lifecycleCallbacks?: LifecycleCallbacks) { this._maxPending = Math.max(0, Math.floor(maxPending)); + this.lifecycleCallbacks = lifecycleCallbacks ?? new LifecycleCallbacks(); } subscribe(subscriber: EventSubscriber): void { @@ -192,7 +196,7 @@ export class EventEmitter { settle(); }; return () => { - void lifecycleCallback([this], deliver).then(release, error => { + void this.lifecycleCallbacks.run([this], deliver).then(release, error => { release(); console.error('[apcore:events] Delivery task failed:', error); }); diff --git a/typescript/src/events/entry.ts b/typescript/src/events/entry.ts new file mode 100644 index 00000000..89fa5231 --- /dev/null +++ b/typescript/src/events/entry.ts @@ -0,0 +1,17 @@ +import { EventEmitter as RuntimeEventEmitter } from './emitter.js'; +import { type LifecycleCallbacks } from '../lifecycle.js'; +import { createNodeLifecycleCallbacks } from '../lifecycle-node.js'; + +/** An event emitter with per-instance asynchronous callback ownership on Node. */ +export class EventEmitter extends RuntimeEventEmitter { + constructor(maxPending?: number, callbacks?: LifecycleCallbacks) { + super(maxPending, callbacks ?? createNodeLifecycleCallbacks()); + } +} + +export { createEvent, resolveSubscriberType } from './emitter.js'; +export type { ApCoreEvent, EventSubscriber } from './emitter.js'; +export { WebhookSubscriber, FileSubscriber, StdoutSubscriber, FilterSubscriber } from './subscribers.js'; +export { CircuitBreakerWrapper, CircuitState } from './circuit-breaker.js'; +export type { CircuitBreakerConfig } from './circuit-breaker.js'; +export type { RetryConfig, RetryConfig as EventRetryConfig } from './retry.js'; diff --git a/typescript/src/events/index.ts b/typescript/src/events/index.ts index 973a2dc1..58d5aaaa 100644 --- a/typescript/src/events/index.ts +++ b/typescript/src/events/index.ts @@ -1,6 +1,6 @@ export { EventEmitter, createEvent, resolveSubscriberType } from './emitter.js'; export type { ApCoreEvent, EventSubscriber } from './emitter.js'; -export { WebhookSubscriber, A2ASubscriber, FileSubscriber, StdoutSubscriber, FilterSubscriber } from './subscribers.js'; +export { WebhookSubscriber, FileSubscriber, StdoutSubscriber, FilterSubscriber } from './subscribers.js'; export { CircuitBreakerWrapper, CircuitState } from './circuit-breaker.js'; export type { CircuitBreakerConfig } from './circuit-breaker.js'; export type { RetryConfig } from './retry.js'; diff --git a/typescript/src/events/subscribers.ts b/typescript/src/events/subscribers.ts index eeafc525..7f6ade89 100644 --- a/typescript/src/events/subscribers.ts +++ b/typescript/src/events/subscribers.ts @@ -98,112 +98,6 @@ export class WebhookSubscriber implements EventSubscriber { } } -/** - * Delivers events via the A2A protocol to the platform. - * - * Sends a POST with `skillId="apevo.event_receiver"` and the - * serialized event in the payload. As of v0.22.0 finding A-D-EVT-001 the - * subscriber no longer silently swallows errors. Mirroring - * `WebhookSubscriber`, it rethrows on 5xx / network errors so the unified - * `EventEmitter._deliver` retry policy applies (defaults to `DEFAULT_RETRY` - * — 3 attempts, 100 ms initial backoff, 2× multiplier, 30 s cap); after - * exhaustion the EventEmitter routes the failure through the DLQ + - * `onFailure` path. 4xx responses are treated as non-retryable: a warning - * is logged and the call returns normally (no retry, no DLQ). - */ -export class A2ASubscriber implements EventSubscriber { - /** Declared subscriber kind for DLQ payloads (A-D-029). */ - readonly subscriberType = 'a2a'; - readonly subscriberId: string; - readonly retry: RetryConfig; - private readonly _platformUrl: string; - private readonly _auth: string | Record | undefined; - private readonly _timeoutMs: number; - private readonly _skillId: string; - - constructor( - platformUrl: string, - auth?: string | Record, - timeoutMsOrOpts: - | number - | { timeoutMs?: number; retry?: RetryConfig; id?: string; skillId?: string } = 5000, - id?: string, - skillId: string = 'apevo.event_receiver', - ) { - if (typeof timeoutMsOrOpts === 'number') { - this._timeoutMs = timeoutMsOrOpts; - this.retry = { ...DEFAULT_RETRY }; - this.subscriberId = id ?? _nextSubscriberId('a2a'); - this._skillId = skillId; - } else { - this._timeoutMs = timeoutMsOrOpts.timeoutMs ?? 5000; - this.retry = { ...DEFAULT_RETRY, ...(timeoutMsOrOpts.retry ?? {}) }; - this.subscriberId = timeoutMsOrOpts.id ?? id ?? _nextSubscriberId('a2a'); - this._skillId = timeoutMsOrOpts.skillId ?? skillId; - } - this._platformUrl = platformUrl; - this._auth = auth as string | Record | undefined; - } - - async onEvent(event: ApCoreEvent): Promise { - const payload: Record = { - skillId: this._skillId, - event: { - event_type: event.eventType, - module_id: event.moduleId, - timestamp: event.timestamp, - severity: event.severity, - data: event.data, - }, - }; - - const headers: Record = { - 'Content-Type': 'application/json', - }; - - if (this._auth !== undefined) { - if (typeof this._auth === 'string') { - // String auth → Bearer token (per spec) - headers['Authorization'] = `Bearer ${this._auth}`; - } else { - // Dict auth → merge as header overrides - for (const [key, value] of Object.entries(this._auth)) { - if (typeof value === 'string') { - headers[key] = value; - } - } - } - } - - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), this._timeoutMs); - try { - const response = await fetch(this._platformUrl, { - method: 'POST', - headers, - body: JSON.stringify(payload), - signal: controller.signal, - }); - - if (response.status >= 500) { - // Server error — rethrow so the EventEmitter retry policy applies. - throw new Error( - `A2A delivery to ${this._platformUrl} failed with status ${response.status}`, - ); - } - if (response.status >= 400) { - // Client error — non-retryable; log and return. - console.warn( - '[apcore:events]', - `A2A delivery to ${this._platformUrl} returned ${response.status} for event ${event.eventType}`, - ); - } - } finally { - clearTimeout(timer); - } - } -} - /** Writes events to a local file (built-in type: 'file'). */ export class FileSubscriber implements EventSubscriber { /** Declared subscriber kind for DLQ payloads (A-D-029). */ diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index 80c03a0e..6cc1d3c3 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -12,7 +12,7 @@ import { type RedactionReferenceContext, } from './utils/redaction-references.js'; import { type ApprovalHandler, discardApprovalToken, prepareApprovalInputs, stripApprovalToken } from './approval.js'; -import type { ExecutionPolicy } from './policy.js'; +import { DEFAULT_EXECUTION_POLICY, type ExecutionPolicy } from './policy.js'; import { BuiltinACLCheck, BuiltinApprovalGate, @@ -750,13 +750,13 @@ export class Executor { const enforcingGates = this._strategy.steps.filter( (step): step is BuiltinApprovalGate => step instanceof BuiltinApprovalGate && - (step.approvalHandler !== null || step.policy?.strict === true), + (step.approvalHandler !== null || step.policy.strict), ); return this._registry.list({ visibility: ['public', 'hidden'] }).filter((id) => { const annotations = this._moduleGovernanceAnnotations(id); if (!annotations?.requiresApproval) return false; return !enforcingGates.some( - (gate) => gate.policy === null || gate.policy.resolve(id, annotations).needsApproval, + (gate) => gate.policy.resolve(id, annotations).needsApproval, ); }); } @@ -825,8 +825,8 @@ export class Executor { ? approvalGates.every((gate) => gate.approvalHandler !== null) : this._approvalHandler !== null; const policyStrict = builtinApprovalGateWired - ? approvalGates.every((gate) => gate.policy !== null && gate.policy.strict === true) - : this._policy !== null && this._policy.strict === true; + ? approvalGates.every((gate) => gate.policy.strict) + : (this._policy ?? DEFAULT_EXECUTION_POLICY).strict; // PROTOCOL_SPEC 6.6.5.1. The approval conjunct carries // `allControlModulesRequireApproval` because `approval_gate` is per-module @@ -1541,19 +1541,12 @@ export class Executor { // That disagreement is the one thing this method exists to prevent. const governance = governanceUnion(mod['annotations'], pipeCtx.declaredAnnotations); const gate = this._strategy.steps.find((step) => step instanceof BuiltinApprovalGate); - const policy = gate instanceof BuiltinApprovalGate ? gate.policy : this._policy; - if (policy !== null) { - // Policy overrides win over declared annotations (apcore#76), so - // preflight reports the same verdict the gate will enforce. - requiresApproval = policy.resolve(moduleId, governance, { - // §7.9.6: preflight resolves against the same call site the gate - // will see, so the reported verdict matches the enforced one. - arguments: effectiveInputs, - context: validateCtx, - }).needsApproval; - } else { - requiresApproval = Boolean(governance?.requiresApproval); - } + const policy = gate?.policy ?? this._policy ?? DEFAULT_EXECUTION_POLICY; + // §7.9.6: preflight resolves the same policy against the same call site. + requiresApproval = policy.resolve(moduleId, governance, { + arguments: effectiveInputs, + context: validateCtx, + }).needsApproval; } // §7.9.5 — report the GOVERNANCE-effective requirement, the union of §6.9 // rows 3–5, which since v1.28.0 includes an ACL rule carrying `approval` diff --git a/typescript/src/full.ts b/typescript/src/full.ts new file mode 100644 index 00000000..748dd369 --- /dev/null +++ b/typescript/src/full.ts @@ -0,0 +1,44 @@ +import { ACL as RuntimeACL, type AclConfigLike, type AuditLogger } from './acl.js'; +import { discoverAcl, loadAclFile } from './acl-yaml.js'; +import { APCore as RuntimeAPCore, type APCoreOptions } from './client.js'; +import { createNodeLifecycleCallbacks } from './lifecycle-node.js'; +import { buildTracingMiddleware } from './observability/tracing-config.js'; +import { createRegistryFilesystem } from './registry/node-filesystem.js'; +import { Registry as RuntimeRegistry, type RegistryOptions } from './registry/registry.js'; +import { registerSysModules } from './sys-modules/entry.js'; + +export * from './node-api.js'; +export { EventEmitter } from './events/entry.js'; +export { createNodeLifecyclePlugin } from './lifecycle-node.js'; + +export class Registry extends RuntimeRegistry { + constructor(options?: RegistryOptions) { + super({ + ...options, + filesystem: options?.filesystem === undefined ? createRegistryFilesystem() : options.filesystem, + lifecycleCallbacks: options?.lifecycleCallbacks ?? createNodeLifecycleCallbacks(), + }); + } +} + +export class ACL extends RuntimeACL { + static override load(yamlPath: string, auditLogger?: AuditLogger | null): ACL { + return loadAclFile(yamlPath, auditLogger, this); + } + + static override discover(config: AclConfigLike): ACL | null { + return discoverAcl(config, path => this.load(path)); + } +} + +/** Assemble the supported Node capabilities for this client. */ +export class APCore extends RuntimeAPCore { + constructor(options?: APCoreOptions) { + super(options, { + createRegistry: (config, lifecycleCallbacks) => new Registry({ config, lifecycleCallbacks }), + discoverAcl: config => ACL.discover(config), + registerSysModules, + createTracingMiddleware: buildTracingMiddleware, + }); + } +} diff --git a/typescript/src/index.ts b/typescript/src/index.ts index 5dca4f9d..b6c08efb 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -1,459 +1,2 @@ -/** - * apcore - Schema-driven module standard. - * - * TypeScript SDK design note: this SDK exposes the APCore class as the primary - * entry point. Unlike the Python SDK, there are no module-level convenience - * functions (apcore.call(), apcore.module(), etc.) — all interaction goes - * through an APCore instance. This is an intentional design choice: TypeScript - * does not have a thread-safe global singleton model equivalent to Python's, - * and explicit instance management is idiomatic in TypeScript/Node.js. - * - * To get Python-style convenience, create a shared instance: - * const apcore = new APCore(); - * export { apcore }; - * // then: apcore.call('module.id', inputs); - * - * This file is the Node entry point. `package.json` `exports` routes browser - * bundlers to `./browser/index.ts` instead, which exposes a curated subset - * that does not depend on `node:*` builtins. - */ - -// Side-effect installs: wire Node-only filesystem loaders onto the -// browser-safe runtime modules. Must be imported before any user-facing -// re-export so the loaders are in place before APCore consumers run. -import './acl-file.js'; -import './install-lifecycle-context.js'; -import './registry/install-filesystem.js'; -import './sys-modules/overrides-file.js'; -import './sys-modules/install.js'; - -// Client -export { APCore } from './client.js'; -export type { APCoreOptions, ModuleOptions } from './client.js'; -export type { DrainAbortedContext, DrainAbortReason, DrainContext, LifecycleError, LifecycleEventFlush, LifecycleModuleReport, LifecycleOperation, LifecycleReport, LifecycleStatus, ShutdownOptions, UnregisterOptions, WatchOptions } from './lifecycle.js'; - -// Core -export { CancelToken, ExecutionCancelledError } from './cancel.js'; -export { Context, createIdentity } from './context.js'; -export { ContextKey } from './context-key.js'; -export { - TRACING_SPANS, - TRACING_SAMPLED, - METRICS_STARTS, - LOGGING_START, - REDACTED_OUTPUT, - RETRY_COUNT_BASE, -} from './context-keys.js'; -export type { Identity, ContextFactory } from './context.js'; -export { - Registry, - REGISTRY_EVENTS, - MODULE_ID_PATTERN, - MAX_MODULE_ID_LENGTH, - RESERVED_WORDS, - EPHEMERAL_NAMESPACE_PREFIX, - isEphemeralModuleId, -} from './registry/registry.js'; -export type { Discoverer, ModuleValidator } from './registry/registry.js'; -export { - Executor, - redactSensitive, - REDACTED_VALUE, - CTX_GLOBAL_DEADLINE, - CTX_TRACING_SPANS, -} from './executor.js'; -export type { StreamCompletion, StreamCompletionReason, StreamExecution, StreamStepOutcome } from './stream-completion.js'; - -// Module types -export { - DEFAULT_ANNOTATIONS, - createAnnotations, - annotationsToJSON, - annotationsFromJSON, - createPreflightResult, - TChange, - TPreviewResult, -} from './module.js'; -export type { - ModuleAnnotations, - ModuleExample, - ModuleDescription, - ResourceLimits, - ValidationResult, - PreflightCheckResult, - PreflightResult, - Module, - Change, - PreviewResult, -} from './module.js'; - -// Config -export { Config, RESERVED_NAMESPACES, discoverConfigFile } from './config.js'; - -// Error Formatter -export { ErrorFormatterRegistry } from './error-formatter.js'; -export type { ErrorFormatter } from './error-formatter.js'; - -// Approval -export { - createApprovalRequest, - createApprovalResult, - AlwaysDenyHandler, - AutoApproveHandler, - CallbackApprovalHandler, -} from './approval.js'; -export type { ApprovalRequest, ApprovalResult, ApprovalHandler } from './approval.js'; - -// Execution-time governance policy (apcore#76 RFC pilot) -export { ExecutionPolicy, PolicyRule } from './policy.js'; -export type { PolicyCallSite, PolicyDecision, PolicyRuleOverrides } from './policy.js'; - -// Errors -export { - ModuleError, - ConfigNotFoundError, - ConfigError, - ACLRuleError, - ACLDeniedError, - ApprovalError, - ApprovalDeniedError, - ApprovalTimeoutError, - ApprovalPendingError, - ModuleNotFoundError, - ModuleDisabledError, - ModuleTimeoutError, - SchemaValidationError, - SchemaNotFoundError, - SchemaParseError, - SchemaCircularRefError, - SchemaMaxDepthExceededError, - CallDepthExceededError, - CircularCallError, - CallFrequencyExceededError, - InvalidInputError, - BindingInvalidTargetError, - BindingModuleNotFoundError, - BindingCallableNotFoundError, - BindingNotCallableError, - BindingSchemaMissingError, - BindingSchemaInferenceFailedError, - BindingSchemaModeConflictError, - BindingStrictSchemaIncompatibleError, - BindingFileInvalidError, - FuncMissingTypeHintError, - FuncMissingReturnTypeError, - CircularDependencyError, - DependencyNotFoundError, - DependencyVersionMismatchError, - ModuleLoadError, - ReloadFailedError, - ModuleExecuteError, - InternalError, - ConfigNamespaceDuplicateError, - ConfigNamespaceReservedError, - ConfigEnvPrefixConflictError, - ConfigEnvMapConflictError, - ConfigMountError, - ConfigBindError, - ErrorFormatterDuplicateError, - TaskLimitExceededError, - TaskStoreError, - VersionConstraintError, - ModuleIdConflictError, - InvalidSegmentError, - IdTooLongError, - CircuitBreakerOpenError, - ModuleReloadConflictError, - SysModuleRegistrationError, - SysModulesDisabledError, - InvalidParentIdError, - StreamingInterfaceError, - DuplicateModuleIdError, - ContextBindingError, - ErrorCodes, -} from './errors.js'; -export type { ErrorCode, ErrorOptions } from './errors.js'; - -// Streaming -export { STREAMING_MARKER, isStreamingModule } from './streaming.js'; -export type { StreamingModule } from './streaming.js'; - -// ACL -export { ACL } from './acl.js'; -export type { - AccessCheckOptions, - AccessDecision, - ACLApproval, - ACLRule, - AuditEntry, - AuditLogger, - ConditionOutcome, - GovernanceProjection, - RuleValidationFinding, -} from './acl.js'; - -// Middleware -export { - Middleware, - RetrySignal, - MiddlewareManager, - MiddlewareChainError, - BeforeMiddleware, - AfterMiddleware, - LoggingMiddleware, - RetryMiddleware, - RetryHintMiddleware, - ErrorHistoryMiddleware, - PlatformNotifyMiddleware, - CircuitBreakerMiddleware, - CircuitBreakerState, - CTX_CIRCUIT_STATE, - validateContextKey, - isAsyncHandler, -} from './middleware/index.js'; -export type { - RetryConfig, - CircuitBreakerOptions, - ContextKeyWriter, - ContextKeyValidation, -} from './middleware/index.js'; - -// Decorator -export { module, FunctionModule } from './decorator.js'; - -// Extensions -export { ExtensionManager } from './extensions.js'; -export type { ExtensionPoint } from './extensions.js'; - -// Events -export { - EventEmitter, - createEvent, - WebhookSubscriber, - A2ASubscriber, - FileSubscriber, - StdoutSubscriber, - FilterSubscriber, - CircuitBreakerWrapper, - CircuitState, -} from './events/index.js'; -export type { - ApCoreEvent, - EventSubscriber, - CircuitBreakerConfig, - RetryConfig as EventRetryConfig, -} from './events/index.js'; - -// System Modules -export { - registerSysModules, - registerSubscriberType, - unregisterSubscriberType, - resetSubscriberRegistry, - createSubscriberFromConfig, - ToggleState, - DEFAULT_TOGGLE_STATE, - isModuleDisabled, - checkModuleDisabled, - classifyHealthStatus, - UpdateConfigModule, - ReloadModule, - HealthModule, - HealthSummaryModule, - ManifestModule, - ManifestFullModule, - UsageModule, - UsageSummaryModule, - ToggleFeatureModule, - InMemoryAuditStore, - FileOverridesStore, - InMemoryOverridesStore, -} from './sys-modules/index.js'; -export type { SysModulesContext, OverridesStore } from './sys-modules/index.js'; - -// Async tasks -export { - AsyncTaskManager, - TaskStatus, - InMemoryTaskStore, - RetryConfig as AsyncRetryConfig, -} from './async-task.js'; -export type { TaskInfo, TaskStore, ReaperHandle } from './async-task.js'; - -// Bindings -export { - BindingLoader, - type BindingConfigLike, - type BindingLoaderOptions, -} from './bindings.js'; - -// Utils -export { matchPattern, calculateSpecificity } from './utils/pattern.js'; -export { canonicalizeName, normalizeToCanonicalId } from './utils/normalize.js'; -export type { CanonicalNameError, CanonicalNameResult } from './utils/normalize.js'; -export { - guardCallChain, - DEFAULT_MAX_CALL_DEPTH, - DEFAULT_MAX_MODULE_REPEAT, -} from './utils/call-chain.js'; -export { propagateError } from './utils/error-propagation.js'; - -// Multi-class discovery -export { classNameToSegment, discoverMultiClass } from './registry/multi-class.js'; -export type { ClassDescriptor, MultiClassEntry } from './registry/multi-class.js'; - -// Error Code Registry -export { - ErrorCodeRegistry, - ErrorCodeCollisionError, - FRAMEWORK_ERROR_CODE_PREFIXES, -} from './error-code-registry.js'; - -// Version -export { negotiateVersion, VersionIncompatibleError } from './version.js'; - -// Schema -export { - SchemaLoader, - jsonSchemaToTypeBox, - contentHash, - contentHashAsync, -} from './schema/loader.js'; -export { SchemaValidator } from './schema/validator.js'; -export { SchemaExporter } from './schema/exporter.js'; -export { SchemaStrategy, ExportProfile } from './schema/types.js'; -export type { - SchemaDefinition, - ResolvedSchema, - SchemaValidationErrorDetail, - SchemaValidationResult, -} from './schema/types.js'; -export { RefResolver } from './schema/ref-resolver.js'; -export { toStrictSchema } from './schema/strict.js'; -export { - assertOpenAiStrictCompatible, - detectOpenAiStrictIncompatibilities, -} from './schema/openai-strict.js'; -export type { AssertOpenAiStrictOptions } from './schema/openai-strict.js'; - -// Registry types -export type { ModuleDescriptor, DiscoveredModule, DependencyInfo } from './registry/types.js'; - -// Registry conflicts -export { detectIdConflicts } from './registry/conflicts.js'; -export type { ConflictResult, ConflictType, ConflictSeverity } from './registry/conflicts.js'; - -// Observability -export { - TracingMiddleware, - StdoutExporter, - InMemoryExporter, - OTLPExporter, - createSpan, -} from './observability/tracing.js'; -export type { Span, SpanExporter } from './observability/tracing.js'; -export { MetricsCollector, MetricsMiddleware } from './observability/metrics.js'; -export { - ContextLogger, - ObsLoggingMiddleware, - RedactionConfig, - DEFAULT_REDACTION_FIELD_PATTERNS, -} from './observability/context-logger.js'; -export { - ErrorHistory, - computeFingerprint, - normalizeMessage, -} from './observability/error-history.js'; -export type { ErrorEntry } from './observability/error-history.js'; -export { UsageCollector, UsageMiddleware } from './observability/usage.js'; -export { - NoopUsageExporter, - PeriodicUsageExporter, -} from './observability/usage-exporter.js'; -export type { UsageExporter } from './observability/usage-exporter.js'; -export { - computeModuleErrorRate, - estimateP99FromHistogram, - matchesModuleId, - METRIC_CALLS_TOTAL, - METRIC_DURATION_SECONDS, -} from './observability/metrics-utils.js'; -export type { - UsageRecord, - CallerUsageSummary, - HourlyBucket, - ModuleUsageSummary, - ModuleUsageDetail, - UsageCollectorOptions, -} from './observability/usage.js'; -export { InMemoryStorageBackend } from './observability/storage.js'; -export type { StorageBackend } from './observability/storage.js'; -export { BatchSpanProcessor, SimpleSpanProcessor } from './observability/batch-span-processor.js'; -export type { - SpanProcessor, - BatchSpanProcessorOptions, -} from './observability/batch-span-processor.js'; -export { PrometheusExporter } from './observability/prometheus-exporter.js'; -export type { PrometheusExporterStartOptions } from './observability/prometheus-exporter.js'; - -// Trace Context -export { TraceContext } from './trace-context.js'; -export type { TraceParent } from './trace-context.js'; - -// Pipeline -export { - ExecutionStrategy, - PipelineEngine, - PipelineAbortError, - StepNotFoundError, - StepNotRemovableError, - StepNotReplaceableError, - StepNameDuplicateError, - StrategyNotFoundError, - PipelineStepError, - PipelineStepNotFoundError, - PipelineDependencyError, -} from './pipeline.js'; -export type { - Step, - StepResult, - PipelineContext, - PipelineState, - StepTrace, - PipelineTrace, - GovernanceState, - StrategyInfo, - StepMiddleware, -} from './pipeline.js'; - -// Built-in Steps -export { - BuiltinContextCreation, - BuiltinCallChainGuard, - BuiltinModuleLookup, - BuiltinACLCheck, - BuiltinApprovalGate, - BuiltinInputValidation, - BuiltinMiddlewareBefore, - BuiltinExecute, - BuiltinOutputValidation, - BuiltinMiddlewareAfter, - BuiltinReturnResult, - buildStandardStrategy, - buildInternalStrategy, - buildTestingStrategy, - buildPerformanceStrategy, - buildMinimalStrategy, -} from './builtin-steps.js'; -export type { StandardStrategyDeps } from './builtin-steps.js'; - -// Pipeline Configuration -export { - registerStepType, - unregisterStepType, - registeredStepTypes, - buildStrategyFromConfig, - ConfigurationError, -} from './pipeline-config.js'; - -export { VERSION } from './generated/version.js'; +/** Portable default runtime. Node capability assembly is available from apcore-js/full. */ +export * from './core.js'; diff --git a/typescript/src/install-lifecycle-context.ts b/typescript/src/install-lifecycle-context.ts deleted file mode 100644 index c4ec9c37..00000000 --- a/typescript/src/install-lifecycle-context.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { AsyncLocalStorage } from 'node:async_hooks'; -import { _setLifecycleCallbackContext } from './lifecycle.js'; - -_setLifecycleCallbackContext(new AsyncLocalStorage()); diff --git a/typescript/src/lifecycle-node.ts b/typescript/src/lifecycle-node.ts new file mode 100644 index 00000000..fdc5cb2d --- /dev/null +++ b/typescript/src/lifecycle-node.ts @@ -0,0 +1,12 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import type { APCorePlugin } from './client.js'; +import { LifecycleCallbacks, type LifecycleCallbackScope } from './lifecycle.js'; + +export function createNodeLifecycleCallbacks(): LifecycleCallbacks { + return new LifecycleCallbacks(new AsyncLocalStorage()); +} + +/** Preserve callback ownership across asynchronous suspension for one Node client. */ +export function createNodeLifecyclePlugin(): APCorePlugin { + return { createLifecycleCallbacks: createNodeLifecycleCallbacks }; +} diff --git a/typescript/src/lifecycle.ts b/typescript/src/lifecycle.ts index 15600de5..dc598be9 100644 --- a/typescript/src/lifecycle.ts +++ b/typescript/src/lifecycle.ts @@ -1,4 +1,4 @@ -import { v4 as uuidv4 } from 'uuid'; +import { uuidV4 as uuidv4 } from './utils/uuid.js'; import { ErrorCodes, InvalidInputError, ModuleError } from './errors.js'; /** Options for the registry drain and this client's event shutdown. */ @@ -184,11 +184,11 @@ export class LifecycleCompletion { export function lifecycleHandle( snapshot: () => LifecycleReport, completion: LifecycleCompletion, - callbackOwners: readonly object[], + callbackWaitError: () => InvalidInputError | undefined, ): LifecycleOperation { return Object.freeze({ snapshot, async wait(timeoutMs?: number, signal?: AbortSignal): Promise { validateLifecycleDuration('waitTimeoutMs', timeoutMs); - const error = timeoutMs === 0 || completion.settled ? undefined : lifecycleCallbackWaitError(callbackOwners); + const error = timeoutMs === 0 || completion.settled ? undefined : callbackWaitError(); if (error) throw error; await completion.wait(timeoutMs, signal); return snapshot(); @@ -201,9 +201,13 @@ export class LifecycleProgress { readonly operation: LifecycleOperation; private readonly _completion = new LifecycleCompletion(); - constructor(kind: LifecycleReport['kind'], modules: ModuleLifecycleProgress[], callbackOwners: readonly object[]) { + constructor( + kind: LifecycleReport['kind'], modules: ModuleLifecycleProgress[], callbackOwners: readonly object[], + readonly callbacks: LifecycleCallbacks, + ) { this.report = { operationId: uuidv4(), kind, status: 'pending', modules, eventFlush: 'not_applicable' }; - this.operation = lifecycleHandle(() => freezeLifecycleReport(this.report), this._completion, [...callbackOwners, this]); + const owners = [...callbackOwners, this]; + this.operation = lifecycleHandle(() => freezeLifecycleReport(this.report), this._completion, () => callbacks.waitError(owners)); } finish(): void { @@ -227,60 +231,60 @@ export class LifecycleProgress { } } -interface CallbackScope { +export interface LifecycleCallbackScope { readonly owners: readonly object[]; - readonly parent: CallbackScope | undefined; + readonly parent: LifecycleCallbackScope | undefined; active: boolean; } -interface CallbackContext { - getStore(): CallbackScope | undefined; - run(scope: CallbackScope, callback: () => T): T; +export interface LifecycleCallbackContext { + getStore(): LifecycleCallbackScope | undefined; + run(scope: LifecycleCallbackScope, callback: () => T): T; } -let synchronousScope: CallbackScope | undefined; -let callbackContext: CallbackContext = { - getStore: () => synchronousScope, - run(scope: CallbackScope, callback: () => T): T { - const previous = synchronousScope; - synchronousScope = scope; - try { - return callback(); - } finally { - synchronousScope = previous; - } - }, -}; - -/** @internal Installed by the Node entry point. */ -export function _setLifecycleCallbackContext(context: CallbackContext): void { - callbackContext = context; +function synchronousCallbackContext(): LifecycleCallbackContext { + let current: LifecycleCallbackScope | undefined; + return { + getStore: () => current, + run(scope: LifecycleCallbackScope, callback: () => T): T { + const previous = current; + current = scope; + try { + return callback(); + } finally { + current = previous; + } + }, + }; } -/** @internal Reject a wait whose completion depends on the current callback. */ -export function lifecycleCallbackWaitError(owners: readonly object[]): InvalidInputError | undefined { - for (let scope = callbackContext.getStore(); scope !== undefined; scope = scope.parent) { - if (scope.active && scope.owners.some(owner => owners.includes(owner))) { - return new InvalidInputError('A lifecycle callback cannot wait for its own operation'); +/** Tracks which callbacks are currently holding up a lifecycle operation. */ +export class LifecycleCallbacks { + constructor(private readonly context: LifecycleCallbackContext = synchronousCallbackContext()) {} + + waitError(owners: readonly object[]): InvalidInputError | undefined { + for (let scope = this.context.getStore(); scope !== undefined; scope = scope.parent) { + if (scope.active && scope.owners.some(owner => owners.includes(owner))) { + return new InvalidInputError('A lifecycle callback cannot wait for its own operation'); + } } + return undefined; } - return undefined; -} -/** @internal Associate callback activity with operations that depend on it. */ -export function lifecycleCallback(owners: readonly object[], callback: () => T): T { - const scope: CallbackScope = { owners, parent: callbackContext.getStore(), active: true }; - const finish = (): void => { scope.active = false; }; - try { - const value = callbackContext.run(scope, callback); - if (value != null && typeof (value as { then?: unknown }).then === 'function') { - void Promise.resolve(value).then(finish, finish); - } else { + run(owners: readonly object[], callback: () => T): T { + const scope: LifecycleCallbackScope = { owners, parent: this.context.getStore(), active: true }; + const finish = (): void => { scope.active = false; }; + try { + const value = this.context.run(scope, callback); + if (value != null && typeof (value as { then?: unknown }).then === 'function') { + void Promise.resolve(value).then(finish, finish); + } else { + finish(); + } + return value; + } catch (error) { finish(); + throw error; } - return value; - } catch (error) { - finish(); - throw error; } } diff --git a/typescript/src/node-api.ts b/typescript/src/node-api.ts new file mode 100644 index 00000000..a7c16152 --- /dev/null +++ b/typescript/src/node-api.ts @@ -0,0 +1,425 @@ +// Client +export { APCore } from './client.js'; +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'; + +// Core +export { CancelToken, ExecutionCancelledError } from './cancel.js'; +export { Context, createIdentity } from './context.js'; +export { ContextKey } from './context-key.js'; +export { + TRACING_SPANS, + TRACING_SAMPLED, + METRICS_STARTS, + LOGGING_START, + REDACTED_OUTPUT, + RETRY_COUNT_BASE, +} from './context-keys.js'; +export type { Identity, ContextFactory } from './context.js'; +export { + Registry, + REGISTRY_EVENTS, + MODULE_ID_PATTERN, + MAX_MODULE_ID_LENGTH, + RESERVED_WORDS, + EPHEMERAL_NAMESPACE_PREFIX, + isEphemeralModuleId, +} from './registry/registry.js'; +export type { Discoverer, ModuleValidator, RegistryOptions } from './registry/registry.js'; +export { + Executor, + redactSensitive, + REDACTED_VALUE, + CTX_GLOBAL_DEADLINE, + CTX_TRACING_SPANS, +} from './executor.js'; +export type { StreamCompletion, StreamCompletionReason, StreamExecution, StreamStepOutcome } from './stream-completion.js'; + +// Module types +export { + DEFAULT_ANNOTATIONS, + createAnnotations, + annotationsToJSON, + annotationsFromJSON, + createPreflightResult, + TChange, + TPreviewResult, +} from './module.js'; +export type { + ModuleAnnotations, + ModuleExample, + ModuleDescription, + ResourceLimits, + ValidationResult, + PreflightCheckResult, + PreflightResult, + Module, + Change, + PreviewResult, +} from './module.js'; + +// Config +export { Config, RESERVED_NAMESPACES, discoverConfigFile } from './config.js'; + +// Error Formatter +export { ErrorFormatterRegistry } from './error-formatter.js'; +export type { ErrorFormatter } from './error-formatter.js'; + +// Approval +export { + createApprovalRequest, + createApprovalResult, + AlwaysDenyHandler, + AutoApproveHandler, + CallbackApprovalHandler, +} from './approval.js'; +export type { ApprovalRequest, ApprovalResult, ApprovalHandler } from './approval.js'; + +// Execution-time governance policy (apcore#76 RFC pilot) +export { ExecutionPolicy, PolicyRule } from './policy.js'; +export type { PolicyCallSite, PolicyDecision, PolicyRuleOverrides } from './policy.js'; + +// Errors +export { + ModuleError, + ConfigNotFoundError, + ConfigError, + ACLRuleError, + ACLDeniedError, + ApprovalError, + ApprovalDeniedError, + ApprovalTimeoutError, + ApprovalPendingError, + ModuleNotFoundError, + ModuleDisabledError, + ModuleTimeoutError, + SchemaValidationError, + SchemaNotFoundError, + SchemaParseError, + SchemaCircularRefError, + SchemaMaxDepthExceededError, + CallDepthExceededError, + CircularCallError, + CallFrequencyExceededError, + InvalidInputError, + BindingInvalidTargetError, + BindingModuleNotFoundError, + BindingCallableNotFoundError, + BindingNotCallableError, + BindingSchemaMissingError, + BindingSchemaInferenceFailedError, + BindingSchemaModeConflictError, + BindingStrictSchemaIncompatibleError, + BindingFileInvalidError, + FuncMissingTypeHintError, + FuncMissingReturnTypeError, + CircularDependencyError, + DependencyNotFoundError, + DependencyVersionMismatchError, + ModuleLoadError, + ReloadFailedError, + ModuleExecuteError, + InternalError, + ConfigNamespaceDuplicateError, + ConfigNamespaceReservedError, + ConfigEnvPrefixConflictError, + ConfigEnvMapConflictError, + ConfigMountError, + ConfigBindError, + ErrorFormatterDuplicateError, + TaskLimitExceededError, + TaskStoreError, + VersionConstraintError, + ModuleIdConflictError, + InvalidSegmentError, + IdTooLongError, + CircuitBreakerOpenError, + ModuleReloadConflictError, + SysModuleRegistrationError, + SysModulesDisabledError, + InvalidParentIdError, + StreamingInterfaceError, + DuplicateModuleIdError, + ContextBindingError, + ErrorCodes, +} from './errors.js'; +export type { ErrorCode, ErrorOptions } from './errors.js'; + +// Streaming +export { STREAMING_MARKER, isStreamingModule } from './streaming.js'; +export type { StreamingModule } from './streaming.js'; + +// ACL +export { ACL } from './acl.js'; +export type { + AccessCheckOptions, + AccessDecision, + ACLApproval, + ACLRule, + AuditEntry, + AuditLogger, + ConditionOutcome, + GovernanceProjection, + RuleValidationFinding, +} from './acl.js'; + +// Middleware +export { + Middleware, + RetrySignal, + MiddlewareManager, + MiddlewareChainError, + BeforeMiddleware, + AfterMiddleware, + LoggingMiddleware, + RetryMiddleware, + RetryHintMiddleware, + ErrorHistoryMiddleware, + PlatformNotifyMiddleware, + CircuitBreakerMiddleware, + CircuitBreakerState, + CTX_CIRCUIT_STATE, + validateContextKey, + isAsyncHandler, +} from './middleware/index.js'; +export type { + RetryConfig, + CircuitBreakerOptions, + ContextKeyWriter, + ContextKeyValidation, +} from './middleware/index.js'; + +// Decorator +export { module, FunctionModule } from './decorator.js'; + +// Extensions +export { ExtensionManager } from './extensions.js'; +export type { ExtensionPoint } from './extensions.js'; + +// Events +export { + EventEmitter, + createEvent, + WebhookSubscriber, + FileSubscriber, + StdoutSubscriber, + FilterSubscriber, + CircuitBreakerWrapper, + CircuitState, +} from './events/index.js'; +export type { + ApCoreEvent, + EventSubscriber, + CircuitBreakerConfig, + RetryConfig as EventRetryConfig, +} from './events/index.js'; + +// System Modules +export { + registerSysModules, + createSubscriberFromConfig, + ToggleState, + DEFAULT_TOGGLE_STATE, + isModuleDisabled, + checkModuleDisabled, + classifyHealthStatus, + UpdateConfigModule, + ReloadModule, + HealthModule, + HealthSummaryModule, + ManifestModule, + ManifestFullModule, + UsageModule, + UsageSummaryModule, + ToggleFeatureModule, + InMemoryAuditStore, + FileOverridesStore, + InMemoryOverridesStore, +} from './sys-modules/index.js'; +export type { SysModulesContext, OverridesStore } from './sys-modules/index.js'; + +// Async tasks +export { + AsyncTaskManager, + TaskStatus, + InMemoryTaskStore, + RetryConfig as AsyncRetryConfig, +} from './async-task.js'; +export type { TaskInfo, TaskStore, ReaperHandle } from './async-task.js'; + +// Bindings +export { + BindingLoader, + type BindingConfigLike, + type BindingLoaderOptions, +} from './bindings.js'; + +// Utils +export { matchPattern, calculateSpecificity } from './utils/pattern.js'; +export { canonicalizeName, normalizeToCanonicalId } from './utils/normalize.js'; +export type { CanonicalNameError, CanonicalNameResult } from './utils/normalize.js'; +export { + guardCallChain, + DEFAULT_MAX_CALL_DEPTH, + DEFAULT_MAX_MODULE_REPEAT, +} from './utils/call-chain.js'; +export { propagateError } from './utils/error-propagation.js'; + +// Multi-class discovery +export { classNameToSegment, discoverMultiClass } from './registry/multi-class.js'; +export type { ClassDescriptor, MultiClassEntry } from './registry/multi-class.js'; + +// Error Code Registry +export { + ErrorCodeRegistry, + ErrorCodeCollisionError, + FRAMEWORK_ERROR_CODE_PREFIXES, +} from './error-code-registry.js'; + +// Version +export { negotiateVersion, VersionIncompatibleError } from './version.js'; + +// Schema +export { + SchemaLoader, + jsonSchemaToTypeBox, + contentHash, + contentHashAsync, +} from './schema/loader.js'; +export { SchemaValidator } from './schema/validator.js'; +export { SchemaExporter } from './schema/exporter.js'; +export { SchemaStrategy, ExportProfile } from './schema/types.js'; +export type { + SchemaDefinition, + ResolvedSchema, + SchemaValidationErrorDetail, + SchemaValidationResult, +} from './schema/types.js'; +export { RefResolver } from './schema/ref-resolver.js'; +export { toStrictSchema } from './schema/strict.js'; +export { + assertOpenAiStrictCompatible, + detectOpenAiStrictIncompatibilities, +} from './schema/openai-strict.js'; +export type { AssertOpenAiStrictOptions } from './schema/openai-strict.js'; + +// Registry types +export type { ModuleDescriptor, DiscoveredModule, DependencyInfo } from './registry/types.js'; + +// Registry conflicts +export { detectIdConflicts } from './registry/conflicts.js'; +export type { ConflictResult, ConflictType, ConflictSeverity } from './registry/conflicts.js'; + +// Observability +export { + TracingMiddleware, + StdoutExporter, + InMemoryExporter, + OTLPExporter, + createSpan, +} from './observability/tracing.js'; +export type { Span, SpanExporter } from './observability/tracing.js'; +export { MetricsCollector, MetricsMiddleware } from './observability/metrics.js'; +export { + ContextLogger, + ObsLoggingMiddleware, + RedactionConfig, + DEFAULT_REDACTION_FIELD_PATTERNS, +} from './observability/context-logger.js'; +export { + ErrorHistory, + computeFingerprint, + normalizeMessage, +} from './observability/error-history.js'; +export type { ErrorEntry } from './observability/error-history.js'; +export { UsageCollector, UsageMiddleware } from './observability/usage.js'; +export { + NoopUsageExporter, + PeriodicUsageExporter, +} from './observability/usage-exporter.js'; +export type { UsageExporter } from './observability/usage-exporter.js'; +export { + computeModuleErrorRate, + estimateP99FromHistogram, + matchesModuleId, + METRIC_CALLS_TOTAL, + METRIC_DURATION_SECONDS, +} from './observability/metrics-utils.js'; +export type { + UsageRecord, + CallerUsageSummary, + HourlyBucket, + ModuleUsageSummary, + ModuleUsageDetail, + UsageCollectorOptions, +} from './observability/usage.js'; +export { InMemoryStorageBackend } from './observability/storage.js'; +export type { StorageBackend } from './observability/storage.js'; +export { BatchSpanProcessor, SimpleSpanProcessor } from './observability/batch-span-processor.js'; +export type { + SpanProcessor, + BatchSpanProcessorOptions, +} from './observability/batch-span-processor.js'; +export { renderPrometheusMetrics } from './observability/prometheus.js'; + +// Trace Context +export { TraceContext } from './trace-context.js'; +export type { TraceParent } from './trace-context.js'; + +// Pipeline +export { + ExecutionStrategy, + PipelineEngine, + PipelineAbortError, + StepNotFoundError, + StepNotRemovableError, + StepNotReplaceableError, + StepNameDuplicateError, + StrategyNotFoundError, + PipelineStepError, + PipelineStepNotFoundError, + PipelineDependencyError, +} from './pipeline.js'; +export type { + Step, + StepResult, + PipelineContext, + PipelineState, + StepTrace, + PipelineTrace, + GovernanceState, + StrategyInfo, + StepMiddleware, +} from './pipeline.js'; + +// Built-in Steps +export { + BuiltinContextCreation, + BuiltinCallChainGuard, + BuiltinModuleLookup, + BuiltinACLCheck, + BuiltinApprovalGate, + BuiltinInputValidation, + BuiltinMiddlewareBefore, + BuiltinExecute, + BuiltinOutputValidation, + BuiltinMiddlewareAfter, + BuiltinReturnResult, + buildStandardStrategy, + buildInternalStrategy, + buildTestingStrategy, + buildPerformanceStrategy, + buildMinimalStrategy, +} from './builtin-steps.js'; +export type { StandardStrategyDeps } from './builtin-steps.js'; + +// Pipeline Configuration +export { + registerStepType, + unregisterStepType, + registeredStepTypes, + buildStrategyFromConfig, + ConfigurationError, +} from './pipeline-config.js'; + +export { VERSION } from './generated/version.js'; diff --git a/typescript/src/observability/index.ts b/typescript/src/observability/index.ts index 01cfc519..b6651ca1 100644 --- a/typescript/src/observability/index.ts +++ b/typescript/src/observability/index.ts @@ -1,37 +1,3 @@ -export { - TracingMiddleware, - StdoutExporter, - InMemoryExporter, - OTLPExporter, - createSpan, -} from './tracing.js'; -export type { Span, SpanExporter } from './tracing.js'; -export { MetricsCollector, MetricsMiddleware } from './metrics.js'; -export type { MetricsCollectorOptions } from './metrics.js'; -export { - ContextLogger, - ObsLoggingMiddleware, - RedactionConfig, - DEFAULT_REDACTION_FIELD_PATTERNS, -} from './context-logger.js'; +export * from './portable.js'; export { ErrorHistory, normalizeMessage, computeFingerprint } from './error-history.js'; export type { ErrorEntry, ErrorHistoryOptions } from './error-history.js'; -export { UsageCollector, UsageMiddleware, bucketKey } from './usage.js'; -export { NoopUsageExporter, PeriodicUsageExporter } from './usage-exporter.js'; -export type { UsageExporter } from './usage-exporter.js'; -export type { - UsageRecord, - CallerUsageSummary, - HourlyBucket, - ModuleUsageSummary, - ModuleUsageDetail, - UsageCollectorOptions, -} from './usage.js'; -export { InMemoryObservabilityStore } from './store.js'; -export type { ObservabilityStore, MetricPoint } from './store.js'; -export { InMemoryStorageBackend } from './storage.js'; -export type { StorageBackend } from './storage.js'; -export { BatchSpanProcessor, SimpleSpanProcessor } from './batch-span-processor.js'; -export type { SpanProcessor, BatchSpanProcessorOptions } from './batch-span-processor.js'; -export { PrometheusExporter } from './prometheus-exporter.js'; -export type { PrometheusExporterStartOptions } from './prometheus-exporter.js'; diff --git a/typescript/src/observability/portable.ts b/typescript/src/observability/portable.ts new file mode 100644 index 00000000..66b8d46c --- /dev/null +++ b/typescript/src/observability/portable.ts @@ -0,0 +1,34 @@ +export { + TracingMiddleware, + StdoutExporter, + InMemoryExporter, + OTLPExporter, + createSpan, +} from './tracing.js'; +export type { Span, SpanExporter } from './tracing.js'; +export { MetricsCollector, MetricsMiddleware } from './metrics.js'; +export type { MetricsCollectorOptions } from './metrics.js'; +export { + ContextLogger, + ObsLoggingMiddleware, + RedactionConfig, + DEFAULT_REDACTION_FIELD_PATTERNS, +} from './context-logger.js'; +export { UsageCollector, UsageMiddleware, bucketKey } from './usage.js'; +export { NoopUsageExporter, PeriodicUsageExporter } from './usage-exporter.js'; +export type { UsageExporter } from './usage-exporter.js'; +export type { + UsageRecord, + CallerUsageSummary, + HourlyBucket, + ModuleUsageSummary, + ModuleUsageDetail, + UsageCollectorOptions, +} from './usage.js'; +export { InMemoryObservabilityStore } from './store.js'; +export type { ObservabilityStore, MetricPoint } from './store.js'; +export { InMemoryStorageBackend } from './storage.js'; +export type { StorageBackend } from './storage.js'; +export { BatchSpanProcessor, SimpleSpanProcessor } from './batch-span-processor.js'; +export type { SpanProcessor, BatchSpanProcessorOptions } from './batch-span-processor.js'; +export { renderPrometheusMetrics } from './prometheus.js'; diff --git a/typescript/src/observability/prometheus-exporter.ts b/typescript/src/observability/prometheus-exporter.ts deleted file mode 100644 index 20d4f4d0..00000000 --- a/typescript/src/observability/prometheus-exporter.ts +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Prometheus text-format exporter with /metrics, /healthz, and /readyz HTTP endpoints. - */ - -import { createServer, type Server } from 'node:http'; -import type { MetricsCollector } from './metrics.js'; -import type { UsageCollector } from './usage.js'; - -function computePercentiles(values: number[], ps: readonly number[]): number[] { - if (values.length === 0) return ps.map(() => 0); - const sorted = [...values].sort((a, b) => a - b); - return ps.map((p) => { - const idx = Math.ceil((p / 100) * sorted.length) - 1; - return sorted[Math.max(0, idx)]; - }); -} - -export interface PrometheusExporterStartOptions { - port?: number; - path?: string; -} - -/** - * Serves Prometheus text metrics and K8s health endpoints over HTTP. - * - * Serves: - * GET {path} (default /metrics) — Prometheus text exposition format - * GET /healthz — liveness probe, always 200 OK - * GET /readyz — readiness probe, 200 OK after markReady() is called - */ -export class PrometheusExporter { - private readonly _collector: MetricsCollector; - private readonly _usageCollector: UsageCollector | null; - private _server: Server | null = null; - private _ready = false; - - constructor(options: { collector: MetricsCollector; usageCollector?: UsageCollector }) { - this._collector = options.collector; - this._usageCollector = options.usageCollector ?? null; - } - - /** Return current metrics in Prometheus text exposition format. */ - export(): string { - let output = this._collector.exportPrometheus(); - if (this._usageCollector !== null) { - output += this._exportUsageMetrics(); - } - return output; - } - - private _exportUsageMetrics(): string { - const summaries = this._usageCollector!.getSummary(); - if (summaries.length === 0) return ''; - - // Build per-metric-family lines so HELP/TYPE immediately precede each family's data. - const callFamilies = [ - { name: 'apcore_usage_calls_24h', help: 'Module calls in the last 24 hours by status' }, - { name: 'apcore_usage_calls_total', help: 'Deprecated alias of apcore_usage_calls_24h' }, - ].map(({ name, help }) => ({ name, lines: [`# HELP ${name} ${help}`, `# TYPE ${name} gauge`] })); - const errorRateLines: string[] = [ - '# HELP apcore_usage_error_rate Module error rate (0.0-1.0)', - '# TYPE apcore_usage_error_rate gauge', - ]; - const p50Lines: string[] = [ - '# HELP apcore_usage_p50_latency_ms Module p50 latency in milliseconds', - '# TYPE apcore_usage_p50_latency_ms gauge', - ]; - const p95Lines: string[] = [ - '# HELP apcore_usage_p95_latency_ms Module p95 latency in milliseconds', - '# TYPE apcore_usage_p95_latency_ms gauge', - ]; - const p99Lines: string[] = [ - '# HELP apcore_usage_p99_latency_ms Module p99 latency in milliseconds', - '# TYPE apcore_usage_p99_latency_ms gauge', - ]; - - for (const summary of summaries) { - const { moduleId, callCount, errorCount } = summary; - const successCount = callCount - errorCount; - const errorRate = callCount > 0 ? errorCount / callCount : 0; - - for (const { name, lines } of callFamilies) { - lines.push(`${name}{module_id="${moduleId}",status="success"} ${successCount}`); - lines.push(`${name}{module_id="${moduleId}",status="error"} ${errorCount}`); - } - errorRateLines.push(`apcore_usage_error_rate{module_id="${moduleId}"} ${errorRate}`); - - const latencies = this._usageCollector!.getLatencies(moduleId); - const [p50, p95, p99] = computePercentiles(latencies, [50, 95, 99]); - p50Lines.push(`apcore_usage_p50_latency_ms{module_id="${moduleId}"} ${p50}`); - p95Lines.push(`apcore_usage_p95_latency_ms{module_id="${moduleId}"} ${p95}`); - p99Lines.push(`apcore_usage_p99_latency_ms{module_id="${moduleId}"} ${p99}`); - } - - return [...callFamilies.flatMap(({ lines }) => lines), ...errorRateLines, ...p50Lines, ...p95Lines, ...p99Lines] - .join('\n') + '\n'; - } - - /** Signal that the application is ready to serve traffic (/readyz → 200). */ - markReady(): void { - this._ready = true; - } - - /** Start the HTTP server in a background listener. */ - start(options?: PrometheusExporterStartOptions): void { - const port = options?.port ?? 9090; - const metricsPath = options?.path ?? '/metrics'; - - if (this._server !== null) { - throw new Error('PrometheusExporter is already running. Call stop() first.'); - } - - this._server = createServer((req, res) => { - const pathname = (req.url ?? '/').split('?', 1)[0]; - if (pathname === metricsPath) { - const body = Buffer.from(this.export(), 'utf-8'); - res.writeHead(200, { - 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8', - 'Content-Length': String(body.length), - }); - res.end(body); - } else if (pathname === '/healthz') { - res.writeHead(200); - res.end('OK'); - } else if (pathname === '/readyz') { - if (this._ready) { - res.writeHead(200); - res.end('OK'); - } else { - res.writeHead(503); - res.end('Not ready'); - } - } else { - res.writeHead(404); - res.end(); - } - }); - - this._server.listen(port); - } - - /** Shut down the HTTP server. */ - stop(): Promise { - return new Promise((resolve) => { - if (this._server !== null) { - const server = this._server; - this._server = null; - server.close(() => resolve()); - server.closeIdleConnections(); - } else { - resolve(); - } - }); - } -} diff --git a/typescript/src/observability/prometheus.ts b/typescript/src/observability/prometheus.ts new file mode 100644 index 00000000..f6806ad3 --- /dev/null +++ b/typescript/src/observability/prometheus.ts @@ -0,0 +1,72 @@ +/** Render metrics without opening a listener or depending on Node. */ + +import type { MetricsCollector } from './metrics.js'; +import type { UsageCollector } from './usage.js'; + +type PrometheusUsageCollector = Pick; + +function computePercentiles(values: number[], ps: readonly number[]): number[] { + if (values.length === 0) return ps.map(() => 0); + const sorted = [...values].sort((a, b) => a - b); + return ps.map((p) => { + const idx = Math.ceil((p / 100) * sorted.length) - 1; + return sorted[Math.max(0, idx)]; + }); +} + +function renderUsageMetrics(usageCollector: PrometheusUsageCollector): string { + const summaries = usageCollector.getSummary(); + if (summaries.length === 0) return ''; + + // Build per-metric-family lines so HELP/TYPE immediately precede each family's data. + const callFamilies = [ + { name: 'apcore_usage_calls_24h', help: 'Module calls in the last 24 hours by status' }, + { name: 'apcore_usage_calls_total', help: 'Deprecated alias of apcore_usage_calls_24h' }, + ].map(({ name, help }) => ({ name, lines: [`# HELP ${name} ${help}`, `# TYPE ${name} gauge`] })); + const errorRateLines: string[] = [ + '# HELP apcore_usage_error_rate Module error rate (0.0-1.0)', + '# TYPE apcore_usage_error_rate gauge', + ]; + const p50Lines: string[] = [ + '# HELP apcore_usage_p50_latency_ms Module p50 latency in milliseconds', + '# TYPE apcore_usage_p50_latency_ms gauge', + ]; + const p95Lines: string[] = [ + '# HELP apcore_usage_p95_latency_ms Module p95 latency in milliseconds', + '# TYPE apcore_usage_p95_latency_ms gauge', + ]; + const p99Lines: string[] = [ + '# HELP apcore_usage_p99_latency_ms Module p99 latency in milliseconds', + '# TYPE apcore_usage_p99_latency_ms gauge', + ]; + + for (const summary of summaries) { + const { moduleId, callCount, errorCount } = summary; + const successCount = callCount - errorCount; + const errorRate = callCount > 0 ? errorCount / callCount : 0; + + for (const { name, lines } of callFamilies) { + lines.push(`${name}{module_id="${moduleId}",status="success"} ${successCount}`); + lines.push(`${name}{module_id="${moduleId}",status="error"} ${errorCount}`); + } + errorRateLines.push(`apcore_usage_error_rate{module_id="${moduleId}"} ${errorRate}`); + + const latencies = usageCollector.getLatencies(moduleId); + const [p50, p95, p99] = computePercentiles(latencies, [50, 95, 99]); + p50Lines.push(`apcore_usage_p50_latency_ms{module_id="${moduleId}"} ${p50}`); + p95Lines.push(`apcore_usage_p95_latency_ms{module_id="${moduleId}"} ${p95}`); + p99Lines.push(`apcore_usage_p99_latency_ms{module_id="${moduleId}"} ${p99}`); + } + + return [...callFamilies.flatMap(({ lines }) => lines), ...errorRateLines, ...p50Lines, ...p95Lines, ...p99Lines] + .join('\n') + '\n'; +} + +/** Render the current metrics and optional usage metrics in Prometheus text format. */ +export function renderPrometheusMetrics( + collector: Pick, + usageCollector?: PrometheusUsageCollector, +): string { + const metrics = collector.exportPrometheus(); + return usageCollector === undefined ? metrics : metrics + renderUsageMetrics(usageCollector); +} diff --git a/typescript/src/observability/usage.ts b/typescript/src/observability/usage.ts index 19fc3620..fde85f47 100644 --- a/typescript/src/observability/usage.ts +++ b/typescript/src/observability/usage.ts @@ -299,6 +299,7 @@ export class UsageCollector { private _cleanupExpired(moduleId: string): void { const cutoff = new Date(Date.now() - this.retentionHours * 3600_000); + if (Number.isNaN(cutoff.getTime())) return; const cutoffKey = bucketKey(cutoff); const mod = this._data.get(moduleId); if (!mod) return; diff --git a/typescript/src/policy.ts b/typescript/src/policy.ts index e3ffe4eb..6787736e 100644 --- a/typescript/src/policy.ts +++ b/typescript/src/policy.ts @@ -40,10 +40,10 @@ const RULE_KEYS = new Set(['pattern', 'requires_approval', 'destructive', 'reaso * decision made by accident. `fromObject` already fails loud on unknown keys * for the same reason; this extends that discipline to the values. * - * `undefined` / `null` mean "unset" and take the documented default of `false`. + * `undefined` / `null` mean "unset" and take the documented default of `true`. */ function _requireBoolean(value: unknown, key: string): boolean { - if (value === undefined || value === null) return false; + if (value === undefined || value === null) return true; if (typeof value !== 'boolean') { const kind = Array.isArray(value) ? 'array' : typeof value; throw new Error( @@ -197,14 +197,13 @@ export class ExecutionPolicy { private readonly _rules: readonly PolicyRule[]; /** * When true, modules whose effective `destructive` annotation is true require - * approval even if `requiresApproval` is false — the opt-in resolution of the - * destructive↔approval gap described in apcore#76. + * approval even if `requiresApproval` is false. Defaults to true. */ readonly gateDestructive: boolean; /** * When true, the approval gate fails closed (denies) when a module needs - * approval but no ApprovalHandler is configured. When false (default), the - * gate keeps the PROTOCOL_SPEC §7.4 skip behavior but logs a warning. + * approval but no ApprovalHandler is configured. Defaults to true. + * Set false to warn and continue (PROTOCOL_SPEC §7.4). */ readonly strict: boolean; @@ -219,8 +218,8 @@ export class ExecutionPolicy { } } this._rules = frozen; - this.gateDestructive = Boolean(options.gateDestructive); - this.strict = Boolean(options.strict); + this.gateDestructive = _requireBoolean(options.gateDestructive, 'gateDestructive'); + this.strict = _requireBoolean(options.strict, 'strict'); } /** The policy's rules as an immutable array. */ @@ -386,3 +385,7 @@ export function applyDecisionToAnnotations( destructive: decision.destructive, }); } + +/** @internal Effective policy when no explicit execution policy was supplied. */ +export const DEFAULT_EXECUTION_POLICY = new ExecutionPolicy(); +Object.freeze(DEFAULT_EXECUTION_POLICY); diff --git a/typescript/src/registry/install-filesystem.ts b/typescript/src/registry/install-filesystem.ts deleted file mode 100644 index 10b52237..00000000 --- a/typescript/src/registry/install-filesystem.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** Installs filesystem registry operations for the Node package entry point. */ -import { accessSync, realpathSync, watch } from 'node:fs'; -import * as path from 'node:path'; -import { pathToFileURL } from 'node:url'; -import { loadIdMap, loadMetadata } from './metadata.js'; -import { _setRegistryFilesystem } from './registry.js'; -import { scanExtensions, scanMultiRoot } from './scanner.js'; - -let reloadGeneration = 0; - -export const registryNodeFilesystem = { - fs: { - accessSync, - realpathSync, - watch(directory: string, options: { recursive: boolean }, listener: (event: string, filename: string | null) => void) { - return watch(directory, options, listener); - }, - }, - path, - entryPointSpecifier(filePath: string, reload: boolean): string { - const url = pathToFileURL(filePath); - if (reload) { - url.searchParams.set('apcore-reload', String(++reloadGeneration)); - } - return url.href; - }, - loadIdMap, - loadMetadata, - scanExtensions, - scanMultiRoot, -}; - -_setRegistryFilesystem(registryNodeFilesystem); diff --git a/typescript/src/registry/managed-drain.ts b/typescript/src/registry/managed-drain.ts index 7d3dbca4..437fdd81 100644 --- a/typescript/src/registry/managed-drain.ts +++ b/typescript/src/registry/managed-drain.ts @@ -1,7 +1,7 @@ import { type DrainAbortReason, type DrainContext, - lifecycleCallback, + type LifecycleCallbacks, LifecycleCompletion, lifecycleError, type LifecycleProgress, @@ -44,7 +44,7 @@ export async function runManagedDrain(options: DrainOptions): Promise<{ forced: remainingMs: () => Math.max(0, Math.floor(deadline - performance.now())), }; void idle.then(wakeIfReady); - const hook = invokeDrainHook(module, context, progress, [callbackOwner, owner], wakeIfReady); + const hook = invokeDrainHook(module, context, progress, owner.callbacks, [callbackOwner, owner], wakeIfReady); wakeIfReady(); await decision.wait(Math.max(0, Math.ceil(deadline - performance.now()))); @@ -74,6 +74,7 @@ function invokeDrainHook( module: Module, context: DrainContext, progress: ModuleLifecycleProgress, + callbacks: LifecycleCallbacks, owners: readonly object[], onSettle: () => void, ): void | Promise { @@ -86,7 +87,7 @@ function invokeDrainHook( const hook = module.onDrain; if (typeof hook !== 'function') return; progress.activeHook = 'on_drain'; - const work = lifecycleCallback(owners, () => hook.call(module, context)); + const work = callbacks.run(owners, () => hook.call(module, context)); if (work !== undefined) return Promise.resolve(work).then(finish, fail); finish(); } catch (error) { diff --git a/typescript/src/registry/node-filesystem.ts b/typescript/src/registry/node-filesystem.ts new file mode 100644 index 00000000..795a2e9a --- /dev/null +++ b/typescript/src/registry/node-filesystem.ts @@ -0,0 +1,34 @@ +/** Filesystem capability for a Node discovery instance. */ +import { randomUUID } from 'node:crypto'; +import { accessSync, realpathSync, watch } from 'node:fs'; +import * as path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { loadIdMap, loadMetadata } from './metadata.js'; +import type { RegistryFilesystem } from './registry.js'; +import { scanExtensions, scanMultiRoot } from './scanner.js'; + +export function createRegistryFilesystem(): RegistryFilesystem { + const cacheNamespace = randomUUID(); + let reloadGeneration = 0; + return { + fs: { + accessSync, + realpathSync, + watch(directory: string, options: { recursive: boolean }, listener: (event: string, filename: string | null) => void) { + return watch(directory, options, listener); + }, + }, + path, + entryPointSpecifier(filePath: string, reload: boolean): string { + const url = pathToFileURL(filePath); + if (reload) { + url.searchParams.set('apcore-reload', `${cacheNamespace}-${++reloadGeneration}`); + } + return url.href; + }, + loadIdMap, + loadMetadata, + scanExtensions, + scanMultiRoot, + }; +} diff --git a/typescript/src/registry/registry.ts b/typescript/src/registry/registry.ts index 0036e077..3c4c41a6 100644 --- a/typescript/src/registry/registry.ts +++ b/typescript/src/registry/registry.ts @@ -20,7 +20,7 @@ import { } from '../errors.js'; import { type DrainAbortReason, - lifecycleCallback, + LifecycleCallbacks, LifecycleCompletion, lifecycleError, LifecycleProgress, @@ -39,7 +39,7 @@ import { resolveEntryPoint } from './entry-point.js'; import { mergeModuleMetadata, parseDependencies, snapshotRegistryData } from './metadata-pure.js'; import { governanceUnion } from '../schema/annotations.js'; import { _discoverMultiClass } from './multi-class.js'; -import { getSchema } from './schema-export.js'; +import { getSchema } from './schema-query.js'; import { toStrictSchema } from '../schema/strict.js'; import type { DependencyInfo, DiscoveredModule, ModuleDescriptor } from './types.js'; import { validateModule } from './validation.js'; @@ -55,17 +55,42 @@ export interface RegistrationSnapshot { readonly generation: ExecutionGeneration; } -type RegistryFilesystem = { - fs: Pick & { - watch(path: string, options: { recursive: boolean }, listener: (event: string, filename: string | null) => void): import('node:fs').FSWatcher; +/** Filesystem services supplied by a discovery extension. */ +export interface RegistryFilesystem { + fs: { + accessSync(path: string): void; + realpathSync: { native(path: string): string }; + watch( + path: string, + options: { recursive: boolean }, + listener: (event: string, filename: string | null) => void, + ): { close(): void; on(event: 'error', listener: (error: Error) => void): unknown }; + }; + path: { + isAbsolute(path: string): boolean; + resolve(...paths: string[]): string; + join(...paths: string[]): string; + basename(path: string, suffix?: string): string; + extname(path: string): string; }; - path: typeof import('node:path'); entryPointSpecifier(filePath: string, reload: boolean): string; - loadIdMap: typeof import('./metadata.js').loadIdMap; - loadMetadata: typeof import('./metadata.js').loadMetadata; - scanExtensions: typeof import('./scanner.js').scanExtensions; - scanMultiRoot: typeof import('./scanner.js').scanMultiRoot; -}; + loadIdMap(idMapPath: string): Record>; + loadMetadata(metaPath: string): Record; + scanExtensions(root: string, maxDepth?: number, followSymlinks?: boolean, ignorePatterns?: readonly string[]): DiscoveredModule[]; + scanMultiRoot( + roots: Array>, maxDepth?: number, followSymlinks?: boolean, ignorePatterns?: readonly string[], + ): DiscoveredModule[]; +} + +export interface RegistryOptions { + config?: Config | null; + extensionsDir?: string | null; + extensionsDirs?: Array> | null; + idMapPath?: string | null; + /** Pass a capability to enable discovery explicitly, or null to use only in-memory operations. */ + filesystem?: RegistryFilesystem | null; + lifecycleCallbacks?: LifecycleCallbacks; +} interface DiscoveredRegistration { readonly sourceFile: string; @@ -115,20 +140,6 @@ interface ReloadReservation { publishedVersion?: string; } -let registryFilesystem: RegistryFilesystem | null = null; - -/** @internal Installed by the Node entry point. */ -export function _setRegistryFilesystem(filesystem: RegistryFilesystem): void { - registryFilesystem = filesystem; -} - -function requireRegistryFilesystem(): RegistryFilesystem { - if (registryFilesystem === null) { - throw new Error('Filesystem registry operations require the Node entry point. Register modules programmatically in browsers.'); - } - return registryFilesystem; -} - /** * One-shot deprecation flag for the legacy 4-arg * `Registry.discoverMultiClass(filePath, classes, extensionsRoot, multiClassEnabled)` @@ -456,12 +467,13 @@ export class Registry { */ private _eventEmitter: EventEmitter | null = null; - constructor(options?: { - config?: Config | null; - extensionsDir?: string | null; - extensionsDirs?: Array> | null; - idMapPath?: string | null; - }) { + private readonly _filesystem: RegistryFilesystem | null; + /** @internal Used by components that share this registry's lifecycle. */ + readonly lifecycleCallbacks: LifecycleCallbacks; + + constructor(options?: RegistryOptions) { + this._filesystem = options?.filesystem ?? null; + this.lifecycleCallbacks = options?.lifecycleCallbacks ?? new LifecycleCallbacks(); const config = options?.config ?? null; const extensionsDir = options?.extensionsDir ?? null; const extensionsDirs = options?.extensionsDirs ?? null; @@ -506,10 +518,18 @@ export class Registry { this._idMapPath = options?.idMapPath ?? idMapFromConfig(config); } + private _requireFilesystem(): RegistryFilesystem { + const filesystem = this._filesystem; + if (filesystem === null) { + throw new Error('Filesystem registry operations require a discovery extension. Register modules programmatically without it.'); + } + return filesystem; + } + /** Lazily load the ID map from disk on first discover(). */ private async _ensureIdMap(): Promise { if (this._idMapLoaded || this._idMapPath === null) return; - this._idMap = requireRegistryFilesystem().loadIdMap(this._idMapPath); + this._idMap = this._requireFilesystem().loadIdMap(this._idMapPath); this._idMapLoaded = true; } @@ -652,9 +672,9 @@ export class Registry { const hasNamespace = this._extensionRoots.some((r) => 'namespace' in r); if (this._extensionRoots.length > 1 || hasNamespace) { - return requireRegistryFilesystem().scanMultiRoot(this._extensionRoots, maxDepth, followSymlinks, ignorePatterns); + return this._requireFilesystem().scanMultiRoot(this._extensionRoots, maxDepth, followSymlinks, ignorePatterns); } - return requireRegistryFilesystem().scanExtensions( + return this._requireFilesystem().scanExtensions( this._extensionRoots[0]['root'] as string, maxDepth, followSymlinks, @@ -695,7 +715,7 @@ export class Registry { private async _applyIdMapOverrides(discovered: import('./types.js').DiscoveredModule[]): Promise { if (Object.keys(this._idMap).length === 0) return; - const { fs: nodeFs, path: nodePath } = requireRegistryFilesystem(); + const { fs: nodeFs, path: nodePath } = this._requireFilesystem(); const resolvedRoots = this._extensionRoots.map((entry) => { const root = entry['root'] as string; return nodePath.isAbsolute(root) ? root : nodePath.resolve(root); @@ -711,10 +731,6 @@ export class Registry { // A silently-skipped override is the worst shape for this surface: // the map loads, the discovery succeeds, and the IDs are simply not // the ones the operator declared. - // Loaded through `ensureNodeModules`, never a top-level `node:fs` - // import: this module is in the browser entry's dependency graph and - // a static import pulls Node-only code into it. The import-graph - // guard catches that, which is how this comment came to exist. let rootReal: string; try { rootReal = nodeFs.realpathSync.native(root); @@ -746,7 +762,7 @@ export class Registry { ): Promise>> { const rawMetadata = new Map>(); for (const dm of discovered) { - rawMetadata.set(dm, dm.metaPath ? requireRegistryFilesystem().loadMetadata(dm.metaPath) : {}); + rawMetadata.set(dm, dm.metaPath ? this._requireFilesystem().loadMetadata(dm.metaPath) : {}); } return rawMetadata; } @@ -760,7 +776,7 @@ export class Registry { for (const dm of discovered) { const metadata = rawMetadata.get(dm) ?? {}; try { - const specifier = requireRegistryFilesystem().entryPointSpecifier(dm.filePath, reloadFiles.has(dm.filePath)); + const specifier = this._requireFilesystem().entryPointSpecifier(dm.filePath, reloadFiles.has(dm.filePath)); const module = await resolveEntryPoint(dm.filePath, metadata, specifier); resolvedModules.push([dm.canonicalId, { module, metadata, sourceFile: dm.filePath }]); } catch (e) { @@ -1125,7 +1141,7 @@ export class Registry { throw error; }; const cleanup = typeof onLoad === 'function' || options?.managed && options.beforePublish - ? lifecycleCallback([this], () => this._runOnUnload(moduleId, module)) : undefined; + ? this.lifecycleCallbacks.run([this], () => this._runOnUnload(moduleId, module)) : undefined; if (cleanup === undefined) return fail(); const failedPublication = cleanup.then(fail); this._inFlight.set(moduleId, failedPublication); @@ -1138,7 +1154,7 @@ export class Registry { if (error) throw error; if (options?.beforePublish) { if (!this._inFlight.has(moduleId)) this._inFlight.set(moduleId, Promise.resolve()); - const before = lifecycleCallback([this], () => options.beforePublish!(moduleId, module)); + const before = this.lifecycleCallbacks.run([this], () => options.beforePublish!(moduleId, module)); if (before !== undefined) { const publication = Promise.resolve(before).then(commit).catch(failPublication); this._inFlight.set(moduleId, publication); @@ -1154,7 +1170,7 @@ export class Registry { if (typeof onLoad === 'function') { this._inFlight.set(moduleId, Promise.resolve()); try { - const result: unknown = lifecycleCallback([this], () => onLoad.call(module)); + const result: unknown = this.lifecycleCallbacks.run([this], () => onLoad.call(module)); if (result != null && typeof (result as PromiseLike).then === 'function') { const promise = Promise.resolve(result).then(publish, (error: unknown) => { failLoad(error); @@ -1209,7 +1225,7 @@ export class Registry { this._assertOpen(); const generations = ids.map(id => this._executionGenerations.get(id) ?? this._latestRemoval(id)?.generation); const rows = ids.map((moduleId): ModuleLifecycleProgress => ({ moduleId, phase: 'pending' })); - const lifecycle = new LifecycleProgress('unregister_many', rows, []); + const lifecycle = new LifecycleProgress('unregister_many', rows, [], this.lifecycleCallbacks); const { drainTimeoutMs = 5_000, operationTimeoutMs, onDrainTimeout = 'continue_waiting', cancelGraceMs } = options; const policy: ManagedDrainPolicy = { timeoutMs: drainTimeoutMs, action: onDrainTimeout, cancelGraceMs }; const deadline = operationTimeoutMs === undefined ? Infinity : performance.now() + operationTimeoutMs; @@ -1749,7 +1765,7 @@ export class Registry { const generation = this._watchGeneration; const drainOptions = options === undefined ? undefined : { ...options }; - const { fs, path: nodePath } = requireRegistryFilesystem(); + const { fs, path: nodePath } = this._requireFilesystem(); const { join } = nodePath; this._watchers = []; @@ -1817,7 +1833,7 @@ export class Registry { private async _handleFileChange(filePath: string, options?: WatchOptions): Promise { const watchGeneration = this._watchGeneration; - const { path: nodePath } = requireRegistryFilesystem(); + const { path: nodePath } = this._requireFilesystem(); const { basename, extname } = nodePath; const removal = this._unregisterWatchedFile(filePath, options); if (removal !== null) await removal.completion; @@ -1988,7 +2004,7 @@ export class Registry { try { if (typeof module.onDrain === 'function' && typeof module.onDrainAborted === 'function') { row.activeHook = 'on_drain_aborted'; - await lifecycleCallback([this, owner], () => module.onDrainAborted!({ + await this.lifecycleCallbacks.run([this, owner], () => module.onDrainAborted!({ operationId: owner.report.operationId, moduleId, signal: new AbortController().signal, abortReason, })); } @@ -2034,7 +2050,7 @@ export class Registry { row.phase = 'resuming'; row.activeHook = 'on_resume'; try { - await lifecycleCallback([this, owner], () => instance.onResume!(state!)); + await this.lifecycleCallbacks.run([this, owner], () => instance.onResume!(state!)); } catch (error) { console.warn(`[apcore:registry] onResume failed for ${moduleId}:`, error); } finally { @@ -2101,7 +2117,7 @@ export class Registry { ): void { if (!emitter) return; try { - lifecycleCallback([this, owner], () => emitter.emit(createEvent(`apcore.registry.${name}`, row.moduleId, severity, { + this.lifecycleCallbacks.run([this, owner], () => emitter.emit(createEvent(`apcore.registry.${name}`, row.moduleId, severity, { operation_id: owner.report.operationId, ...data, }))); } catch (error) { @@ -2604,7 +2620,7 @@ export class Registry { }; const completeUnload = (): void => { delete progress.activeHook; - lifecycleCallback(owners, () => this._notifyUnregister(moduleId, module, options.context)); + this.lifecycleCallbacks.run(owners, () => this._notifyUnregister(moduleId, module, options.context)); progress.outcome = progress.error ? 'failed' : forcedAfterMs === undefined ? 'removed' : 'forced_removed'; if (forcedAfterMs !== undefined && generation.references > 0) { progress.cleanupPending = true; @@ -2623,7 +2639,7 @@ export class Registry { }; const unload = (): void => { progress.activeHook = 'on_unload'; - const cleanup = lifecycleCallback(owners, () => this._runOnUnload(moduleId, module, error => { + const cleanup = this.lifecycleCallbacks.run(owners, () => this._runOnUnload(moduleId, module, error => { progress.error ??= lifecycleError(error, 'unloading'); })); if (cleanup === undefined) completeUnload(); @@ -2633,7 +2649,7 @@ export class Registry { if (forcedAfterMs === undefined && options.beforeUnload) { const warn = (error: unknown): void => { console.warn(`[apcore:registry] Pre-unload hook failed for ${moduleId}:`, error); }; try { - const before = lifecycleCallback(owners, () => options.beforeUnload!(module)); + const before = this.lifecycleCallbacks.run(owners, () => options.beforeUnload!(module)); if (before !== undefined) { void before.catch(warn).then(unload); return; @@ -2675,7 +2691,7 @@ export class Registry { for (const [moduleId, generation] of this._executionGenerations) rows.set(generation, { moduleId, phase: 'pending' }); const removals = new Set(Array.from(this._removals.values()).flatMap(entries => [...entries])); for (const removal of removals) rows.set(removal.generation, removal.progress); - const lifecycle = new LifecycleProgress('shutdown', [...rows.values()], [this]); + const lifecycle = new LifecycleProgress('shutdown', [...rows.values()], [this], this.lifecycleCallbacks); const completion = lifecycle.run(async () => { this.unwatch(); this._scheduleShutdownRemovals(lifecycle, rows, removals, timeoutMs, policy); diff --git a/typescript/src/registry/schema-export.ts b/typescript/src/registry/schema-export.ts index 8d878e44..219534ce 100644 --- a/typescript/src/registry/schema-export.ts +++ b/typescript/src/registry/schema-export.ts @@ -3,41 +3,16 @@ */ import yaml from 'js-yaml'; -import type { ModuleAnnotations, ModuleExample } from '../module.js'; import { InvalidInputError, ModuleNotFoundError } from '../errors.js'; import { deepCopy } from '../utils/index.js'; import { SchemaExporter } from '../schema/exporter.js'; import { stripExtensions, toStrictSchema } from '../schema/strict.js'; -import { ExportProfile, type SchemaDefinition } from '../schema/types.js'; +import { ExportProfile } from '../schema/types.js'; import { snapshotRegistryData } from './metadata-pure.js'; +import { readSchema } from './schema-query.js'; import type { Registry } from './registry.js'; -/** Return a detached schema object for a registered module. */ -export function getSchema(registry: Registry, moduleId: string): Record | null { - return snapshotRegistryData(readSchema(registry, moduleId)); -} - -function readSchema(registry: Registry, moduleId: string): Record | null { - const module = registry.get(moduleId); - if (module === null) return null; - - const mod = module as Record; - - // A schema export, not a module manifest — exactly the four keys - // `schemas/module-schema-export.schema.json` declares. `name`, `version`, - // `tags`, `annotations` and `examples` used to ride along here, which made - // this envelope a partial, non-conforming duplicate of `system.manifest.module` - // (sys-manifest-module.schema.json) and left the three SDKs emitting three - // different shapes. Descriptor metadata belongs to the manifest module; - // callers that need it should ask for it there. TypeBox schemas are already - // JSON Schema, so they pass through unchanged. - return { - module_id: moduleId, - description: (mod['description'] as string) ?? '', - input_schema: (mod['inputSchema'] as Record) ?? {}, - output_schema: (mod['outputSchema'] as Record) ?? {}, - }; -} +export { getSchema } from './schema-query.js'; export function exportSchema( registry: Registry, @@ -53,7 +28,17 @@ export function exportSchema( } if (profile != null) { - return exportWithProfile(registry, moduleId, schemaDict, profile, format); + if (profile !== ExportProfile.GENERIC) { + throw new InvalidInputError("Only the 'generic' export profile is supported by Core"); + } + return serialize(new SchemaExporter().exportGeneric({ + moduleId, + description: schemaDict['description'] as string, + inputSchema: schemaDict['input_schema'] as Record, + outputSchema: schemaDict['output_schema'] as Record, + definitions: {}, + version: ((registry.get(moduleId) as Record | null)?.['version'] as string) ?? '1.0.0', + }), format); } const result = deepCopy(schemaDict); @@ -88,7 +73,6 @@ export function exportAllSchemas( format: string = 'json', strict: boolean = false, compact: boolean = false, - profile?: string | null, ): string { const allSchemas = readAllSchemas(registry); @@ -108,45 +92,6 @@ export function exportAllSchemas( return serialize(allSchemas, format); } -function exportWithProfile( - registry: Registry, - moduleId: string, - schemaDict: Record, - profile: string, - format: string, -): string { - const schemaDef: SchemaDefinition = { - moduleId, - description: schemaDict['description'] as string, - inputSchema: schemaDict['input_schema'] as Record, - outputSchema: schemaDict['output_schema'] as Record, - definitions: {}, - version: - ((registry.get(moduleId) as Record | null)?.['version'] as string) ?? - '1.0.0', - }; - const module = registry.get(moduleId); - const annotations = module ? (module as Record)['annotations'] as ModuleAnnotations | undefined : undefined; - const examples = module ? ((module as Record)['examples'] as ModuleExample[]) ?? [] : []; - const name = module ? (module as Record)['name'] as string | undefined : undefined; - - const validProfiles = new Set(Object.values(ExportProfile)); - if (!validProfiles.has(profile as ExportProfile)) { - throw new InvalidInputError( - `Invalid export profile: '${profile}'. Must be one of: ${[...validProfiles].join(', ')}`, - ); - } - - const exported = new SchemaExporter().export( - schemaDef, - profile as ExportProfile, - annotations, - examples, - name, - ); - return serialize(exported, format); -} - function applyCompact(schemaDict: Record): void { const desc = schemaDict['description'] as string; if (desc) { diff --git a/typescript/src/registry/schema-query.ts b/typescript/src/registry/schema-query.ts new file mode 100644 index 00000000..ec87f497 --- /dev/null +++ b/typescript/src/registry/schema-query.ts @@ -0,0 +1,29 @@ +import { snapshotRegistryData } from './metadata-pure.js'; +import type { Registry } from './registry.js'; + +/** Return a detached schema object for a registered module. */ +export function getSchema(registry: Registry, moduleId: string): Record | null { + return snapshotRegistryData(readSchema(registry, moduleId)); +} + +export function readSchema(registry: Registry, moduleId: string): Record | null { + const module = registry.get(moduleId); + if (module === null) return null; + + const mod = module as Record; + + // A schema export, not a module manifest — exactly the four keys + // `schemas/module-schema-export.schema.json` declares. `name`, `version`, + // `tags`, `annotations` and `examples` used to ride along here, which made + // this envelope a partial, non-conforming duplicate of `system.manifest.module` + // (sys-manifest-module.schema.json) and left the three SDKs emitting three + // different shapes. Descriptor metadata belongs to the manifest module; + // callers that need it should ask for it there. TypeBox schemas are already + // JSON Schema, so they pass through unchanged. + return { + module_id: moduleId, + description: (mod['description'] as string) ?? '', + input_schema: (mod['inputSchema'] as Record) ?? {}, + output_schema: (mod['outputSchema'] as Record) ?? {}, + }; +} diff --git a/typescript/src/schema/exporter.ts b/typescript/src/schema/exporter.ts index 522c3435..342d63a1 100644 --- a/typescript/src/schema/exporter.ts +++ b/typescript/src/schema/exporter.ts @@ -1,90 +1,16 @@ -/** - * SchemaExporter — converts schemas to platform-specific export formats. - */ - -import type { ModuleAnnotations, ModuleExample } from '../module.js'; -import { deepCopy } from '../utils/index.js'; -import { applyLlmDescriptions, stripExtensions, toStrictSchema } from './strict.js'; +import { InvalidInputError } from '../errors.js'; import { ExportProfile, type SchemaDefinition } from './types.js'; +/** Export protocol-neutral module schemas. */ export class SchemaExporter { export( - schemaDef: SchemaDefinition, - profile: ExportProfile, - annotations?: ModuleAnnotations | null, - examples?: ModuleExample[] | null, - name?: string | null, - ): Record { - if (profile === ExportProfile.MCP) { - return this.exportMcp(schemaDef, annotations, name); - } - if (profile === ExportProfile.OPENAI) { - return this.exportOpenai(schemaDef); - } - if (profile === ExportProfile.ANTHROPIC) { - return this.exportAnthropic(schemaDef, examples); - } - return this.exportGeneric(schemaDef); - } - - exportMcp( - schemaDef: SchemaDefinition, - annotations?: ModuleAnnotations | null, - name?: string | null, + schema: SchemaDefinition, + profile: ExportProfile = ExportProfile.GENERIC, ): Record { - return { - name: name ?? schemaDef.moduleId, - description: schemaDef.description, - inputSchema: schemaDef.inputSchema, - annotations: { - readOnlyHint: annotations?.readonly ?? false, - destructiveHint: annotations?.destructive ?? false, - idempotentHint: annotations?.idempotent ?? false, - openWorldHint: annotations?.openWorld ?? true, - }, - _meta: { - ...(annotations?.requiresApproval ? { requiresApproval: true } : {}), - ...(annotations?.streaming ? { streaming: true } : {}), - cacheable: annotations?.cacheable ?? false, - cacheTtl: annotations?.cacheTtl ?? 0, - cacheKeyFields: annotations?.cacheKeyFields ?? null, - paginated: annotations?.paginated ?? false, - paginationStyle: annotations?.paginationStyle ?? 'cursor', - }, - }; - } - - exportOpenai(schemaDef: SchemaDefinition): Record { - const schema = deepCopy(schemaDef.inputSchema); - applyLlmDescriptions(schema); - const strictSchema = toStrictSchema(schema); - return { - type: 'function', - function: { - name: schemaDef.moduleId.replace(/\./g, '_'), - description: schemaDef.description, - parameters: strictSchema, - strict: true, - }, - }; - } - - exportAnthropic( - schemaDef: SchemaDefinition, - examples?: ModuleExample[] | null, - ): Record { - const schema = deepCopy(schemaDef.inputSchema); - applyLlmDescriptions(schema); - stripExtensions(schema, false); - const result: Record = { - name: schemaDef.moduleId.replace(/\./g, '_'), - description: schemaDef.description, - input_schema: schema, - }; - if (examples && examples.length > 0) { - result['input_examples'] = examples.map((ex) => ex.inputs); + if (profile !== ExportProfile.GENERIC) { + throw new InvalidInputError("Only the 'generic' export profile is supported by Core"); } - return result; + return this.exportGeneric(schema); } exportGeneric(schemaDef: SchemaDefinition): Record { diff --git a/typescript/src/schema/strict.ts b/typescript/src/schema/strict.ts index 03a44295..e23b4518 100644 --- a/typescript/src/schema/strict.ts +++ b/typescript/src/schema/strict.ts @@ -12,46 +12,6 @@ export function toStrictSchema(schema: Record): Record; - // Only substitute when a description already exists; never inject a - // description onto a node that lacked one (Python/Rust parity — avoids - // fabricating descriptions the spec did not declare). - if ('x-llm-description' in obj && 'description' in obj) { - obj['description'] = obj['x-llm-description']; - } - - if ('properties' in obj && typeof obj['properties'] === 'object' && obj['properties'] !== null) { - for (const prop of Object.values(obj['properties'] as Record)) { - applyLlmDescriptions(prop); - } - } - if ('items' in obj && typeof obj['items'] === 'object') { - applyLlmDescriptions(obj['items']); - } - if ('prefixItems' in obj && Array.isArray(obj['prefixItems'])) { - for (const item of obj['prefixItems'] as unknown[]) { - applyLlmDescriptions(item); - } - } - for (const keyword of ['oneOf', 'anyOf', 'allOf']) { - if (keyword in obj && Array.isArray(obj[keyword])) { - for (const sub of obj[keyword] as unknown[]) { - applyLlmDescriptions(sub); - } - } - } - for (const defsKey of ['definitions', '$defs']) { - if (defsKey in obj && typeof obj[defsKey] === 'object' && obj[defsKey] !== null) { - for (const defn of Object.values(obj[defsKey] as Record)) { - applyLlmDescriptions(defn); - } - } - } -} - export function stripExtensions(node: unknown, stripDefaults: boolean = true, nameMap: boolean = false): void { if (typeof node !== 'object' || node === null || Array.isArray(node)) return; diff --git a/typescript/src/schema/types.ts b/typescript/src/schema/types.ts index 3385ba68..1db70a6a 100644 --- a/typescript/src/schema/types.ts +++ b/typescript/src/schema/types.ts @@ -12,9 +12,6 @@ export enum SchemaStrategy { } export enum ExportProfile { - MCP = 'mcp', - OPENAI = 'openai', - ANTHROPIC = 'anthropic', GENERIC = 'generic', } diff --git a/typescript/src/sys-modules/control.ts b/typescript/src/sys-modules/control.ts index 31617fcb..950124be 100644 --- a/typescript/src/sys-modules/control.ts +++ b/typescript/src/sys-modules/control.ts @@ -236,19 +236,10 @@ export class ReloadModule { readonly annotations = { readonly: false, destructive: false, idempotent: false, requiresApproval: true, openWorld: false, streaming: false, cacheable: false, cacheTtl: 0, cacheKeyFields: null, paginated: false, paginationStyle: 'cursor' as const }; readonly inputSchema = { type: 'object' as const, + additionalProperties: false, properties: { module_id: { type: 'string' as const, description: 'ID of the module to reload (mutually exclusive with path_filter)' }, path_filter: { type: 'string' as const, description: 'Glob pattern to bulk-reload matching modules (mutually exclusive with module_id)' }, - reload_dependents: { - type: 'boolean' as const, - deprecated: true, - description: - 'DEPRECATED (spec v1.51.0, D-121) — ignored, and removed at 2.0. Declared in all ' - + 'three SDKs and implemented by none, so no caller could ever rely on it. Use an ' - + 'explicit path_filter that also matches the dependents. At 2.0 this field is ' - + 'REMOVED and, because this schema sets additionalProperties: false, passing it ' - + 'becomes a validation error rather than a silent no-op.', - }, reason: { type: 'string' as const, description: 'Audit reason for the reload' }, lifecycle: reloadLifecycleOptionsSchema, }, @@ -293,43 +284,7 @@ export class ReloadModule { this._auditStore = auditStore ?? null; } - /** - * Once per INSTANCE, not per process. `reload` is called by hot-reload loops - * and watchers, so an advisory whose volume is proportional to traffic is one - * operators learn to filter out — the cadence reasoning D-89 settled. Per - * instance rather than per process for the reason D-90's notice is per token: - * a process-wide one-shot tells the first caller and leaves every later one to - * discover it in production. - */ - private _reloadDependentsWarned = false; - - /** - * Warn once that `reload_dependents` is ignored and will be removed (D-121). - * - * The field was declared in all three SDKs' input schemas and read by none — a - * spec MUST that no implementation satisfied, which is the §9.1.3 "declared - * surface reaches no mechanism" shape applied to a module input field. Three - * independent implementations skipping it is the evidence the maintainer - * decision rests on. - * - * Deprecated rather than removed now, because the input schema sets - * `additionalProperties: false`: at 2.0 the same call stops being a silent - * no-op and becomes a validation error, so a caller passing it today needs a - * release in which they are told. - */ - private _warnReloadDependents(inputs: Record): void { - if (!inputs['reload_dependents']) return; - if (this._reloadDependentsWarned) return; - this._reloadDependentsWarned = true; - console.warn( - "[apcore:sys-modules] system.control.reload: 'reload_dependents' is ignored and will be " + - 'removed at 2.0 (spec D-121). No SDK has ever implemented it. Use a path_filter that also ' + - 'matches the dependents; after removal this field becomes a validation error, not a no-op.', - ); - } - async execute(inputs: Record, context: unknown): Promise> { - this._warnReloadDependents(inputs); const { moduleId, pathFilter, reason } = this._validateInputs(inputs); const ctx = context as Context | null; const lifecycle = inputs['lifecycle']; @@ -383,7 +338,7 @@ export class ReloadModule { return [snapshot]; }); const rows = snapshots.map(({ moduleId }): ModuleLifecycleProgress => ({ moduleId, phase: 'pending' })); - const lifecycle = new LifecycleProgress('reload', rows, [this._registry]); + const lifecycle = new LifecycleProgress('reload', rows, [this._registry], this._registry.lifecycleCallbacks); const versions = new Map(); const done = await lifecycle.run(async () => { for (const [index, snapshot] of snapshots.entries()) { diff --git a/typescript/src/sys-modules/entry.ts b/typescript/src/sys-modules/entry.ts new file mode 100644 index 00000000..8603a11c --- /dev/null +++ b/typescript/src/sys-modules/entry.ts @@ -0,0 +1,17 @@ +import type { APCorePlugin } from '../client.js'; +import { registerSysModules, type RegisterSysModulesOptions } from './registration.js'; + +export { createSubscriberFromConfig, registerSysModules } from './registration.js'; +export { FileOverridesStore } from './overrides.js'; +export type { OverridesStore } from './overrides.js'; +export type { RegisterSysModulesOptions, SubscriberFactory, SysModulesContext } from './registration.js'; + +/** Attach the system-module extension to one APCore instance. */ +export function createSysModulesPlugin( + options?: Omit, +): APCorePlugin { + return { + registerSysModules: (registry, executor, config, metrics, runtime) => + registerSysModules(registry, executor, config, metrics, { ...options, ...runtime }), + }; +} diff --git a/typescript/src/sys-modules/health.ts b/typescript/src/sys-modules/health.ts index 2722a2da..d9d6cf1b 100644 --- a/typescript/src/sys-modules/health.ts +++ b/typescript/src/sys-modules/health.ts @@ -38,7 +38,14 @@ export class HealthSummaryModule { readonly outputSchema = { type: 'object' as const, properties: { - project: { type: 'object' as const, description: 'Project information' }, + project: { + type: 'object' as const, + description: 'Project information', + properties: { + name: { type: 'string' as const, description: 'Project name' }, + version: { type: 'string' as const, description: 'Configured project version' }, + }, + }, summary: { type: 'object' as const, description: 'Aggregated health counts by status' }, modules: { type: 'array' as const, description: 'Per-module health entries' }, }, @@ -92,8 +99,12 @@ export class HealthSummaryModule { } const projectName = this._config?.get('project.name', 'apcore') ?? 'apcore'; + const projectVersion = this._config?.get('project.version'); return { - project: { name: projectName }, + project: { + name: projectName, + ...(typeof projectVersion === 'string' ? { version: projectVersion } : {}), + }, summary: { total_modules: moduleIds.length, ...counts }, modules, }; diff --git a/typescript/src/sys-modules/index.ts b/typescript/src/sys-modules/index.ts index 29f9cf85..8a335474 100644 --- a/typescript/src/sys-modules/index.ts +++ b/typescript/src/sys-modules/index.ts @@ -4,7 +4,7 @@ export { ManifestModule, ManifestFullModule } from './manifest.js'; export { UpdateConfigModule, ReloadModule } from './control.js'; export type { UpdateConfigOptions } from './control.js'; export { UsageSummaryModule, UsageModule } from './usage.js'; -export { registerSysModules, registerSubscriberType, unregisterSubscriberType, resetSubscriberRegistry, createSubscriberFromConfig } from './registration.js'; +export { registerSysModules, createSubscriberFromConfig } from './registration.js'; export type { SysModulesContext, RegisterSysModulesOptions } from './registration.js'; export { InMemoryAuditStore, buildAuditEntry, extractAuditIdentity } from './audit.js'; export type { AuditEntry, AuditStore, AuditFilter, AuditAction } from './audit.js'; diff --git a/typescript/src/sys-modules/install.ts b/typescript/src/sys-modules/install.ts deleted file mode 100644 index ce4405e9..00000000 --- a/typescript/src/sys-modules/install.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Side-effect module: wires the Node-only `registerSysModules` into - * `APCore` so that `new APCore({ config })` auto-registers sys modules. - * - * Imported by the package's Node entry (`src/index.ts`). The browser - * entry intentionally does NOT import this file, which keeps the - * `sys-modules/registration.ts` chain (and its transitive `node:fs` / - * `node:path` dependencies via `events/subscribers.ts`, - * `sys-modules/control.ts`) out of the browser bundle. - */ - -import { _setSysModulesInstaller } from '../client.js'; -import { registerSysModules } from './registration.js'; - -_setSysModulesInstaller(registerSysModules); diff --git a/typescript/src/sys-modules/overrides-file.ts b/typescript/src/sys-modules/overrides-file.ts deleted file mode 100644 index cdb76e54..00000000 --- a/typescript/src/sys-modules/overrides-file.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Side-effect module: installs the Node-side overrides-file loader on - * `registerSysModules`. - * - * This file is imported by the package's Node entry (`src/index.ts`). It is - * intentionally NOT re-exported from the browser entry — browser bundles - * therefore see `_overridesLoader === null` and skip the file-loading - * branch in `registerSysModules`. - * - * Pulled out of `registration.ts` so that the `node:fs` static import - * lives on a leaf module the browser entry never reaches. - */ - -import { existsSync, readFileSync } from 'node:fs'; -import yaml from 'js-yaml'; -import { _setOverridesLoader } from './registration.js'; - -_setOverridesLoader((path: string): Record | null => { - if (!existsSync(path)) return null; - try { - const content = readFileSync(path, 'utf-8'); - const parsed = yaml.load(content); - return typeof parsed === 'object' && parsed !== null - ? (parsed as Record) - : null; - } catch (err) { - console.warn('[apcore:sys-modules] Failed to load overrides file:', err); - return null; - } -}); diff --git a/typescript/src/sys-modules/read-overrides-file.ts b/typescript/src/sys-modules/read-overrides-file.ts new file mode 100644 index 00000000..af3c1906 --- /dev/null +++ b/typescript/src/sys-modules/read-overrides-file.ts @@ -0,0 +1,16 @@ +import { existsSync, readFileSync } from 'node:fs'; +import yaml from 'js-yaml'; + +export function readFileOverrides(path: string): Record | null { + if (!existsSync(path)) return null; + try { + const content = readFileSync(path, 'utf-8'); + const parsed = yaml.load(content); + return typeof parsed === 'object' && parsed !== null + ? (parsed as Record) + : null; + } catch (err) { + console.warn('[apcore:sys-modules] Failed to load overrides file:', err); + return null; + } +} diff --git a/typescript/src/sys-modules/registration.ts b/typescript/src/sys-modules/registration.ts index 9d8eff97..0f4484a3 100644 --- a/typescript/src/sys-modules/registration.ts +++ b/typescript/src/sys-modules/registration.ts @@ -9,14 +9,15 @@ import type { MetricsCollector } from '../observability/metrics.js'; import type { AuditStore } from './audit.js'; import type { OverridesStore } from './overrides.js'; import { FileOverridesStore } from './overrides.js'; +import { readFileOverrides } from './read-overrides-file.js'; import { TOGGLE_OVERRIDE_PREFIX } from './override-update.js'; -import { SysModuleRegistrationError } from '../errors.js'; +import { ConfigError, SysModuleRegistrationError } from '../errors.js'; import { ErrorHistory } from '../observability/error-history.js'; import { ErrorHistoryMiddleware } from '../middleware/error-history.js'; import { UsageCollector, UsageMiddleware } from '../observability/usage.js'; import type { EventSubscriber } from '../events/emitter.js'; -import { createEvent, EventEmitter } from '../events/emitter.js'; -import { WebhookSubscriber, A2ASubscriber, FileSubscriber, StdoutSubscriber, FilterSubscriber } from '../events/subscribers.js'; +import { createEvent, EventEmitter } from '../events/entry.js'; +import { WebhookSubscriber, FileSubscriber, StdoutSubscriber, FilterSubscriber } from '../events/subscribers.js'; import type { RetryConfig } from '../events/retry.js'; import { CircuitBreakerWrapper } from '../events/circuit-breaker.js'; import { PlatformNotifyMiddleware } from '../middleware/platform-notify.js'; @@ -67,9 +68,7 @@ function _cfgGet( // Subscriber type registry — extensible factory for EventSubscriber types // --------------------------------------------------------------------------- -type SubscriberFactory = (config: Record) => EventSubscriber; - -const _subscriberFactories: Map = new Map(); +export type SubscriberFactory = (config: Record) => EventSubscriber; /** * Parse a subscriber's nested `retry:` block into a RetryConfig. @@ -100,8 +99,8 @@ function _parseRetryConfig(config: Record): RetryConfig | undef return retry; } -function _registerBuiltInFactories(): void { - _subscriberFactories.set('webhook', (config: Record): EventSubscriber => { +function _registerBuiltInFactories(factories: Map): void { + factories.set('webhook', (config: Record): EventSubscriber => { const url = config['url'] as string; const headers = config['headers'] as Record | undefined; const retryCount = config['retry_count'] as number | undefined; @@ -121,18 +120,7 @@ function _registerBuiltInFactories(): void { return new WebhookSubscriber(url, headers, opts); }); - _subscriberFactories.set('a2a', (config: Record): EventSubscriber => { - const platformUrl = config['platform_url'] as string; - const auth = config['auth'] as string | Record | undefined; - const timeoutMs = config['timeout_ms'] as number | undefined; - const opts: { timeoutMs?: number; retry?: RetryConfig } = {}; - if (timeoutMs !== undefined) opts.timeoutMs = timeoutMs; - const retry = _parseRetryConfig(config); - if (retry !== undefined) opts.retry = retry; - return new A2ASubscriber(platformUrl, auth, opts); - }); - - _subscriberFactories.set('file', (config: Record): EventSubscriber => { + factories.set('file', (config: Record): EventSubscriber => { const path = config['path']; if (typeof path !== 'string' || path.length === 0) { throw new Error(`file subscriber requires a non-empty "path" string field`); @@ -153,7 +141,7 @@ function _registerBuiltInFactories(): void { ); }); - _subscriberFactories.set('stdout', (config: Record): EventSubscriber => { + factories.set('stdout', (config: Record): EventSubscriber => { const format = config['format'] as string | undefined; const levelFilter = config['level_filter'] as string | undefined; const retry = _parseRetryConfig(config); @@ -167,13 +155,13 @@ function _registerBuiltInFactories(): void { ); }); - _subscriberFactories.set('filter', (config: Record): EventSubscriber => { + factories.set('filter', (config: Record): EventSubscriber => { const delegateType = config['delegate_type']; if (typeof delegateType !== 'string') { throw new Error(`filter subscriber requires a "delegate_type" string field`); } const delegateConfig = (config['delegate_config'] ?? {}) as Record; - const delegateFactory = _subscriberFactories.get(delegateType); + const delegateFactory = factories.get(delegateType); if (delegateFactory === undefined) { throw new Error(`Unknown delegate subscriber type '${delegateType}' for filter subscriber`); } @@ -190,41 +178,28 @@ function _registerBuiltInFactories(): void { }); } -// Register built-in factories on module load -_registerBuiltInFactories(); - -/** Register a custom subscriber type for config-driven instantiation. */ -export function registerSubscriberType( - typeName: string, - factory: SubscriberFactory, -): void { - _subscriberFactories.set(typeName, factory); -} - -/** Remove a previously registered subscriber type. */ -export function unregisterSubscriberType(typeName: string): void { - if (!_subscriberFactories.has(typeName)) { - throw new Error(`Subscriber type '${typeName}' is not registered`); - } - _subscriberFactories.delete(typeName); -} - -/** Reset the registry to built-in types only. Intended for test teardown. */ -export function resetSubscriberRegistry(): void { - _subscriberFactories.clear(); - _registerBuiltInFactories(); +function instanceSubscriberFactories( + custom: Readonly>, +): ReadonlyMap { + const factories = new Map(); + _registerBuiltInFactories(factories); + for (const [name, factory] of Object.entries(custom)) factories.set(name, factory); + return factories; } /** * Instantiate a single subscriber from a config object. * The `type` field selects the factory; all other fields are passed as config. */ -export function createSubscriberFromConfig(config: Record): EventSubscriber { +export function createSubscriberFromConfig( + config: Record, + subscriberFactories: Readonly> = {}, +): EventSubscriber { const typeName = config['type'] as string | undefined; if (typeof typeName !== 'string') { throw new Error('Subscriber config missing "type" field'); } - const factory = _subscriberFactories.get(typeName); + const factory = instanceSubscriberFactories(subscriberFactories).get(typeName); if (factory === undefined) { throw new Error(`Unknown subscriber type '${typeName}'`); } @@ -238,6 +213,7 @@ export function _instantiateSubscribers( config: Config, eventEmitter: EventEmitter, sysCfg: Record | null = null, + factories: ReadonlyMap = instanceSubscriberFactories({}), ): void { const subscriberConfigs = _cfgGet(sysCfg, config, 'events.subscribers', []) as ReadonlyArray>; @@ -249,7 +225,7 @@ export function _instantiateSubscribers( continue; } - const factory = _subscriberFactories.get(typeName); + const factory = factories.get(typeName); if (factory === undefined) { console.warn('[apcore:events]', `Unknown subscriber type '${typeName}', skipping`); continue; @@ -285,6 +261,10 @@ export interface RegisterSysModulesOptions { overridesPath?: string; /** Pluggable persistent override store (Issue #45.1). */ overridesStore?: OverridesStore; + /** Factories used only by this installation, layered over the built-ins. */ + subscriberFactories?: Readonly>; + /** @internal Reader used when an explicit store is combined with an overrides file. */ + overridesLoader?: OverridesLoader; auditStore?: AuditStore; /** * Per-instance ToggleState (Issue #71). When provided, the toggle module @@ -346,13 +326,6 @@ function _applyOverrides( } } -let _overridesLoader: OverridesLoader | null = null; - -/** @internal — used by `./overrides-file.ts` to install the Node-side reader. */ -export function _setOverridesLoader(fn: OverridesLoader): void { - _overridesLoader = fn; -} - /** * Auto-register all sys.* modules and middleware based on config. */ @@ -366,6 +339,7 @@ export function registerSysModules( const result: SysModulesContext = {}; const failOnError = options?.failOnError ?? false; const explicitOverridesStore = options?.overridesStore ?? null; + const overridesLoader = options?.overridesLoader ?? readFileOverrides; const auditStore = options?.auditStore ?? null; // Per-instance ToggleState (Issue #71): undefined here lets // ToggleFeatureModule fall back to DEFAULT_TOGGLE_STATE. @@ -410,22 +384,11 @@ export function registerSysModules( explicitOverridesStore ?? (overridesPath !== null ? new FileOverridesStore(overridesPath) : null); - // Load overrides file and apply after base config. The actual file - // reader is installed by the Node-only side-effect module - // `./overrides-file.js` (imported by the package's Node entry). When - // running in a browser bundle the loader is unset and overridesPath is - // silently ignored. - // - // Only needed when an explicit store displaced the synthesized file store: - // otherwise the `FileOverridesStore` built above reads the same YAML file - // in the store branch below, and running both would apply it twice. - if (explicitOverridesStore !== null && overridesPath !== null && _overridesLoader !== null) { - // Loaders installed via `_setOverridesLoader` already swallow file IO - // errors and return null, but we still defend against a future loader - // that throws — preserves the v0.21.0 fail-soft semantics. + // Read the file separately when a supplied store takes precedence. + if (explicitOverridesStore !== null && overridesPath !== null) { let parsed: Record | null = null; try { - parsed = _overridesLoader(overridesPath); + parsed = overridesLoader(overridesPath); } catch (err) { console.warn('[apcore:sys-modules] Overrides loader threw:', err); } @@ -456,6 +419,14 @@ export function registerSysModules( sysCfg = _resolveSysCfg(config); } + const retentionHours = _cfgGet(sysCfg, config, 'usage.retention_hours', 168); + if (typeof retentionHours !== 'number' || !Number.isInteger(retentionHours) || retentionHours < 1) { + throw new ConfigError('sys_modules.usage.retention_hours must be a positive integer'); + } + if (_cfgGet(sysCfg, config, 'usage.bucketing_strategy', 'hourly') !== 'hourly') { + throw new ConfigError("sys_modules.usage.bucketing_strategy must be 'hourly'"); + } + // Error history const maxPerModule = Number(_cfgGet(sysCfg, config, 'error_history.max_entries_per_module', 50)); const maxTotal = Number(_cfgGet(sysCfg, config, 'error_history.max_total_entries', 1000)); @@ -467,7 +438,7 @@ export function registerSysModules( result.errorHistoryMiddleware = ehMiddleware; // Usage tracking - const usageCollector = new UsageCollector(); + const usageCollector = new UsageCollector({ retentionHours }); result.usageCollector = usageCollector; const usageMiddleware = new UsageMiddleware(usageCollector); executor.use(usageMiddleware); @@ -518,11 +489,12 @@ export function registerSysModules( // Events system if (_cfgGet(sysCfg, config, 'events.enabled', false)) { - const eventEmitter = new EventEmitter(); + const eventEmitter = new EventEmitter(undefined, registry.lifecycleCallbacks); result.eventEmitter = eventEmitter; // Config-driven subscribers - _instantiateSubscribers(config, eventEmitter, sysCfg); + const factories = instanceSubscriberFactories(options?.subscriberFactories ?? {}); + _instantiateSubscribers(config, eventEmitter, sysCfg, factories); // PlatformNotifyMiddleware const errorRateThreshold = Number(_cfgGet(sysCfg, config, 'events.thresholds.error_rate', 0.1)); diff --git a/typescript/src/utils/uuid.ts b/typescript/src/utils/uuid.ts new file mode 100644 index 00000000..0093498b --- /dev/null +++ b/typescript/src/utils/uuid.ts @@ -0,0 +1,11 @@ +/** RFC 9562 random UUID using the platform's Web Crypto API. */ +export function uuidV4(): string { + const crypto = globalThis.crypto; + if (!crypto) throw new Error('Web Crypto is required to generate an APCore UUID'); + if (typeof crypto.randomUUID === 'function') return crypto.randomUUID(); + const bytes = crypto.getRandomValues(new Uint8Array(16)); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} diff --git a/typescript/tests/acl-argument-approval_spec.test.ts b/typescript/tests/acl-argument-approval_spec.test.ts index 11a5b562..aa7addfd 100644 --- a/typescript/tests/acl-argument-approval_spec.test.ts +++ b/typescript/tests/acl-argument-approval_spec.test.ts @@ -18,7 +18,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { Type } from '@sinclair/typebox'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import type { ACLRule, AuditEntry } from '../src/acl.js'; import { ArgumentsHandler, buildGovernanceProjection } from '../src/acl-handlers.js'; import { createApprovalResult } from '../src/approval.js'; diff --git a/typescript/tests/acl-effect-closure_spec.test.ts b/typescript/tests/acl-effect-closure_spec.test.ts index 14d90c84..374fdb4f 100644 --- a/typescript/tests/acl-effect-closure_spec.test.ts +++ b/typescript/tests/acl-effect-closure_spec.test.ts @@ -21,11 +21,10 @@ import { describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import type { ACLRule } from '../src/acl.js'; import { ACLRuleError } from '../src/errors.js'; // Side-effect import installs the Node-side YAML loader onto ACL.load. -import '../src/acl-file.js'; function writeAcl(body: string): string { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'acl-effect-')); diff --git a/typescript/tests/acl-pattern-arity_spec.test.ts b/typescript/tests/acl-pattern-arity_spec.test.ts index 5acacc38..196d334a 100644 --- a/typescript/tests/acl-pattern-arity_spec.test.ts +++ b/typescript/tests/acl-pattern-arity_spec.test.ts @@ -35,11 +35,10 @@ import { describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import type { ACLApproval, ACLRule, AuditEntry } from '../src/acl.js'; import { ACLRuleError } from '../src/errors.js'; // Side-effect import installs the Node-side YAML loader onto ACL.load. -import '../src/acl-file.js'; interface RuleSpec { readonly callers: string[]; diff --git a/typescript/tests/acl-system_spec.test.ts b/typescript/tests/acl-system_spec.test.ts index bdd6d9f4..ebe4141e 100644 --- a/typescript/tests/acl-system_spec.test.ts +++ b/typescript/tests/acl-system_spec.test.ts @@ -16,11 +16,10 @@ import { describe, it, expect } from 'vitest'; import { writeFileSync, mkdtempSync, rmSync, unlinkSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import type { ACLRule, AuditEntry } from '../src/acl.js'; import { ACLRuleError, ConfigNotFoundError } from '../src/errors.js'; // Side-effect import installs the Node-side YAML loader onto ACL.load. -import '../src/acl-file.js'; // --------------------------------------------------------------------------- // Helpers diff --git a/typescript/tests/apcore-client_spec.test.ts b/typescript/tests/apcore-client_spec.test.ts index 100d7568..a3ad8c3a 100644 --- a/typescript/tests/apcore-client_spec.test.ts +++ b/typescript/tests/apcore-client_spec.test.ts @@ -1,3 +1,4 @@ +import { AutoApproveHandler } from '../src/approval.js'; /** * Spec-traced contract tests for the APCore unified client (TypeScript SDK). * @@ -19,7 +20,7 @@ import { describe, it, expect } from 'vitest'; import { Type } from '@sinclair/typebox'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { FunctionModule } from '../src/decorator.js'; import { @@ -529,6 +530,7 @@ describe('APCoreClient.disable', () => { it('apcore_client.disable.input.reason.default: returns disabled result with default reason', async () => { const client = new APCore({ config: sysConfig() }); + client.executor.setApprovalHandler(new AutoApproveHandler()); client.module({ id: 'risky.module', inputSchema: Type.Object({}), @@ -544,6 +546,7 @@ describe('APCoreClient.disable', () => { it('apcore_client.disable.property.idempotent_true: disabling twice stays disabled', async () => { const client = new APCore({ config: sysConfig() }); + client.executor.setApprovalHandler(new AutoApproveHandler()); client.module({ id: 'risky.dup', inputSchema: Type.Object({}), @@ -579,6 +582,7 @@ describe('APCoreClient.enable', () => { it('apcore_client.enable.input.reason.default: returns enabled result with default reason', async () => { const client = new APCore({ config: sysConfig() }); + client.executor.setApprovalHandler(new AutoApproveHandler()); client.module({ id: 'risky.enable', inputSchema: Type.Object({}), @@ -595,6 +599,7 @@ describe('APCoreClient.enable', () => { it('apcore_client.enable.property.idempotent_true: enabling twice stays enabled', async () => { const client = new APCore({ config: sysConfig() }); + client.executor.setApprovalHandler(new AutoApproveHandler()); client.module({ id: 'risky.reenable', inputSchema: Type.Object({}), diff --git a/typescript/tests/browser-entry.test.ts b/typescript/tests/browser-entry.test.ts index 91eebd9b..8cb069ce 100644 --- a/typescript/tests/browser-entry.test.ts +++ b/typescript/tests/browser-entry.test.ts @@ -24,7 +24,6 @@ import ts from 'typescript'; import { describe, expect, it } from 'vitest'; import * as browser from '../src/browser/index.js'; -import { _setAclFileLoader } from '../src/acl.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -105,10 +104,10 @@ interface StaticCheckFinding { reason: string; } -function walkBrowserGraph(): StaticCheckFinding[] { +function walkBrowserGraph(entry = BROWSER_ENTRY, forbiddenModules: readonly string[] = []): StaticCheckFinding[] { const findings: StaticCheckFinding[] = []; const visited = new Set(); - const stack: string[] = [BROWSER_ENTRY]; + const stack: string[] = [entry]; while (stack.length > 0) { const file = stack.pop()!; @@ -139,6 +138,8 @@ function walkBrowserGraph(): StaticCheckFinding[] { for (const spec of collectImportSpecifiers(file, src)) { if (isNodeSpecifier(spec)) { findings.push({ file: rel, reason: `imports Node builtin "${spec}"` }); + } else if (forbiddenModules.includes(spec)) { + findings.push({ file: rel, reason: `imports optional dependency "${spec}"` }); } else { const resolved = resolveRelative(file, spec); if (resolved) stack.push(resolved); @@ -197,32 +198,24 @@ describe('browser entry point', () => { expect(findings, `Browser entry drags in Node-only code:\n${formatted}`).toEqual([]); }); + it('package root has no Node, YAML, or Node-conditioned UUID dependencies', () => { + expect(walkBrowserGraph(resolve(SRC_ROOT, 'index.ts'), ['js-yaml', 'uuid'])).toEqual([]); + }); + + it('observability subpath has no Node-only imports or globals', () => { + const entry = resolve(SRC_ROOT, 'observability', 'portable.ts'); + expect(walkBrowserGraph(entry)).toEqual([]); + }); + // ── Runtime contracts ───────────────────────────────────────────── // The static guards above keep `node:*` out of the bundle; these // tests pin the behavioural contract that the browser surface has // to maintain so apwebsite (and any future browser consumer) keeps // working through future refactors. - it('ACL.load throws a guidance error when the Node loader is absent', async () => { - // Vitest setupFiles installs every Node-side loader so the rest of the - // test suite (which imports source files directly) keeps working. - // To assert the actual browser-bundle behaviour we temporarily - // un-install the ACL file loader, run the call, then restore. - const aclModule = await import('../src/acl.js'); - // Save the current loader by re-importing the installer side effect - // — `acl-file.ts` runs once at module load and is idempotent on re-run. - _setAclFileLoader(null); - try { - expect(() => browser.ACL.load('/whatever.yaml')).toThrow( - /requires the Node entry of apcore-js/, - ); - } finally { - // Reinstall the Node loader so subsequent tests in the suite - // (e.g. `tests/test-acl.test.ts`) see normal `ACL.load` behaviour. - // `acl-file.ts` registers the loader as a side-effect of import. - void aclModule; - await import('../src/acl-file.js'); - } + it('ACL file load gives portable callers the explicit configuration path', async () => { + await import('../src/full.js'); + expect(() => browser.ACL.load('/whatever.yaml')).toThrow(/apcore-js\/config/); }); it('Registry + FunctionModule + Executor + AutoApproveHandler runs end-to-end', async () => { @@ -254,7 +247,7 @@ describe('browser entry point', () => { // sha256 of canonical-form JSON. WebCrypto must agree byte-for-byte // with `node:crypto` — any divergence breaks Node↔browser↔Python↔Rust // cache-key alignment. - const node = await import('../src/index.js'); + const node = await import('../src/full.js'); const fixtures: unknown[] = [ { a: 1, b: 2 }, { z: 'last', a: 'first', m: [3, 1, 2] }, diff --git a/typescript/tests/conformance-acl-audit-delivery.test.ts b/typescript/tests/conformance-acl-audit-delivery.test.ts index de39827a..27da12d4 100644 --- a/typescript/tests/conformance-acl-audit-delivery.test.ts +++ b/typescript/tests/conformance-acl-audit-delivery.test.ts @@ -13,11 +13,11 @@ import path from 'node:path'; import { describe, it, expect, vi } from 'vitest'; import yaml from 'js-yaml'; -import { ACL, AUDIT_EVENT_NAME } from '../src/acl.js'; +import { ACL } from '../src/full.js'; +import { AUDIT_EVENT_NAME } from '../src/acl.js'; import type { AuditEntry } from '../src/acl.js'; import { ConfigError } from '../src/errors.js'; import { findFixturesRoot } from './spec-repo.js'; -import '../src/acl-file.js'; interface AuditCase { readonly id: string; diff --git a/typescript/tests/conformance-acl-effect-value-closure.test.ts b/typescript/tests/conformance-acl-effect-value-closure.test.ts index 0d1ce669..9f1f551d 100644 --- a/typescript/tests/conformance-acl-effect-value-closure.test.ts +++ b/typescript/tests/conformance-acl-effect-value-closure.test.ts @@ -21,7 +21,7 @@ import { describe, it, expect } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import type { ACLRule } from '../src/acl.js'; import { ACLRuleError } from '../src/errors.js'; import { findFixturesRoot } from './spec-repo.js'; diff --git a/typescript/tests/conformance-acl-pattern-arity.test.ts b/typescript/tests/conformance-acl-pattern-arity.test.ts index d7a0ea9a..954f5246 100644 --- a/typescript/tests/conformance-acl-pattern-arity.test.ts +++ b/typescript/tests/conformance-acl-pattern-arity.test.ts @@ -37,12 +37,11 @@ import { describe, it, expect } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import type { ACLRule, AuditEntry } from '../src/acl.js'; import { ACLRuleError } from '../src/errors.js'; import { findFixturesRoot } from './spec-repo.js'; // Side-effect import installs the Node-side YAML loader onto ACL.load. -import '../src/acl-file.js'; const FIXTURE = 'acl_pattern_arity.json'; const FIXTURE_PATH = path.join(findFixturesRoot(), FIXTURE); diff --git a/typescript/tests/conformance-acl-root-discovery.test.ts b/typescript/tests/conformance-acl-root-discovery.test.ts index d540eb05..eb662533 100644 --- a/typescript/tests/conformance-acl-root-discovery.test.ts +++ b/typescript/tests/conformance-acl-root-discovery.test.ts @@ -11,10 +11,7 @@ * `acl.default_effect` is `deny`. Auto-discovery is skipped entirely when the * caller supplies their own Executor. * - * `ACL.load` / `ACL.discover` are Node-only: the filesystem discoverer lives on - * the side-effect module `src/acl-file.ts`, which `tests/setup-node-installers.ts` - * imports for every suite (see vitest.config.ts `setupFiles`). No extra wiring - * is needed here. + * The full profile owns Node file loading and discovery. * * `acl_attached` and `enforcement` are asserted BEHAVIOURALLY rather than by * reading a field: `Executor` keeps its ACL private (src/executor.ts:235), and @@ -31,14 +28,14 @@ import * as path from 'node:path'; import yaml from 'js-yaml'; import { Type } from '@sinclair/typebox'; -import { ACL } from '../src/acl.js'; -import { APCore } from '../src/client.js'; +import { ACL } from '../src/full.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { getDefault } from '../src/config-defaults.js'; import { FunctionModule } from '../src/decorator.js'; import { ACLDeniedError } from '../src/errors.js'; import { Executor } from '../src/executor.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import { findFixturesRoot } from './spec-repo.js'; // --------------------------------------------------------------------------- diff --git a/typescript/tests/conformance-acl-rule-key-closure.test.ts b/typescript/tests/conformance-acl-rule-key-closure.test.ts index f34ff617..5ccab7d6 100644 --- a/typescript/tests/conformance-acl-rule-key-closure.test.ts +++ b/typescript/tests/conformance-acl-rule-key-closure.test.ts @@ -11,7 +11,7 @@ import { describe, it, expect } from 'vitest'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import { ACLRuleError } from '../src/errors.js'; import { findFixturesRoot } from './spec-repo.js'; diff --git a/typescript/tests/conformance-bindings-dir-resolution.test.ts b/typescript/tests/conformance-bindings-dir-resolution.test.ts index 3e4efc64..6f415d20 100644 --- a/typescript/tests/conformance-bindings-dir-resolution.test.ts +++ b/typescript/tests/conformance-bindings-dir-resolution.test.ts @@ -73,12 +73,12 @@ import * as path from 'node:path'; import yaml from 'js-yaml'; import { BindingLoader } from '../src/bindings.js'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import type { Context } from '../src/context.js'; import { BindingFileInvalidError } from '../src/errors.js'; import type { FunctionModule } from '../src/decorator.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import { findFixturesRoot } from './spec-repo.js'; // --------------------------------------------------------------------------- diff --git a/typescript/tests/conformance-config-project-root.test.ts b/typescript/tests/conformance-config-project-root.test.ts index 5045618d..1020db11 100644 --- a/typescript/tests/conformance-config-project-root.test.ts +++ b/typescript/tests/conformance-config-project-root.test.ts @@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, isAbsolute, join, resolve } from 'node:path'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import { Config, getDefault } from '../src/config.js'; import { SchemaLoader } from '../src/schema/loader.js'; import { findFixturesRoot } from './spec-repo.js'; diff --git a/typescript/tests/conformance-gate-provider-binding.test.ts b/typescript/tests/conformance-gate-provider-binding.test.ts index ea2b1fc6..ad23a9ee 100644 --- a/typescript/tests/conformance-gate-provider-binding.test.ts +++ b/typescript/tests/conformance-gate-provider-binding.test.ts @@ -26,7 +26,7 @@ import { Executor, Registry, buildStandardStrategy, -} from '../src/index.js'; +} from '../src/full.js'; import { MiddlewareManager } from '../src/middleware/manager.js'; import { ModuleError } from '../src/errors.js'; import { findFixturesRoot } from './spec-repo.js'; diff --git a/typescript/tests/conformance-governance-state.test.ts b/typescript/tests/conformance-governance-state.test.ts index e613cec2..f3db81de 100644 --- a/typescript/tests/conformance-governance-state.test.ts +++ b/typescript/tests/conformance-governance-state.test.ts @@ -15,7 +15,7 @@ import { describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as path from 'node:path'; -import { ACL, ExecutionPolicy, Executor, Registry } from '../src/index.js'; +import { ACL, ExecutionPolicy, Executor, Registry } from '../src/full.js'; import { Config } from '../src/config.js'; import { ExecutionStrategy } from '../src/pipeline.js'; import type { PipelineContext, Step, StepResult } from '../src/pipeline.js'; @@ -122,7 +122,7 @@ function build(setup: Setup): Executor { if (setup.acl_attached) executor.setAcl(new ACL([], 'deny')); if (setup.approval_handler_attached) executor.setApprovalHandler(neverCalledHandler); - if (setup.policy_strict) executor.setPolicy(new ExecutionPolicy([], { strict: true })); + executor.setPolicy(new ExecutionPolicy([], { strict: setup.policy_strict })); return executor; } diff --git a/typescript/tests/conformance-id-map-from-config.test.ts b/typescript/tests/conformance-id-map-from-config.test.ts index 487be7ec..aa62d004 100644 --- a/typescript/tests/conformance-id-map-from-config.test.ts +++ b/typescript/tests/conformance-id-map-from-config.test.ts @@ -15,7 +15,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import yaml from 'js-yaml'; import { Config } from '../src/config.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import { findFixturesRoot } from './spec-repo.js'; interface IdMapCase { diff --git a/typescript/tests/conformance-issue123.test.ts b/typescript/tests/conformance-issue123.test.ts index 205331c0..4ceb3074 100644 --- a/typescript/tests/conformance-issue123.test.ts +++ b/typescript/tests/conformance-issue123.test.ts @@ -12,17 +12,15 @@ import { describe, expect, it, vi } from 'vitest'; import { ACL, type ACLRule } from '../src/acl.js'; import { BindingLoader } from '../src/bindings.js'; import { CancelToken, ExecutionCancelledError } from '../src/cancel.js'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { Context, Identity } from '../src/context.js'; import { ModuleError } from '../src/errors.js'; import type { ApCoreEvent } from '../src/events/emitter.js'; import { Executor } from '../src/executor.js'; -import { annotationsFromJSON, type Change, type PreviewResult } from '../src/module.js'; -import { Registry } from '../src/registry/registry.js'; -import { SchemaExporter } from '../src/schema/exporter.js'; +import { type Change, type PreviewResult } from '../src/module.js'; +import { Registry } from '../src/full.js'; import { jsonSchemaToTypeBox } from '../src/schema/loader-pure.js'; -import type { ExportProfile } from '../src/schema/types.js'; import { findFixturesRoot } from './spec-repo.js'; type JsonObject = Record; @@ -235,49 +233,6 @@ describe('error_details_shape.json', () => { } }); -function pointer(value: unknown, path: string): unknown { - let current = value; - for (const key of path.slice(1).split('/').map((part) => part.replace(/~1/g, '/').replace(/~0/g, '~'))) { - if (current == null || typeof current !== 'object' || !(key in current)) return undefined; - current = (current as JsonObject)[key]; - } - return current; -} - -function assertNoExtensionKeywords(value: unknown, propertyNames = false): void { - if (Array.isArray(value)) { for (const item of value) assertNoExtensionKeywords(item); return; } - if (value == null || typeof value !== 'object') return; - for (const [key, child] of Object.entries(value)) { - if (!propertyNames) expect(key.startsWith('x-'), `Unexpected extension keyword ${key}`).toBe(false); - assertNoExtensionKeywords(child, key === 'properties'); - } -} - -// D-140, PROTOCOL_SPEC §4.17/Appendix D.1: exercise the public profile exporter. -describe('export_profiles.json', () => { - const data = fixture<{ profile: ExportProfile; annotations: JsonObject }>('export_profiles'); - it('handles every canonical case and expected field', () => guardCases(data, 5, ['paths', 'absent_paths', 'no_x_keywords_under'])); - for (const testCase of data.test_cases) { - it(testCase.id, async () => { - const contract = data.module_contract; - const registry = new Registry(); - const module = contractedModule(contract); - module['annotations'] = annotationsFromJSON(testCase.input.annotations); - // Streaming declarations must represent real streaming modules. - if (testCase.input.annotations['streaming']) module['stream'] = async function* () { yield { sent: true }; }; - await registry.register(contract['module_id'] as string, module); - const output = new SchemaExporter().export({ - moduleId: contract['module_id'] as string, description: contract['description'] as string, - inputSchema: contract['input_schema'] as JsonObject, outputSchema: contract['output_schema'] as JsonObject, - definitions: {}, version: '1.0.0', - }, testCase.input.profile, annotationsFromJSON(testCase.input.annotations)); - for (const [path, value] of Object.entries((testCase.expected['paths'] ?? {}) as JsonObject)) expect(pointer(output, path), path).toEqual(value); - for (const path of (testCase.expected['absent_paths'] ?? []) as string[]) expect(pointer(output, path), path).toBeUndefined(); - if ('no_x_keywords_under' in testCase.expected) assertNoExtensionKeywords(pointer(output, testCase.expected['no_x_keywords_under'] as string)); - }); - } -}); - // D-136, type-mapping §17.3 R5/R6: native TypeBox schemas, not JSON-Schema loading. describe('json_input_native_types.json', () => { const data = fixture<{ inputs: JsonObject }>('json_input_native_types'); diff --git a/typescript/tests/conformance-module-lifecycle.test.ts b/typescript/tests/conformance-module-lifecycle.test.ts index 4c0e90f9..6a61066f 100644 --- a/typescript/tests/conformance-module-lifecycle.test.ts +++ b/typescript/tests/conformance-module-lifecycle.test.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { expect, it, vi } from 'vitest'; -import { AlwaysDenyHandler, APCore, AutoApproveHandler, CancelToken, Config, Context, ModuleError, ModuleLoadError, STREAMING_MARKER } from '../src/index.js'; +import { AlwaysDenyHandler, APCore, AutoApproveHandler, CancelToken, Config, Context, ModuleError, ModuleLoadError, STREAMING_MARKER } from '../src/full.js'; import { jsonSchemaToTypeBox } from '../src/schema/loader.js'; import { RefResolver } from '../src/schema/ref-resolver.js'; import { SchemaValidator } from '../src/schema/validator.js'; diff --git a/typescript/tests/conformance-multi-root-discovery.test.ts b/typescript/tests/conformance-multi-root-discovery.test.ts index 637689a8..4065fca0 100644 --- a/typescript/tests/conformance-multi-root-discovery.test.ts +++ b/typescript/tests/conformance-multi-root-discovery.test.ts @@ -18,7 +18,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import yaml from 'js-yaml'; import { Config } from '../src/config.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import { findFixturesRoot } from './spec-repo.js'; interface MultiRootCase { diff --git a/typescript/tests/conformance-pipeline-section-wiring.test.ts b/typescript/tests/conformance-pipeline-section-wiring.test.ts index a70e04a8..8d3ede92 100644 --- a/typescript/tests/conformance-pipeline-section-wiring.test.ts +++ b/typescript/tests/conformance-pipeline-section-wiring.test.ts @@ -18,7 +18,7 @@ import path from 'node:path'; import { describe, it, expect, vi } from 'vitest'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { registerStepType, unregisterStepType } from '../src/pipeline-config.js'; import type { Step, StepResult, PipelineContext } from '../src/pipeline.js'; diff --git a/typescript/tests/conformance-registry-load-ordering.test.ts b/typescript/tests/conformance-registry-load-ordering.test.ts index 550abb86..a51028b6 100644 --- a/typescript/tests/conformance-registry-load-ordering.test.ts +++ b/typescript/tests/conformance-registry-load-ordering.test.ts @@ -20,8 +20,7 @@ import { describe, it, expect, vi } from 'vitest'; import * as fs from 'node:fs'; import { tmpdir } from 'node:os'; import * as path from 'node:path'; -import '../src/registry/install-filesystem.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import { EventEmitter } from '../src/events/emitter.js'; import type { ApCoreEvent } from '../src/events/emitter.js'; import { DuplicateModuleIdError, ModuleError } from '../src/errors.js'; diff --git a/typescript/tests/conformance-reload-path-filter.test.ts b/typescript/tests/conformance-reload-path-filter.test.ts index 87eef621..364a06fb 100644 --- a/typescript/tests/conformance-reload-path-filter.test.ts +++ b/typescript/tests/conformance-reload-path-filter.test.ts @@ -26,7 +26,7 @@ import { AutoApproveHandler } from '../src/approval.js'; import { ModuleError } from '../src/errors.js'; import { EventEmitter } from '../src/events/emitter.js'; import { Executor } from '../src/executor.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import { jsonSchemaToTypeBox } from '../src/schema/loader.js'; import { SchemaValidator } from '../src/schema/validator.js'; import { InMemoryAuditStore } from '../src/sys-modules/audit.js'; @@ -115,6 +115,10 @@ describe('Conformance: reload_module path_filter (reload_path_filter.json)', () expect(error, `case '${tc.id}' expected an error, got result ${JSON.stringify(result)}`) .toBeInstanceOf(ModuleError); expect((error as ModuleError).code).toBe(expected['error_code']); + if (tc.id === 'removed_reload_dependents_is_rejected') { + expect(registry.discover).not.toHaveBeenCalled(); + expect(auditStore.query()).toEqual([]); + } } else if (error !== null) { throw error; } else { @@ -197,8 +201,7 @@ describe('Conformance: reload_module path_filter (reload_path_filter.json)', () 'bracket_is_a_literal_and_MUST_NOT_be_rejected', 'character_class_does_not_expand', 'double_star_is_two_ordinary_stars', - // D-121: the deprecated field is accepted and changes nothing. - 'reload_dependents_is_accepted_and_inert', + 'removed_reload_dependents_is_rejected', // D-111: per-module audit entries sharing one correlation id. 'bulk_reload_audits_per_module_with_one_correlation_id', ]); diff --git a/typescript/tests/conformance-schema-keyword-parity.test.ts b/typescript/tests/conformance-schema-keyword-parity.test.ts index d86ee7f4..9a8339b9 100644 --- a/typescript/tests/conformance-schema-keyword-parity.test.ts +++ b/typescript/tests/conformance-schema-keyword-parity.test.ts @@ -18,7 +18,7 @@ import { describe, it, expect, vi } from 'vitest'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { Type } from '@sinclair/typebox'; -import { APCore } from '../src/index.js'; +import { APCore } from '../src/full.js'; import { jsonSchemaToTypeBox } from '../src/schema/loader-pure.js'; import { SchemaValidator } from '../src/schema/validator.js'; import { findFixturesRoot } from './spec-repo.js'; diff --git a/typescript/tests/conformance-toggle-isolation.test.ts b/typescript/tests/conformance-toggle-isolation.test.ts index 83b13c14..d83087fc 100644 --- a/typescript/tests/conformance-toggle-isolation.test.ts +++ b/typescript/tests/conformance-toggle-isolation.test.ts @@ -1,3 +1,4 @@ +import { AutoApproveHandler } from '../src/approval.js'; /** * Cross-language conformance driver for toggle_state_isolation.json (Issue #71). * @@ -24,7 +25,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { Type } from '@sinclair/typebox'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { ModuleDisabledError } from '../src/errors.js'; import { DEFAULT_TOGGLE_STATE } from '../src/sys-modules/toggle.js'; @@ -60,7 +61,9 @@ function newInstance(): APCore { const config = new Config({ sys_modules: { enabled: true, events: { enabled: true } }, }); - return new APCore({ config }); + const client = new APCore({ config }); + client.executor.setApprovalHandler(new AutoApproveHandler()); + return client; } /** diff --git a/typescript/tests/conformance-tracing-from-config.test.ts b/typescript/tests/conformance-tracing-from-config.test.ts index 587f5f36..c3c6e5d8 100644 --- a/typescript/tests/conformance-tracing-from-config.test.ts +++ b/typescript/tests/conformance-tracing-from-config.test.ts @@ -14,7 +14,7 @@ import path from 'node:path'; import { describe, it, expect, vi } from 'vitest'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { ConfigError } from '../src/errors.js'; import { diff --git a/typescript/tests/conformance-usage-contract.test.ts b/typescript/tests/conformance-usage-contract.test.ts index 79f913b4..9dd7116b 100644 --- a/typescript/tests/conformance-usage-contract.test.ts +++ b/typescript/tests/conformance-usage-contract.test.ts @@ -14,7 +14,7 @@ import { describe, expect, it } from 'vitest'; import * as fs from 'node:fs'; import * as path from 'node:path'; -import { APCore, Registry } from '../src/index.js'; +import { APCore, Registry } from '../src/full.js'; import { Config } from '../src/config.js'; import { UsageCollector, UsageMiddleware } from '../src/observability/usage.js'; import { UsageModule, UsageSummaryModule } from '../src/sys-modules/usage.js'; diff --git a/typescript/tests/conformance.test.ts b/typescript/tests/conformance.test.ts index 99730603..3f9e9567 100644 --- a/typescript/tests/conformance.test.ts +++ b/typescript/tests/conformance.test.ts @@ -57,6 +57,8 @@ import { SchemaValidator } from '../src/schema/validator.js'; import type { SchemaDefinition } from '../src/schema/types.js'; import type { TSchema } from '@sinclair/typebox'; import { deepMergeChunk } from '../src/executor.js'; +import { APCore as CoreProfile, Registry as CoreRegistry } from '../src/core.js'; +import { ExecutionPolicy, PolicyRule } from '../src/policy.js'; import { createAnnotations, annotationsToJSON, @@ -78,8 +80,6 @@ import { } from '../src/events/index.js'; import type { ApCoreEvent, EventSubscriber } from '../src/events/index.js'; import { - registerSubscriberType, - resetSubscriberRegistry, createSubscriberFromConfig, registerSysModules, } from '../src/sys-modules/registration.js'; @@ -98,7 +98,7 @@ import { } from '../src/middleware/index.js'; // Public export name (audit D2-001): middleware circuit-breaker state enum is // publicly exported as `CircuitBreakerState` for cross-SDK parity (matches apcore-rust). -import { CircuitBreakerState } from '../src/index.js'; +import { CircuitBreakerState } from '../src/full.js'; import { AsyncTaskManager, TaskStatus, @@ -109,7 +109,7 @@ import type { TaskStore } from '../src/async-task.js'; import { Executor } from '../src/executor.js'; import { InMemoryOverridesStore } from '../src/sys-modules/overrides.js'; import { Registry } from '../src/registry/registry.js'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { ManifestFullModule } from '../src/sys-modules/manifest.js'; import { HealthSummaryModule } from '../src/sys-modules/health.js'; import { FunctionModule } from '../src/decorator.js'; @@ -125,7 +125,7 @@ import { createSpan, TracingMiddleware, MetricsCollector, - PrometheusExporter, + renderPrometheusMetrics, RedactionConfig, } from '../src/observability/index.js'; import { DEFAULT_REDACTION_FIELD_PATTERNS } from '../src/observability/context-logger.js'; @@ -1087,7 +1087,8 @@ describe('apcore Conformance Suite (TypeScript)', () => { } } - const gate = new BuiltinApprovalGate(handler); + const policy = tc.execution_policy ? ExecutionPolicy.fromObject(tc.execution_policy) : null; + const gate = new BuiltinApprovalGate(handler, policy); const mod: Record = { annotations: { @@ -1144,6 +1145,62 @@ describe('apcore Conformance Suite (TypeScript)', () => { }); }); + // --- core_profile_governance --- + describe('Core profile governance', () => { + const governanceFixture = loadFixture('core_profile_governance'); + const moduleId = 'governance.review'; + + for (const { id, input, expected } of governanceFixture.test_cases) { + it(id, async () => { + const source = input.approval_source; + const acl = source === 'acl' ? new ACL([{ + callers: ['@external'], + targets: [moduleId], + effect: 'allow', + approval: 'required', + description: 'Request approval for the review module', + }], 'deny') : undefined; + const rules = source === 'policy_rule' + ? [new PolicyRule(moduleId, { requiresApproval: true })] + : []; + const policy = input.execution_policy + ? ExecutionPolicy.fromObject(input.execution_policy) + : rules.length ? new ExecutionPolicy(rules) : undefined; + const executor = input.client === 'injected_executor' + ? new Executor({ registry: new CoreRegistry(), acl, policy }) + : undefined; + const client = new CoreProfile({ executor, policy }); + if (acl) client.executor.setAcl(acl); + let executions = 0; + await client.register(moduleId, { + description: 'Review a pending change', + annotations: createAnnotations({ + requiresApproval: source === 'annotation', + destructive: source === 'destructive', + }), + inputSchema: { type: 'object' }, + outputSchema: { type: 'object' }, + execute: () => { + executions += 1; + return {}; + }, + }); + + const preflight = await client.validate(moduleId, {}); + expect(preflight.requiresApproval).toBe(expected.requires_approval); + if (expected.error_code === null) { + await expect(client.call(moduleId, {})).resolves.toEqual({}); + } else { + await expect(client.call(moduleId, {})).rejects.toMatchObject({ code: expected.error_code }); + await expect(client.stream(moduleId, {}).next()).rejects.toMatchObject({ + code: expected.error_code, + }); + } + expect(executions).toBe(expected.executions); + }); + } + }); + // --- binding_errors / binding_yaml_canonical --- // Driven by tests/conformance-bindings.test.ts. (They were skipped here with // the reason "BindingLoader requires real file I/O and dynamic imports", @@ -1828,12 +1885,7 @@ describe('apcore Conformance Suite (TypeScript)', () => { } describe('Event Management Hardening (Issue #36)', () => { - beforeEach(() => { - resetSubscriberRegistry(); - }); - afterEach(() => { - resetSubscriberRegistry(); vi.useRealTimers(); }); @@ -1854,11 +1906,10 @@ describe('apcore Conformance Suite (TypeScript)', () => { async onEvent(_event: ApCoreEvent): Promise {} } - for (const typeName of tc.input.registered_types as string[]) { - registerSubscriberType(typeName, () => new RegisteredSubscriber(typeName)); - } - - const subscriber = createSubscriberFromConfig(tc.input.subscriber_config); + const factories = Object.fromEntries((tc.input.registered_types as string[]).map( + (typeName) => [typeName, () => new RegisteredSubscriber(typeName)], + )); + const subscriber = createSubscriberFromConfig(tc.input.subscriber_config, factories); expect(subscriber !== null && subscriber !== undefined).toBe( tc.expected.subscriber_created, ); @@ -1903,14 +1954,12 @@ describe('apcore Conformance Suite (TypeScript)', () => { }, }; - registerSubscriberType('mock_passthrough', () => mockDelegate); - const subscriber = createSubscriberFromConfig({ type: 'filter', delegate_type: 'mock_passthrough', delegate_config: {}, include_events: tc.input.subscriber_config.include_events, - }) as FilterSubscriber; + }, { mock_passthrough: () => mockDelegate }) as FilterSubscriber; const event = makeTestEvent({ eventType: tc.input.event.event_type, @@ -1945,8 +1994,6 @@ describe('apcore Conformance Suite (TypeScript)', () => { deliveryAttempted = true; }, }; - registerSubscriberType('mock_passthrough', () => mockDelegate); - const subscriber = createSubscriberFromConfig({ type: 'filter', delegate_type: 'mock_passthrough', @@ -1957,7 +2004,7 @@ describe('apcore Conformance Suite (TypeScript)', () => { ...(tc.input.subscriber_config.exclude_events !== undefined ? { exclude_events: tc.input.subscriber_config.exclude_events } : {}), - }) as FilterSubscriber; + }, { mock_passthrough: () => mockDelegate }) as FilterSubscriber; await subscriber.onEvent( makeTestEvent({ @@ -1998,14 +2045,12 @@ describe('apcore Conformance Suite (TypeScript)', () => { }, }; - registerSubscriberType('mock_sink', () => mockDelegate); - const subscriber = createSubscriberFromConfig({ type: 'filter', delegate_type: 'mock_sink', delegate_config: {}, include_events: tc.input.subscriber_config.include_events, - }) as FilterSubscriber; + }, { mock_sink: () => mockDelegate }) as FilterSubscriber; const event = makeTestEvent({ eventType: tc.input.event.event_type, @@ -2922,8 +2967,7 @@ describe('apcore Conformance Suite (TypeScript)', () => { collector.observe('apcore_module_duration_seconds', { module_id: 'test' }, obs); } - const exporter = new PrometheusExporter({ collector }); - const output = exporter.export(); + const output = renderPrometheusMetrics(collector); for (const metric of tc.expected.output_contains) { expect(output).toContain(metric); @@ -3592,10 +3636,8 @@ describe('apcore Conformance Suite (TypeScript)', () => { } const collector = new MetricsCollector(); - const exporter = new PrometheusExporter({ collector, usageCollector }); - const start = Date.now(); - const output = exporter.export(); + const output = renderPrometheusMetrics(collector, usageCollector); const elapsed = Date.now() - start; expect(elapsed).toBeLessThan(tc['expected']['export_within_timeout_ms']); diff --git a/typescript/tests/event-system_spec.test.ts b/typescript/tests/event-system_spec.test.ts index e81a9328..92348467 100644 --- a/typescript/tests/event-system_spec.test.ts +++ b/typescript/tests/event-system_spec.test.ts @@ -33,7 +33,6 @@ import { describe, it, expect, vi } from 'vitest'; import { EventEmitter, WebhookSubscriber, - A2ASubscriber, } from '../src/events/index.js'; import { CircuitBreakerWrapper, CircuitState } from '../src/events/circuit-breaker.js'; import type { ApCoreEvent, EventSubscriber } from '../src/events/index.js'; @@ -580,125 +579,3 @@ describe('EventEmitter.flush', () => { } }); }); - -// =========================================================================== -// Contract: A2ASubscriber.deliver -// =========================================================================== - -describe('A2ASubscriber.deliver', () => { - it('event_system.deliver.input.event.required_a2a: A2A delivery POSTs a {skillId, event} wrapper', async () => { - const fetchMock = stubFetch(200); - try { - const sub = new A2ASubscriber('https://platform.example.com'); - const event = makeEvent({ eventType: 'apcore.health.recovered' }); - await sub.onEvent(event); - expect(fetchMock).toHaveBeenCalledTimes(1); - const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]; - const body = JSON.parse(init.body as string); - expect(body.skillId).toBe('apevo.event_receiver'); - expect(body.event.event_type).toBe('apcore.health.recovered'); - } finally { - vi.unstubAllGlobals(); - } - }); - - it.skip('event_system.deliver.error.ImportError_a2a: missing symbol — TS uses global fetch, no ImportError without aiohttp (contract gap)', async () => { - // Python raises ImportError synchronously if aiohttp is not installed. The - // TS SDK uses the global `fetch`; there is no optional HTTP-client import - // and thus no ImportError analogue. Recorded as a missing-symbol skip. - }); - - it('event_system.deliver.property.async_a2a: A2A delivery returns a Promise that resolves to undefined', async () => { - const fetchMock = stubFetch(200); - try { - const sub = new A2ASubscriber('https://platform.example.com'); - const result = sub.onEvent(makeEvent()); - expect(result).toBeInstanceOf(Promise); - await expect(result).resolves.toBeUndefined(); - expect(fetchMock).toHaveBeenCalled(); - } finally { - vi.unstubAllGlobals(); - } - }); - - it('event_system.deliver.property.thread_safe_a2a: >=8 concurrent A2A deliveries each issue their own POST', async () => { - const fetchMock = stubFetch(200); - try { - const sub = new A2ASubscriber('https://platform.example.com'); - await Promise.all( - Array.from({ length: 8 }, (_, i) => sub.onEvent(makeEvent({ data: { i } }))), - ); - expect(fetchMock).toHaveBeenCalledTimes(8); - } finally { - vi.unstubAllGlobals(); - } - }); - - it('event_system.deliver.property.pure_a2a: delivery is NOT pure — it POSTs to the platform URL', async () => { - const fetchMock = stubFetch(200); - try { - const sub = new A2ASubscriber('https://platform.example.com'); - await sub.onEvent(makeEvent()); - expect(fetchMock.mock.calls[0][0]).toBe('https://platform.example.com'); - } finally { - vi.unstubAllGlobals(); - } - }); - - it('event_system.deliver.side_effect.1.auth_modes_a2a: str->Bearer; dict->merged headers; None->no Authorization', async () => { - // str auth -> Bearer - let fetchMock = stubFetch(200); - try { - const subStr = new A2ASubscriber('https://p.example.com', 'tok123'); - await subStr.onEvent(makeEvent()); - const headersStr = (fetchMock.mock.calls[0][1] as RequestInit).headers as Record; - expect(headersStr['Authorization']).toBe('Bearer tok123'); - } finally { - vi.unstubAllGlobals(); - } - - // dict auth -> merged - fetchMock = stubFetch(200); - try { - const subDict = new A2ASubscriber('https://p.example.com', { 'X-Api-Key': 'k' }); - await subDict.onEvent(makeEvent()); - const headersDict = (fetchMock.mock.calls[0][1] as RequestInit).headers as Record; - expect(headersDict['X-Api-Key']).toBe('k'); - } finally { - vi.unstubAllGlobals(); - } - - // None auth -> no Authorization - fetchMock = stubFetch(200); - try { - const subNone = new A2ASubscriber('https://p.example.com', undefined); - await subNone.onEvent(makeEvent()); - const headersNone = (fetchMock.mock.calls[0][1] as RequestInit).headers as Record; - expect('Authorization' in headersNone).toBe(false); - } finally { - vi.unstubAllGlobals(); - } - }); - - it('event_system.deliver.side_effect.2.retry_on_5xx_a2a: 5xx rethrows (emitter retries); 4xx does not throw (no retry)', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); - // 5xx -> throws - let fetchMock = stubFetch(502); - try { - const sub5xx = new A2ASubscriber('https://p.example.com'); - await expect(sub5xx.onEvent(makeEvent())).rejects.toThrow(); - } finally { - vi.unstubAllGlobals(); - } - // 4xx -> not thrown - fetchMock = stubFetch(403); - try { - const sub4xx = new A2ASubscriber('https://p.example.com'); - await expect(sub4xx.onEvent(makeEvent())).resolves.toBeUndefined(); - expect(fetchMock).toHaveBeenCalledTimes(1); - } finally { - vi.unstubAllGlobals(); - vi.restoreAllMocks(); - } - }); -}); diff --git a/typescript/tests/integration/test-module-lifecycle.test.ts b/typescript/tests/integration/test-module-lifecycle.test.ts index 0ea26cdf..52dcf58b 100644 --- a/typescript/tests/integration/test-module-lifecycle.test.ts +++ b/typescript/tests/integration/test-module-lifecycle.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest'; -import { APCore, AutoApproveHandler, CancelToken, Config, Context, Executor, Middleware, Registry, registerSysModules } from '../../src/index.js'; +import { APCore, AutoApproveHandler, CancelToken, Config, Context, Executor, Middleware, Registry, registerSysModules } from '../../src/full.js'; function gate() { let open!: () => void; diff --git a/typescript/tests/observability/test-concurrent-calls.test.ts b/typescript/tests/observability/test-concurrent-calls.test.ts index 0f30686b..314321b9 100644 --- a/typescript/tests/observability/test-concurrent-calls.test.ts +++ b/typescript/tests/observability/test-concurrent-calls.test.ts @@ -1,6 +1,6 @@ import { Type } from '@sinclair/typebox'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { APCore } from '../../src/client.js'; +import { APCore } from '../../src/full.js'; import { Context } from '../../src/context.js'; import { MetricsCollector, MetricsMiddleware } from '../../src/observability/metrics.js'; import { InMemoryExporter, TracingMiddleware } from '../../src/observability/tracing.js'; diff --git a/typescript/tests/observability/test-prometheus-exporter-server.test.ts b/typescript/tests/observability/test-prometheus-exporter-server.test.ts deleted file mode 100644 index b125be3a..00000000 --- a/typescript/tests/observability/test-prometheus-exporter-server.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -/** - * PrometheusExporter HTTP server — covers the start()/stop() lifecycle and - * the /metrics, /healthz, /readyz, and 404 routes. - * - * Uses port 0 so the OS picks a free ephemeral port; tests don't compete - * for a fixed listener. - */ -import { afterEach, describe, it, expect, vi } from 'vitest'; -import { - MetricsCollector, - PrometheusExporter, - UsageCollector, -} from '../../src/observability/index.js'; -import type { AddressInfo } from 'node:net'; - -interface ExporterInternals { - _server: { address(): AddressInfo | string | null } | null; -} - -async function fetchText(port: number, path: string): Promise<{ status: number; body: string }> { - // Each case closes its ephemeral listener. Do not let the shared fetch pool - // reuse an idle socket after that listener closes and its port is reassigned. - const res = await fetch(`http://127.0.0.1:${port}${path}`, { headers: { Connection: 'close' } }); - const body = await res.text(); - return { status: res.status, body }; -} - -function getPort(exporter: PrometheusExporter): number { - const internals = exporter as unknown as ExporterInternals; - const addr = internals._server?.address(); - if (addr === null || addr === undefined || typeof addr === 'string') { - throw new Error('exporter is not listening'); - } - return addr.port; -} - -describe('PrometheusExporter HTTP server', () => { - let exporter: PrometheusExporter | null = null; - - afterEach(async () => { - if (exporter !== null) { - await exporter.stop(); - exporter = null; - } - }); - - it('serves /metrics with Prometheus content type and metrics body', async () => { - const collector = new MetricsCollector(); - collector.increment('apcore_module_calls_total', { module_id: 'mod.x', status: 'success' }); - exporter = new PrometheusExporter({ collector }); - exporter.start({ port: 0 }); - const port = getPort(exporter); - - const res = await fetch(`http://127.0.0.1:${port}/metrics`, { headers: { Connection: 'close' } }); - expect(res.status).toBe(200); - expect(res.headers.get('content-type')).toContain('text/plain'); - const body = await res.text(); - expect(body).toContain('apcore'); - }); - - it('serves /metrics on the configured custom path', async () => { - const collector = new MetricsCollector(); - exporter = new PrometheusExporter({ collector }); - exporter.start({ port: 0, path: '/p' }); - const port = getPort(exporter); - - const ok = await fetchText(port, '/p?format=openmetrics'); - expect(ok.status).toBe(200); - - const missing = await fetchText(port, '/metrics'); - expect(missing.status).toBe(404); - }); - - it('/healthz returns 200 OK', async () => { - exporter = new PrometheusExporter({ collector: new MetricsCollector() }); - exporter.start({ port: 0 }); - const port = getPort(exporter); - - const r = await fetchText(port, '/healthz'); - expect(r.status).toBe(200); - expect(r.body).toBe('OK'); - }); - - it('/readyz returns 503 before markReady() and 200 after', async () => { - exporter = new PrometheusExporter({ collector: new MetricsCollector() }); - exporter.start({ port: 0 }); - const port = getPort(exporter); - - const before = await fetchText(port, '/readyz'); - expect(before.status).toBe(503); - expect(before.body).toBe('Not ready'); - - exporter.markReady(); - const after = await fetchText(port, '/readyz'); - expect(after.status).toBe(200); - expect(after.body).toBe('OK'); - }); - - it('returns 404 for unknown paths', async () => { - exporter = new PrometheusExporter({ collector: new MetricsCollector() }); - exporter.start({ port: 0 }); - const port = getPort(exporter); - - const r = await fetchText(port, '/nope'); - expect(r.status).toBe(404); - }); - - it('start() throws when called twice without stop()', () => { - exporter = new PrometheusExporter({ collector: new MetricsCollector() }); - exporter.start({ port: 0 }); - expect(() => exporter!.start({ port: 0 })).toThrow(/already running/i); - }); - - it('stop() resolves even when start() was never called', async () => { - const e = new PrometheusExporter({ collector: new MetricsCollector() }); - await expect(e.stop()).resolves.toBeUndefined(); - }); - - it('export() includes usage metrics when a UsageCollector is attached', async () => { - const collector = new MetricsCollector(); - const usageCollector = new UsageCollector(); - usageCollector.record('mod.usage', 'caller', 25, true); - usageCollector.record('mod.usage', 'caller', 30, false); - exporter = new PrometheusExporter({ collector, usageCollector }); - exporter.start({ port: 0 }); - const port = getPort(exporter); - - const r = await fetchText(port, '/metrics'); - expect(r.body).toContain('apcore_usage_calls_total'); - expect(r.body).toContain('apcore_usage_p50_latency_ms'); - }); - - it('export() omits usage block when no usage data has been recorded', () => { - const collector = new MetricsCollector(); - const usageCollector = new UsageCollector(); - const e = new PrometheusExporter({ collector, usageCollector }); - const text = e.export(); - expect(text).not.toContain('apcore_usage_calls_total'); - }); - - it('exposes rolling usage counts as gauges that fall as calls leave the window', () => { - vi.useFakeTimers(); - try { - vi.setSystemTime(new Date('2026-02-01T10:00:00Z')); - const collector = new MetricsCollector(); - collector.increment('demo_counter_total', {}); - const usageCollector = new UsageCollector(); - usageCollector.record('demo.one', 'client', 12, true); - const renderer = new PrometheusExporter({ collector, usageCollector }); - const before = renderer.export(); - vi.setSystemTime(new Date('2026-02-02T11:00:00Z')); - const after = renderer.export(); - - for (const family of ['apcore_usage_calls_24h', 'apcore_usage_calls_total']) { - const sample = `${family}{module_id="demo.one",status="success"}`; - expect(before.split('\n')).toContain(`# TYPE ${family} gauge`); - expect(before.split('\n')).toContain(`${sample} 1`); - expect(after.split('\n')).toContain(`${sample} 0`); - } - expect(before.endsWith('\n') && after.endsWith('\n')).toBe(true); - } finally { - vi.useRealTimers(); - } - }); -}); diff --git a/typescript/tests/observability/test-prometheus-renderer.test.ts b/typescript/tests/observability/test-prometheus-renderer.test.ts new file mode 100644 index 00000000..14b35409 --- /dev/null +++ b/typescript/tests/observability/test-prometheus-renderer.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest'; +import { + MetricsCollector, + UsageCollector, + renderPrometheusMetrics, +} from '../../src/observability/portable.js'; + +describe('renderPrometheusMetrics', () => { + it('preserves the collected text when there is no usage data', () => { + const bytes = 'sample_counter{label="\u6e2c\u8a66"} 1\n'; + const metrics = { exportPrometheus: () => bytes }; + expect(renderPrometheusMetrics(metrics)).toBe(bytes); + expect(renderPrometheusMetrics(metrics, new UsageCollector())).toBe(bytes); + }); + + it('preserves all usage metric families and the final newline', () => { + const collector = new MetricsCollector(); + collector.increment('sample_counter', {}); + const usageCollector = new UsageCollector(); + usageCollector.record('sample.module', 'caller', 25, true); + usageCollector.record('sample.module', 'caller', 30, false); + const usage = [ + '# HELP apcore_usage_calls_24h Module calls in the last 24 hours by status', + '# TYPE apcore_usage_calls_24h gauge', + 'apcore_usage_calls_24h{module_id="sample.module",status="success"} 1', + 'apcore_usage_calls_24h{module_id="sample.module",status="error"} 1', + '# HELP apcore_usage_calls_total Deprecated alias of apcore_usage_calls_24h', + '# TYPE apcore_usage_calls_total gauge', + 'apcore_usage_calls_total{module_id="sample.module",status="success"} 1', + 'apcore_usage_calls_total{module_id="sample.module",status="error"} 1', + '# HELP apcore_usage_error_rate Module error rate (0.0-1.0)', + '# TYPE apcore_usage_error_rate gauge', + 'apcore_usage_error_rate{module_id="sample.module"} 0.5', + '# HELP apcore_usage_p50_latency_ms Module p50 latency in milliseconds', + '# TYPE apcore_usage_p50_latency_ms gauge', + 'apcore_usage_p50_latency_ms{module_id="sample.module"} 25', + '# HELP apcore_usage_p95_latency_ms Module p95 latency in milliseconds', + '# TYPE apcore_usage_p95_latency_ms gauge', + 'apcore_usage_p95_latency_ms{module_id="sample.module"} 30', + '# HELP apcore_usage_p99_latency_ms Module p99 latency in milliseconds', + '# TYPE apcore_usage_p99_latency_ms gauge', + 'apcore_usage_p99_latency_ms{module_id="sample.module"} 30', + '', + ].join('\n'); + const rendered = renderPrometheusMetrics(collector, usageCollector); + expect(rendered).toBe(collector.exportPrometheus() + usage); + }); +}); diff --git a/typescript/tests/observability_spec.test.ts b/typescript/tests/observability_spec.test.ts index 2fcffb72..782d696b 100644 --- a/typescript/tests/observability_spec.test.ts +++ b/typescript/tests/observability_spec.test.ts @@ -12,7 +12,7 @@ * 2. `MetricsEmitter.record` — MISSING SYMBOL in apcore-typescript (no * `MetricsEmitter` export; the SDK ships * `MetricsCollector.increment` / `observe`). Skips. - * 3. `PrometheusExporter.export` — PRESENT and fully exercised. + * 3. `renderPrometheusMetrics` — PRESENT and fully exercised. * * Each `it(...)` name carries the verbatim clause id formatted * `observability...` so cross-language diffs line up @@ -23,7 +23,7 @@ import { describe, it, expect } from 'vitest'; import { MetricsCollector } from '../src/observability/metrics.js'; -import { PrometheusExporter } from '../src/observability/prometheus-exporter.js'; +import { renderPrometheusMetrics } from '../src/observability/prometheus.js'; import * as Observability from '../src/observability/index.js'; // --------------------------------------------------------------------------- @@ -40,10 +40,10 @@ const MetricsEmitter = (Observability as Record)['MetricsEmitte // Helpers // --------------------------------------------------------------------------- -function exporterWithOneCounter(): PrometheusExporter { +function collectorWithOneCounter(): MetricsCollector { const collector = new MetricsCollector(); collector.incrementCalls('math.add', 'success'); - return new PrometheusExporter({ collector }); + return collector; } // =========================================================================== @@ -97,39 +97,29 @@ describe('Contract: MetricsEmitter.record', () => { }); // =========================================================================== -// Contract 3: PrometheusExporter.export (PRESENT — fully exercised) +// Contract 3: renderPrometheusMetrics (PRESENT — fully exercised) // -// In apcore-typescript the `collector` from the contract's ### Inputs is -// supplied at construction (`new PrometheusExporter({ collector })`), and -// `export()` takes no arguments and returns the Prometheus text string. // =========================================================================== -describe('Contract: PrometheusExporter.export', () => { +describe('Contract: renderPrometheusMetrics', () => { it('observability.export.input.collector.required: collector is required and its live data is rendered', () => { - // Negative: the required `collector` arg cannot be omitted. The TS - // constructor dereferences `options.collector`, so calling with no - // argument throws a TypeError (mirrors Python's pytest.raises(TypeError)). - expect(() => new (PrometheusExporter as unknown as new () => PrometheusExporter)()).toThrow(TypeError); - - // Positive: a supplied collector's data is what `export()` renders. const collector = new MetricsCollector(); collector.incrementCalls('math.add', 'success'); - const exporter = new PrometheusExporter({ collector }); - const text = exporter.export(); + const text = renderPrometheusMetrics(collector); expect(text).toContain('apcore_module_calls_total'); expect(text).toContain('module_id="math.add"'); expect(text).toContain('status="success"'); }); it('observability.export.error.none: export over empty collector returns string without throwing', () => { - const exporter = new PrometheusExporter({ collector: new MetricsCollector() }); - const text = exporter.export(); + const collector = new MetricsCollector(); + const text = renderPrometheusMetrics(collector); expect(typeof text).toBe('string'); }); it('observability.export.returns.prometheus_text: returns UTF-8 string with HELP/TYPE comment lines', () => { - const exporter = exporterWithOneCounter(); - const text = exporter.export(); + const collector = collectorWithOneCounter(); + const text = renderPrometheusMetrics(collector); expect(typeof text).toBe('string'); // Round-trips through UTF-8 without loss. expect(Buffer.from(text, 'utf-8').toString('utf-8')).toBe(text); @@ -139,17 +129,17 @@ describe('Contract: PrometheusExporter.export', () => { }); it('observability.export.property.async: export() is synchronous, returns a concrete string (not a Promise)', () => { - const exporter = exporterWithOneCounter(); - const result = exporter.export(); + const collector = collectorWithOneCounter(); + const result = renderPrometheusMetrics(collector); expect(typeof result).toBe('string'); expect(result).not.toBeInstanceOf(Promise); }); it('observability.export.property.thread_safe: >=8 concurrent exports yield identical snapshots, no throw', async () => { - const exporter = exporterWithOneCounter(); + const collector = collectorWithOneCounter(); const doExport = async (): Promise => { await Promise.resolve(); - return exporter.export(); + return renderPrometheusMetrics(collector); }; const results = await Promise.all(Array.from({ length: 12 }, () => doExport())); expect(results.length).toBe(12); @@ -161,10 +151,9 @@ describe('Contract: PrometheusExporter.export', () => { it('observability.export.property.pure: export() does not mutate collector but reflects live state', () => { const collector = new MetricsCollector(); collector.incrementCalls('math.add', 'success'); - const exporter = new PrometheusExporter({ collector }); const before = JSON.stringify(collector.snapshot()); - const first = exporter.export(); + const first = renderPrometheusMetrics(collector); const after = JSON.stringify(collector.snapshot()); // export() is a query: it does not mutate collector state. expect(before).toBe(after); @@ -172,15 +161,15 @@ describe('Contract: PrometheusExporter.export', () => { // Live-state coupling: a new module appears on the next export. collector.incrementCalls('math.sub', 'success'); - const second = exporter.export(); + const second = renderPrometheusMetrics(collector); expect(second).toContain('module_id="math.sub"'); expect(first).not.toContain('module_id="math.sub"'); }); it('observability.export.property.idempotent: two successive calls on unchanged state are identical', () => { - const exporter = exporterWithOneCounter(); - const first = exporter.export(); - const second = exporter.export(); + const collector = collectorWithOneCounter(); + const first = renderPrometheusMetrics(collector); + const second = renderPrometheusMetrics(collector); expect(first).toBe(second); expect(first).not.toBe(''); }); diff --git a/typescript/tests/policy.test.ts b/typescript/tests/policy.test.ts index 2c0087a3..6b754835 100644 --- a/typescript/tests/policy.test.ts +++ b/typescript/tests/policy.test.ts @@ -147,8 +147,8 @@ describe('ExecutionPolicy.fromObject', () => { it('parses an empty document', () => { const policy = ExecutionPolicy.fromObject({}); expect(policy.rules).toHaveLength(0); - expect(policy.gateDestructive).toBe(false); - expect(policy.strict).toBe(false); + expect(policy.gateDestructive).toBe(true); + expect(policy.strict).toBe(true); }); it('rejects a non-mapping', () => { @@ -343,8 +343,8 @@ describe('Approval gate with policy', () => { expect(result['status']).toBe('executed'); }); - it('warns once and skips when a handler is missing (fail-loud default)', async () => { - const executor = new Executor({ registry: makeRegistry() }); + it('warns once when strict mode is explicitly disabled and a handler is missing', async () => { + const executor = new Executor({ registry: makeRegistry(), policy: new ExecutionPolicy([], { strict: false }) }); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { expect((await executor.call('admin.reset'))['status']).toBe('executed'); @@ -361,7 +361,7 @@ describe('Approval gate with policy', () => { }); it('warns once about a destructive-ungated module', async () => { - const executor = new Executor({ registry: makeRegistry() }); + const executor = new Executor({ registry: makeRegistry(), policy: new ExecutionPolicy([], { gateDestructive: false }) }); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { await executor.call('orders.delete_order'); @@ -400,6 +400,7 @@ describe('Approval gate with policy', () => { const executor = new Executor({ registry: makeRegistry(), approvalHandler: new AlwaysDenyHandler(), + policy: new ExecutionPolicy([], { gateDestructive: false }), }); expect((await executor.call('orders.delete_order'))['status']).toBe('executed'); @@ -409,7 +410,7 @@ describe('Approval gate with policy', () => { await expect(executor.call('orders.delete_order')).rejects.toThrow(ApprovalDeniedError); executor.setPolicy(null); - expect((await executor.call('orders.delete_order'))['status']).toBe('executed'); + await expect(executor.call('orders.delete_order')).rejects.toThrow(ApprovalDeniedError); }); it('policy-gated request upholds the annotations contract', async () => { @@ -579,7 +580,8 @@ describe('Governance events', () => { it('emits no decision event when the gate is skipped without a handler', async () => { const emitter = new CollectingEmitter(); - const executor = new Executor({ registry: makeRegistry(), eventEmitter: asEmitter(emitter) }); + const executor = new Executor({ registry: makeRegistry(), + policy: new ExecutionPolicy([], { strict: false }), eventEmitter: asEmitter(emitter) }); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { await executor.call('admin.reset'); diff --git a/typescript/tests/registry/test-discover-default-stages.test.ts b/typescript/tests/registry/test-discover-default-stages.test.ts index 3bc55cbd..86276142 100644 --- a/typescript/tests/registry/test-discover-default-stages.test.ts +++ b/typescript/tests/registry/test-discover-default-stages.test.ts @@ -17,7 +17,7 @@ * modules are registered in dependency order. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { Registry } from '../../src/registry/registry.js'; +import { Registry } from '../../src/full.js'; import { detectIdConflicts } from '../../src/registry/conflicts.js'; describe('_discoverDefault 8-stage decomposition (D-32)', () => { diff --git a/typescript/tests/registry/test-ephemeral-namespace.test.ts b/typescript/tests/registry/test-ephemeral-namespace.test.ts index 4792092e..23872311 100644 --- a/typescript/tests/registry/test-ephemeral-namespace.test.ts +++ b/typescript/tests/registry/test-ephemeral-namespace.test.ts @@ -12,11 +12,8 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { Type } from '@sinclair/typebox'; -import { - Registry, - EPHEMERAL_NAMESPACE_PREFIX, - isEphemeralModuleId, -} from '../../src/registry/registry.js'; +import { Registry } from '../../src/full.js'; +import { EPHEMERAL_NAMESPACE_PREFIX, isEphemeralModuleId } from '../../src/registry/registry.js'; import { FunctionModule } from '../../src/decorator.js'; import { InvalidInputError } from '../../src/errors.js'; import { createAnnotations } from '../../src/module.js'; diff --git a/typescript/tests/registry/test-registry-load-ordering.test.ts b/typescript/tests/registry/test-registry-load-ordering.test.ts index 5cb16e6a..badc34ee 100644 --- a/typescript/tests/registry/test-registry-load-ordering.test.ts +++ b/typescript/tests/registry/test-registry-load-ordering.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { Registry } from '../../src/registry/registry.js'; +import { Registry } from '../../src/full.js'; import { EventEmitter } from '../../src/events/emitter.js'; import { DuplicateModuleIdError, InvalidInputError } from '../../src/errors.js'; diff --git a/typescript/tests/registry/test-registry.test.ts b/typescript/tests/registry/test-registry.test.ts index 999983f1..a70fbe5d 100644 --- a/typescript/tests/registry/test-registry.test.ts +++ b/typescript/tests/registry/test-registry.test.ts @@ -5,9 +5,10 @@ import { tmpdir } from 'node:os'; import { fileURLToPath } from 'node:url'; import { EventEmitter as NodeEventEmitter } from 'node:events'; import type { FSWatcher } from 'node:fs'; -import { registryNodeFilesystem } from '../../src/registry/install-filesystem.js'; +import { createRegistryFilesystem } from '../../src/registry/node-filesystem.js'; import { Type } from '@sinclair/typebox'; -import { Registry, MAX_MODULE_ID_LENGTH } from '../../src/registry/registry.js'; +import { Registry } from '../../src/full.js'; +import { MAX_MODULE_ID_LENGTH } from '../../src/registry/registry.js'; import { FunctionModule } from '../../src/decorator.js'; import { DuplicateModuleIdError, InvalidInputError, ModuleNotFoundError, ReloadFailedError } from '../../src/errors.js'; import { Config } from '../../src/config.js'; @@ -1578,6 +1579,7 @@ describe('Registry discover() with idMapPath', () => { it('encodes literal path characters for discovery and adds a fresh query for each reload', () => { const source = join(tempDir, 'extensions # %', 'module.js'); + const registryNodeFilesystem = createRegistryFilesystem(); const initial = new URL(registryNodeFilesystem.entryPointSpecifier(source, false)); const reloaded = new URL(registryNodeFilesystem.entryPointSpecifier(source, true)); @@ -1902,7 +1904,8 @@ describe('Registry hot reload (watch/unwatch)', () => { inputSchema: { type: 'object' }, outputSchema: { type: 'object' }, };`); } - const registry = new Registry({ extensionsDir: tempDir }); + const registryNodeFilesystem = createRegistryFilesystem(); + const registry = new Registry({ filesystem: registryNodeFilesystem, extensionsDir: tempDir }); await expect(registry.discover()).resolves.toBe(2); const onChange = vi.fn(); registry.on('file_changed', onChange); @@ -1932,7 +1935,8 @@ describe('Registry hot reload (watch/unwatch)', () => { execute() { return {}; }, description: 'Watched source', inputSchema: { type: 'object' }, outputSchema: { type: 'object' }, };`); - const registry = new Registry({ extensionsDirs: [{ root: tempDir, namespace: 'ns' }] }); + const registryNodeFilesystem = createRegistryFilesystem(); + const registry = new Registry({ filesystem: registryNodeFilesystem, extensionsDirs: [{ root: tempDir, namespace: 'ns' }] }); await expect(registry.discover()).resolves.toBe(1); vi.spyOn(registry, 'discover').mockResolvedValue(0); const reload = new ReloadModule(registry, new EventEmitter()); @@ -1966,7 +1970,8 @@ describe('Registry hot reload (watch/unwatch)', () => { execute() { return {}; }, description: 'Watched source', inputSchema: { type: 'object' }, outputSchema: { type: 'object' }, };`); - const registry = new Registry({ extensionsDirs: [{ root: tempDir, namespace: 'ns' }] }); + const registryNodeFilesystem = createRegistryFilesystem(); + const registry = new Registry({ filesystem: registryNodeFilesystem, extensionsDirs: [{ root: tempDir, namespace: 'ns' }] }); await expect(registry.discover()).resolves.toBe(1); const moduleId = 'ns.active_module'; const module = registry.get(moduleId) as Record; @@ -2009,7 +2014,8 @@ describe('Registry hot reload (watch/unwatch)', () => { execute() { return {}; }, description: 'Managed watch source', inputSchema: { type: 'object' }, outputSchema: { type: 'object' }, };`); - const registry = new Registry({ extensionsDir: tempDir }); + const registryNodeFilesystem = createRegistryFilesystem(); + const registry = new Registry({ filesystem: registryNodeFilesystem, extensionsDir: tempDir }); await expect(registry.discover()).resolves.toBe(1); const moduleId = 'managed_watch'; const old = registry.get(moduleId) as Record; @@ -2063,7 +2069,8 @@ describe('Registry hot reload (watch/unwatch)', () => { }); it('forgets expired debounce entries and clears current entries on unwatch', async () => { - const registry = new Registry({ extensionsDir: tempDir }); + const registryNodeFilesystem = createRegistryFilesystem(); + const registry = new Registry({ filesystem: registryNodeFilesystem, extensionsDir: tempDir }); const onChange = vi.fn(); registry.on('file_changed', onChange); let notify!: (eventType: string, filename: string | null) => void; diff --git a/typescript/tests/registry/test-schema-export.test.ts b/typescript/tests/registry/test-schema-export.test.ts index b558a41e..b7bf1ebc 100644 --- a/typescript/tests/registry/test-schema-export.test.ts +++ b/typescript/tests/registry/test-schema-export.test.ts @@ -286,47 +286,6 @@ describe('exportAllSchemas', () => { }); describe('exportSchema with profile', () => { - it('exports with mcp profile and returns valid JSON with MCP shape', () => { - const mod = createModule('mcp.mod'); - const registry = makeRegistry(['mcp.mod', mod]); - - const result = exportSchema(registry, 'mcp.mod', 'json', false, false, 'mcp'); - const parsed = JSON.parse(result); - expect(parsed['name']).toBeDefined(); - expect(parsed['description']).toBeDefined(); - expect(parsed['inputSchema']).toBeDefined(); - expect(parsed['annotations']).toBeDefined(); - expect(parsed['annotations']['readOnlyHint']).toBe(true); - expect(parsed['annotations']['destructiveHint']).toBe(false); - }); - - it('exports with openai profile and returns function tool shape', () => { - const mod = createModule('openai.mod'); - const registry = makeRegistry(['openai.mod', mod]); - - const result = exportSchema(registry, 'openai.mod', 'json', false, false, 'openai'); - const parsed = JSON.parse(result); - expect(parsed['type']).toBe('function'); - expect(parsed['function']).toBeDefined(); - expect(parsed['function']['name']).toBe('openai_mod'); - expect(parsed['function']['description']).toBeDefined(); - expect(parsed['function']['parameters']).toBeDefined(); - expect(parsed['function']['strict']).toBe(true); - }); - - it('exports with anthropic profile and returns tool shape with input_examples', () => { - const mod = createModule('anthro.mod'); - const registry = makeRegistry(['anthro.mod', mod]); - - const result = exportSchema(registry, 'anthro.mod', 'json', false, false, 'anthropic'); - const parsed = JSON.parse(result); - expect(parsed['name']).toBe('anthro_mod'); - expect(parsed['description']).toBeDefined(); - expect(parsed['input_schema']).toBeDefined(); - expect(parsed['input_examples']).toBeDefined(); - expect((parsed['input_examples'] as unknown[]).length).toBe(1); - }); - it('exports with generic profile and returns module_id and schema fields', () => { const mod = createModule('generic.mod'); const registry = makeRegistry(['generic.mod', mod]); @@ -340,31 +299,12 @@ describe('exportSchema with profile', () => { expect(parsed['definitions']).toBeDefined(); }); - it('exports with profile using yaml format', () => { - const mod = createModule('mcp.yaml'); - const registry = makeRegistry(['mcp.yaml', mod]); - - const result = exportSchema(registry, 'mcp.yaml', 'yaml', false, false, 'mcp'); - expect(result).toContain('name:'); - expect(result).toContain('inputSchema:'); - }); - - it('throws InvalidInputError for an unrecognized profile name', () => { - const mod = createModule('bad.profile'); - const registry = makeRegistry(['bad.profile', mod]); - - expect(() => - exportSchema(registry, 'bad.profile', 'json', false, false, 'not_a_real_profile'), - ).toThrow(InvalidInputError); - }); - - it('includes the invalid profile name in the error message', () => { - const mod = createModule('err.profile'); - const registry = makeRegistry(['err.profile', mod]); - - expect(() => - exportSchema(registry, 'err.profile', 'json', false, false, 'bogus'), - ).toThrowError(/bogus/); + it('rejects profiles owned by protocol adapters', () => { + const registry = makeRegistry(['profile.demo', createModule('profile.demo')]); + for (const profile of ['mcp', 'openai', 'anthropic']) { + expect(() => exportSchema(registry, 'profile.demo', 'json', false, false, profile)) + .toThrow("Only the 'generic' export profile is supported by Core"); + } }); }); diff --git a/typescript/tests/schema/test-exporter.test.ts b/typescript/tests/schema/test-exporter.test.ts index b83ccbc0..d48e3296 100644 --- a/typescript/tests/schema/test-exporter.test.ts +++ b/typescript/tests/schema/test-exporter.test.ts @@ -6,7 +6,6 @@ import { describe, it, expect } from 'vitest'; import { SchemaExporter } from '../../src/schema/exporter.js'; import { ExportProfile } from '../../src/schema/types.js'; import type { SchemaDefinition } from '../../src/schema/types.js'; -import type { ModuleAnnotations, ModuleExample } from '../../src/module.js'; function makeSchemaDef(overrides?: Partial): SchemaDefinition { return { @@ -46,192 +45,10 @@ describe('SchemaExporter', () => { }); }); - describe('exportMcp', () => { - it('returns MCP tool format with annotations', () => { - const sd = makeSchemaDef(); - const annotations: ModuleAnnotations = { - readonly: true, - destructive: false, - idempotent: true, - requiresApproval: false, - openWorld: false, - streaming: false, - cacheable: false, - cacheTtl: 0, - cacheKeyFields: null, - paginated: false, - paginationStyle: 'cursor', extra: {}, - }; - const result = exporter.exportMcp(sd, annotations, 'MyTool'); - expect(result['name']).toBe('MyTool'); - expect(result['description']).toBe('A test module'); - expect(result['inputSchema']).toEqual(sd.inputSchema); - const annots = result['annotations'] as Record; - expect(annots['readOnlyHint']).toBe(true); - expect(annots['destructiveHint']).toBe(false); - expect(annots['idempotentHint']).toBe(true); - expect(annots['openWorldHint']).toBe(false); - expect(annots).not.toHaveProperty('streaming'); - expect(result['_meta']).not.toHaveProperty('streaming'); - }); - - it('includes streaming hint when annotation is true', () => { - const sd = makeSchemaDef(); - const annotations: ModuleAnnotations = { - readonly: false, - destructive: false, - idempotent: false, - requiresApproval: false, - openWorld: true, - streaming: true, - cacheable: false, - cacheTtl: 0, - cacheKeyFields: null, - paginated: false, - paginationStyle: 'cursor', extra: {}, - }; - const result = exporter.exportMcp(sd, annotations); - const annots = result['annotations'] as Record; - expect(annots).not.toHaveProperty('streaming'); - expect(result['_meta']).toHaveProperty('streaming', true); - }); - - it('falls back to moduleId when name is null', () => { - const sd = makeSchemaDef(); - const result = exporter.exportMcp(sd, null, null); - expect(result['name']).toBe('test.module'); - }); - - it('includes _meta with cache and pagination defaults when annotations is null', () => { - const sd = makeSchemaDef(); - const result = exporter.exportMcp(sd, null); - const meta = result['_meta'] as Record; - expect(meta['cacheable']).toBe(false); - expect(meta['cacheTtl']).toBe(0); - expect(meta['cacheKeyFields']).toBeNull(); - expect(meta['paginated']).toBe(false); - expect(meta['paginationStyle']).toBe('cursor'); - }); - - it('includes _meta with cache and pagination values from annotations', () => { - const sd = makeSchemaDef(); - const annotations: ModuleAnnotations = { - readonly: false, - destructive: false, - idempotent: false, - requiresApproval: false, - openWorld: true, - streaming: false, - cacheable: true, - cacheTtl: 120, - cacheKeyFields: ['userId'], - paginated: true, - paginationStyle: 'offset', extra: {}, - }; - const result = exporter.exportMcp(sd, annotations); - const meta = result['_meta'] as Record; - expect(meta['cacheable']).toBe(true); - expect(meta['cacheTtl']).toBe(120); - expect(meta['cacheKeyFields']).toEqual(['userId']); - expect(meta['paginated']).toBe(true); - expect(meta['paginationStyle']).toBe('offset'); - }); - - it('uses default annotation values when annotations is null', () => { - const sd = makeSchemaDef(); - const result = exporter.exportMcp(sd, null); - const annots = result['annotations'] as Record; - expect(annots['readOnlyHint']).toBe(false); - expect(annots['destructiveHint']).toBe(false); - expect(annots['idempotentHint']).toBe(false); - expect(annots['openWorldHint']).toBe(true); - expect(annots).not.toHaveProperty('streaming'); - expect(result['_meta']).not.toHaveProperty('streaming'); - }); - }); - - describe('exportOpenai', () => { - it('returns OpenAI function calling format with strict schema', () => { - const sd = makeSchemaDef(); - const result = exporter.exportOpenai(sd); - expect(result['type']).toBe('function'); - const fn = result['function'] as Record; - expect(fn['name']).toBe('test_module'); - expect(fn['description']).toBe('A test module'); - expect(fn['strict']).toBe(true); - const params = fn['parameters'] as Record; - expect(params['additionalProperties']).toBe(false); - }); - - it('applies x-llm-description to properties', () => { - const sd = makeSchemaDef(); - const result = exporter.exportOpenai(sd); - const fn = result['function'] as Record; - const params = fn['parameters'] as Record; - const props = params['properties'] as Record>; - expect(props['name']['description']).toBe('LLM Name'); - }); - }); - - describe('exportAnthropic', () => { - it('returns Anthropic tool format', () => { - const sd = makeSchemaDef(); - const result = exporter.exportAnthropic(sd); - expect(result['name']).toBe('test_module'); - expect(result['description']).toBe('A test module'); - expect(result['input_schema']).toBeDefined(); - }); - - it('includes input_examples when examples are provided', () => { - const sd = makeSchemaDef(); - const examples: ModuleExample[] = [ - { title: 'Ex1', inputs: { name: 'Alice' }, output: { result: 'ok' } }, - ]; - const result = exporter.exportAnthropic(sd, examples); - const inputExamples = result['input_examples'] as Array>; - expect(inputExamples).toHaveLength(1); - expect(inputExamples[0]).toEqual({ name: 'Alice' }); - }); - - it('omits input_examples when no examples', () => { - const sd = makeSchemaDef(); - const result = exporter.exportAnthropic(sd, []); - expect(result['input_examples']).toBeUndefined(); - }); - - it('strips x- extensions from schema', () => { - const sd = makeSchemaDef(); - const result = exporter.exportAnthropic(sd); - const schema = result['input_schema'] as Record; - const props = schema['properties'] as Record>; - expect(props['name']['x-llm-description']).toBeUndefined(); - }); - }); - - describe('export dispatch', () => { - it('dispatches to MCP profile', () => { - const sd = makeSchemaDef(); - const result = exporter.export(sd, ExportProfile.MCP); - expect(result['name']).toBe('test.module'); - expect(result['annotations']).toBeDefined(); - }); - - it('dispatches to OpenAI profile', () => { - const sd = makeSchemaDef(); - const result = exporter.export(sd, ExportProfile.OPENAI); - expect(result['type']).toBe('function'); - }); - - it('dispatches to Anthropic profile', () => { - const sd = makeSchemaDef(); - const result = exporter.export(sd, ExportProfile.ANTHROPIC); - expect(result['input_schema']).toBeDefined(); - }); - - it('dispatches to Generic profile', () => { - const sd = makeSchemaDef(); - const result = exporter.export(sd, ExportProfile.GENERIC); - expect(result['module_id']).toBe('test.module'); - }); + it('defaults to the generic profile and supports its explicit name', () => { + const schema = makeSchemaDef(); + const expected = exporter.exportGeneric(schema); + expect(exporter.export(schema)).toEqual(expected); + expect(exporter.export(schema, ExportProfile.GENERIC)).toEqual(expected); }); }); diff --git a/typescript/tests/schema/test-strict.test.ts b/typescript/tests/schema/test-strict.test.ts index 70b193de..30e18dba 100644 --- a/typescript/tests/schema/test-strict.test.ts +++ b/typescript/tests/schema/test-strict.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { toStrictSchema, applyLlmDescriptions, stripExtensions } from '../../src/schema/strict.js'; +import { toStrictSchema, stripExtensions } from '../../src/schema/strict.js'; describe('toStrictSchema', () => { it('preserves boolean schemas for optional properties and sorts property names by code point', () => { @@ -89,54 +89,6 @@ describe('toStrictSchema', () => { }); }); -describe('applyLlmDescriptions', () => { - it('replaces description with x-llm-description', () => { - const schema = { - description: 'Original', - 'x-llm-description': 'LLM version', - properties: { - name: { - type: 'string', - description: 'Name', - 'x-llm-description': 'User name for LLM', - }, - }, - }; - applyLlmDescriptions(schema); - expect(schema['description']).toBe('LLM version'); - expect((schema['properties'] as Record>)['name']['description']).toBe('User name for LLM'); - }); - - it('does not modify without x-llm-description', () => { - const schema = { description: 'Original' }; - applyLlmDescriptions(schema); - expect(schema['description']).toBe('Original'); - }); - - it('does not inject a description when only x-llm-description is present', () => { - const schema: Record = { - type: 'string', - 'x-llm-description': 'LLM only', - }; - applyLlmDescriptions(schema); - expect('description' in schema).toBe(false); - }); - - it('does not gain a description after strict export when only x-llm-description present', () => { - const schema = { - type: 'object', - properties: { - name: { type: 'string', 'x-llm-description': 'Name for LLM' }, - }, - required: ['name'], - }; - applyLlmDescriptions(schema); - const result = toStrictSchema(schema); - const props = result['properties'] as Record>; - expect('description' in props['name']).toBe(false); - }); -}); - describe('toStrictSchema - definitions and combinators', () => { it('recurses into definitions block', () => { const schema = { @@ -379,61 +331,6 @@ describe('toStrictSchema - definitions and combinators', () => { }); }); -describe('applyLlmDescriptions - definitions and combinators', () => { - it('recurses into definitions block', () => { - const schema: Record = { - definitions: { - Foo: { description: 'old', 'x-llm-description': 'new' }, - }, - }; - applyLlmDescriptions(schema); - const defs = schema['definitions'] as Record>; - expect(defs['Foo']['description']).toBe('new'); - }); - - it('recurses into $defs block', () => { - const schema: Record = { - $defs: { - Bar: { description: 'old', 'x-llm-description': 'updated' }, - }, - }; - applyLlmDescriptions(schema); - const defs = schema['$defs'] as Record>; - expect(defs['Bar']['description']).toBe('updated'); - }); - - it('recurses into items', () => { - const schema: Record = { - type: 'array', - items: { description: 'orig', 'x-llm-description': 'item desc' }, - }; - applyLlmDescriptions(schema); - const items = schema['items'] as Record; - expect(items['description']).toBe('item desc'); - }); - - it('recurses into oneOf/anyOf/allOf', () => { - const schema: Record = { - oneOf: [ - { description: 'a', 'x-llm-description': 'variant A' }, - { description: 'b', 'x-llm-description': 'variant B' }, - ], - }; - applyLlmDescriptions(schema); - const oneOf = schema['oneOf'] as Record[]; - expect(oneOf[0]['description']).toBe('variant A'); - expect(oneOf[1]['description']).toBe('variant B'); - }); - - it('does not set a description when no prior description exists', () => { - const schema: Record = { - 'x-llm-description': 'brand new', - }; - applyLlmDescriptions(schema); - expect('description' in schema).toBe(false); - }); -}); - describe('stripExtensions', () => { it('removes x- prefixed keys', () => { const schema: Record = { diff --git a/typescript/tests/setup-node-installers.ts b/typescript/tests/setup-node-installers.ts deleted file mode 100644 index 68febfb6..00000000 --- a/typescript/tests/setup-node-installers.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Vitest setup: install the Node-only file readers that the package's - * Node entry (`src/index.ts`) wires up via side-effect imports. - * - * Tests typically import individual source files directly - * (`from '../src/acl.js'` etc.), which skips the Node entry and so - * leaves `ACL.load`, `registerSysModules` overrides loading, etc. in - * their browser-no-op state. Importing the side-effect modules here - * runs them once before any test executes. - */ - -import '../src/acl-file.js'; -import '../src/registry/install-filesystem.js'; -import '../src/sys-modules/overrides-file.js'; -import '../src/sys-modules/install.js'; diff --git a/typescript/tests/sys-modules/test-overrides-path-round-trip.test.ts b/typescript/tests/sys-modules/test-overrides-path-round-trip.test.ts index 73502668..772a8a4c 100644 --- a/typescript/tests/sys-modules/test-overrides-path-round-trip.test.ts +++ b/typescript/tests/sys-modules/test-overrides-path-round-trip.test.ts @@ -1,3 +1,4 @@ +import { AutoApproveHandler } from '../../src/approval.js'; /** * SYS-2 — `sys_modules.control.overrides_path` must persist a toggle, not * only restore one. @@ -35,7 +36,7 @@ const DUMMY = { function boot(overridesPath: string, toggleState: ToggleState) { const registry = new Registry(); - const executor = new Executor({ registry }); + const executor = new Executor({ registry, approvalHandler: new AutoApproveHandler() }); const config = new Config({ sys_modules: { enabled: true, @@ -121,7 +122,7 @@ describe('sys_modules.control.overrides_path round trip (SYS-2)', () => { }; const registry = new Registry(); - const executor = new Executor({ registry }); + const executor = new Executor({ registry, approvalHandler: new AutoApproveHandler() }); const config = new Config({ sys_modules: { enabled: true, diff --git a/typescript/tests/sys-modules/test-reload-dependents-deprecation.test.ts b/typescript/tests/sys-modules/test-reload-dependents-deprecation.test.ts deleted file mode 100644 index ed22e91a..00000000 --- a/typescript/tests/sys-modules/test-reload-dependents-deprecation.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -/** - * D-121 — `reload_dependents` is deprecated for removal. - * - * Declared in all three SDKs' input schemas and read by none: a spec MUST - * ("also reload modules that depend on matched modules") that no implementation - * satisfied. That is the §9.1.3 "declared surface reaches no mechanism" shape - * the spec forbids for configuration keys, here applied to a module INPUT - * FIELD, and three independent implementations skipping it is the evidence the - * maintainer decision rests on — deprecate now, remove at 2.0, do NOT - * implement. - * - * Deprecated rather than removed today because the input schema sets - * `additionalProperties: false`: at 2.0 the same call stops being a silent - * no-op and becomes a VALIDATION ERROR, so a caller passing it needs a release - * in which they are told. - */ - -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { ReloadModule } from '../../src/sys-modules/control.js'; -import { Registry } from '../../src/registry/registry.js'; -import { EventEmitter } from '../../src/events/emitter.js'; - -function reloadModule(): ReloadModule { - return new ReloadModule(new Registry(), new EventEmitter()); -} - -/** Reach the private warner the way the executor's `execute` does. */ -function warn(mod: ReloadModule, inputs: Record): void { - (mod as unknown as { _warnReloadDependents(i: Record): void })._warnReloadDependents( - inputs, - ); -} - -function countWarnings(f: () => void): string[] { - const spy = vi.spyOn(console, 'warn').mockImplementation(() => {}); - try { - f(); - return spy.mock.calls - .map((c) => String(c[0])) - .filter((m) => m.includes('reload_dependents')); - } finally { - spy.mockRestore(); - } -} - -describe('D-121: reload_dependents is deprecated', () => { - afterEach(() => vi.restoreAllMocks()); - - it('passing it warns', () => { - expect(countWarnings(() => warn(reloadModule(), { reload_dependents: true }))).toHaveLength(1); - }); - - it('the warning names the replacement and the removal', () => { - // A deprecation notice that does not say what to do instead, or when the - // field stops being ignored, leaves the caller to discover both. - const [message] = countWarnings(() => warn(reloadModule(), { reload_dependents: true })); - expect(message).toContain('path_filter'); - expect(message).toContain('2.0'); - expect(message).toContain('validation error'); - }); - - it('it warns once per instance', () => { - // `reload` is called by hot-reload loops and watchers, so an advisory whose - // volume is proportional to traffic is one operators learn to filter out — - // the cadence D-89 settled. - const mod = reloadModule(); - expect( - countWarnings(() => { - for (let i = 0; i < 5; i++) warn(mod, { reload_dependents: true }); - }), - ).toHaveLength(1); - }); - - it('the cadence is per instance, not per process', () => { - // A process-wide one-shot tells the FIRST caller and leaves every later one - // to discover it in production — the reason D-90's notice is per token and - // D-89's dedupe is per registry instance. - expect( - countWarnings(() => { - warn(reloadModule(), { reload_dependents: true }); - warn(reloadModule(), { reload_dependents: true }); - }), - ).toHaveLength(2); - }); - - it.each([[{}], [{ reload_dependents: false }]])( - 'control: omitting it or passing false says nothing (%o)', - (inputs) => { - // Without this, "it warns" is also satisfied by warning on every reload, - // which is noise for the ordinary call the method exists for. - expect(countWarnings(() => warn(reloadModule(), inputs))).toHaveLength(0); - }, - ); - - it('the schema marks it deprecated and says what replaces it', () => { - // The notice has to be readable WITHOUT triggering it: a host reading the - // input schema — which is what `describe` / `getDefinition` hand an agent — - // must see the deprecation without having to call with the field. - const field = ( - reloadModule().inputSchema.properties as Record> - )['reload_dependents']; - expect(field['deprecated']).toBe(true); - expect(String(field['description'])).toContain('path_filter'); - expect(String(field['description'])).toContain('2.0'); - }); -}); diff --git a/typescript/tests/test-acl-audit-delivery.test.ts b/typescript/tests/test-acl-audit-delivery.test.ts index a8450b10..fd51135e 100644 --- a/typescript/tests/test-acl-audit-delivery.test.ts +++ b/typescript/tests/test-acl-audit-delivery.test.ts @@ -19,10 +19,10 @@ import path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import yaml from 'js-yaml'; -import { ACL, AUDIT_EVENT_NAME } from '../src/acl.js'; +import { ACL } from '../src/full.js'; +import { AUDIT_EVENT_NAME } from '../src/acl.js'; import type { ACLRule, AuditEntry } from '../src/acl.js'; import { ConfigError } from '../src/errors.js'; -import '../src/acl-file.js'; const RULES = [{ callers: ['api.*'], targets: ['executor.*'], effect: 'allow' }]; diff --git a/typescript/tests/test-acl-discovery.test.ts b/typescript/tests/test-acl-discovery.test.ts index f688ce7b..5401b05b 100644 --- a/typescript/tests/test-acl-discovery.test.ts +++ b/typescript/tests/test-acl-discovery.test.ts @@ -15,14 +15,14 @@ import { writeFileSync, mkdtempSync, mkdirSync, rmSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { tmpdir } from 'node:os'; import { Type } from '@sinclair/typebox'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import { Config } from '../src/config.js'; import { Executor } from '../src/executor.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import { FunctionModule } from '../src/decorator.js'; import { getDefault } from '../src/config-defaults.js'; import { ACLDeniedError, ConfigError } from '../src/errors.js'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; function makeModule(id: string): FunctionModule { return new FunctionModule({ diff --git a/typescript/tests/test-acl-unevaluable-conditions.test.ts b/typescript/tests/test-acl-unevaluable-conditions.test.ts index bd089a63..0844d738 100644 --- a/typescript/tests/test-acl-unevaluable-conditions.test.ts +++ b/typescript/tests/test-acl-unevaluable-conditions.test.ts @@ -15,7 +15,7 @@ import { describe, it, expect, afterEach, beforeEach, vi, type MockInstance } fr import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import type { ACLRule, AuditEntry, RuleValidationFinding } from '../src/acl.js'; import type { ACLConditionHandler } from '../src/acl-handlers.js'; import { ACLRuleError } from '../src/errors.js'; diff --git a/typescript/tests/test-acl.test.ts b/typescript/tests/test-acl.test.ts index a2bb7167..51874f57 100644 --- a/typescript/tests/test-acl.test.ts +++ b/typescript/tests/test-acl.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { writeFileSync, mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import type { AuditEntry } from '../src/acl.js'; import type { ACLConditionHandler } from '../src/acl-handlers.js'; import { ACLRuleError, ConfigNotFoundError } from '../src/errors.js'; diff --git a/typescript/tests/test-approval-executor.test.ts b/typescript/tests/test-approval-executor.test.ts index 33c68bd8..33a22f49 100644 --- a/typescript/tests/test-approval-executor.test.ts +++ b/typescript/tests/test-approval-executor.test.ts @@ -1,3 +1,4 @@ +import { ExecutionPolicy } from '../src/policy.js'; /** * Unit tests for the approval gate in the Executor (Step 4.5). */ @@ -170,7 +171,7 @@ function createTestRegistry(): Registry { describe('ApprovalGate call()', () => { it('skips gate when no handler is configured', async () => { const registry = createTestRegistry(); - const executor = new Executor({ registry }); + const executor = new Executor({ registry, policy: new ExecutionPolicy([], { strict: false }) }); const result = await executor.call('test.approval_required'); expect(result['status']).toBe('executed'); }); @@ -267,13 +268,10 @@ describe('ApprovalGate call()', () => { const registry = createTestRegistry(); const executor = new Executor({ registry }); - // No handler → executes - const result = await executor.call('test.approval_required'); - expect(result['status']).toBe('executed'); - - // Set deny handler → raises - executor.setApprovalHandler(new AlwaysDenyHandler()); await expect(executor.call('test.approval_required')).rejects.toThrow(ApprovalDeniedError); + + executor.setApprovalHandler(new AutoApproveHandler()); + await expect(executor.call('test.approval_required')).resolves.toMatchObject({ status: 'executed' }); }); it('carries correct context in ApprovalRequest', async () => { @@ -379,7 +377,7 @@ describe('ApprovalGate call()', () => { describe('ApprovalGate callAsync()', () => { it('skips gate when no handler configured', async () => { const registry = createTestRegistry(); - const executor = new Executor({ registry }); + const executor = new Executor({ registry, policy: new ExecutionPolicy([], { strict: false }) }); const result = await executor.callAsync('test.approval_required'); expect(result['status']).toBe('executed'); }); @@ -530,7 +528,7 @@ describe('ApprovalAuditEvents', () => { it('does not emit audit log when gate is skipped', async () => { const registry = createTestRegistry(); - const executor = new Executor({ registry }); + const executor = new Executor({ registry, policy: new ExecutionPolicy([], { strict: false }) }); const infoSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); try { await executor.call('test.approval_required'); diff --git a/typescript/tests/test-approval-integration.test.ts b/typescript/tests/test-approval-integration.test.ts index 90bb5b19..8f4b987a 100644 --- a/typescript/tests/test-approval-integration.test.ts +++ b/typescript/tests/test-approval-integration.test.ts @@ -1,3 +1,4 @@ +import { ExecutionPolicy } from '../src/policy.js'; /** * Integration tests for the approval system through the full executor pipeline. */ @@ -327,7 +328,7 @@ describe('ApprovalExtensionManager', () => { describe('ApprovalImports', () => { it('all types importable from apcore package', async () => { - const apcore = await import('../src/index.js'); + const apcore = await import('../src/full.js'); expect(apcore.AlwaysDenyHandler).toBeDefined(); expect(apcore.AutoApproveHandler).toBeDefined(); expect(apcore.CallbackApprovalHandler).toBeDefined(); @@ -397,7 +398,7 @@ describe('_approval_token versus additionalProperties: false', () => { it('is stripped when approval is required but no handler is configured', async () => { const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); const seen: Record[] = []; - const executor = new Executor({ registry: await buildRegistry(true, seen) }); + const executor = new Executor({ registry: await buildRegistry(true, seen), policy: new ExecutionPolicy([], { strict: false }) }); const result = await executor.call('probe.strict', { a: 'x', _approval_token: 'tok' }); warnSpy.mockRestore(); expect(result['ok']).toBe('x'); diff --git a/typescript/tests/test-assembly-extensions.test.ts b/typescript/tests/test-assembly-extensions.test.ts new file mode 100644 index 00000000..64c7d521 --- /dev/null +++ b/typescript/tests/test-assembly-extensions.test.ts @@ -0,0 +1,167 @@ +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, it, vi } from 'vitest'; + +import { APCore } from '../src/client.js'; +import { ACL as CoreACL, APCore as CoreAPCore, Registry as CoreRegistry } from '../src/core.js'; +import { ACL as FullACL, APCore as FullAPCore } from '../src/full.js'; +import { Config, createAclDiscoveryPlugin, loadAclFile } from '../src/config-entry.js'; +import { createDiscoveryRegistry, createFilesystemDiscoveryPlugin } from '../src/discovery.js'; +import { createNodeLifecyclePlugin } from '../src/lifecycle-node.js'; +import type { LifecycleOperation } from '../src/lifecycle.js'; +import { createEvent } from '../src/events/emitter.js'; +import { Registry } from '../src/registry/registry.js'; +import { createSysModulesPlugin } from '../src/sys-modules/entry.js'; +import { uuidV4 } from '../src/utils/uuid.js'; + +const moduleSource = `export default { + description: 'Return a sample greeting', + inputSchema: { type: 'object' }, + outputSchema: { type: 'object' }, + execute: () => ({ message: 'hello' }), +};`; + +describe('instance-scoped assembly extensions', () => { + it('discovers into one registry without enabling filesystem access in another', async () => { + const root = await mkdtemp(join(tmpdir(), 'apcore-explicit-discovery-')); + try { + await writeFile(join(root, 'greeter.js'), moduleSource); + const enabled = createDiscoveryRegistry({ extensionsDir: root }); + const memory = new Registry({ extensionsDir: root, filesystem: null }); + await expect(enabled.discover()).resolves.toBe(1); + await expect(memory.discover()).rejects.toThrow(/filesystem registry operations/i); + expect(enabled.has('greeter')).toBe(true); + expect(memory.has('greeter')).toBe(false); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it('uses the discovery plugin only for the client-owned registry', async () => { + const root = await mkdtemp(join(tmpdir(), 'apcore-discovery-plugin-')); + try { + await writeFile(join(root, 'greeter.js'), moduleSource); + const plugin = createFilesystemDiscoveryPlugin({ extensionsDir: root }); + const owned = new APCore({ plugins: [plugin] }); + await expect(owned.discover()).resolves.toBe(1); + const supplied = new Registry({ filesystem: null }); + const injected = new APCore({ registry: supplied, plugins: [plugin] }); + expect(injected.registry).toBe(supplied); + await expect(injected.discover()).rejects.toThrow(/filesystem registry operations/i); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it('loads ACL files explicitly and lets the client assemble only its own executor', async () => { + const root = await mkdtemp(join(tmpdir(), 'apcore-acl-plugin-')); + try { + const aclPath = join(root, 'global_acl.yaml'); + await writeFile(aclPath, 'default_effect: deny\nrules: []\n'); + const plugin = createAclDiscoveryPlugin(); + const config = new Config({ acl: { root } }); + const client = new APCore({ config, plugins: [plugin] }); + expect(client.executor.governanceState().aclConfigured).toBe(true); + expect(loadAclFile(aclPath).check('caller.sample', 'target.sample')).toBe(false); + const other = new APCore(); + const injected = new APCore({ executor: other.executor, config, plugins: [plugin] }); + expect(injected.executor).toBe(other.executor); + expect(injected.executor.governanceState().aclConfigured).toBe(false); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + it('rejects waiting on the same shutdown after an async callback suspends', async () => { + const lifecycle = createNodeLifecyclePlugin(); + const first = new APCore({ plugins: [lifecycle] }); + const second = new APCore({ plugins: [lifecycle] }); + expect(first.registry.lifecycleCallbacks).not.toBe(second.registry.lifecycleCallbacks); + let shutdown: LifecycleOperation; + let inside: unknown; + await first.register('letter.send', { + description: 'Return a sample result', + inputSchema: { type: 'object' }, + outputSchema: { type: 'object' }, + execute: () => ({}), + async onUnload(): Promise { + await Promise.resolve(); + inside = await shutdown.wait(100).catch(error => error); + }, + }); + shutdown = first.startShutdown(); + await expect(shutdown.wait(500)).resolves.toMatchObject({ status: 'completed' }); + expect(inside).toMatchObject({ message: 'A lifecycle callback cannot wait for its own operation' }); + }); + + it('resolves subscriber factories independently for each system-module installation', async () => { + const config = new Config({ + sys_modules: { + enabled: true, + events: { enabled: true, subscribers: [{ type: 'sample-subscriber' }] }, + }, + }); + const deliveries: string[] = []; + const runtime = (name: string) => new FullAPCore({ + config, + plugins: [createSysModulesPlugin({ + subscriberFactories: { + 'sample-subscriber': () => ({ + eventPattern: 'sample.notice', + onEvent: () => { deliveries.push(name); }, + }), + }, + })], + }); + const first = runtime('first'); + const second = runtime('second'); + const event = createEvent('sample.notice', null, 'info', {}); + first.events!.emit(event); + await first.events!.flush(); + expect(deliveries).toEqual(['first']); + second.events!.emit(event); + await second.events!.flush(); + expect(deliveries).toEqual(['first', 'second']); + await Promise.all([first.shutdown(), second.shutdown()]); + }); + + it('keeps an in-memory core isolated alongside the full profile', async () => { + const root = await mkdtemp(join(tmpdir(), 'apcore-runtime-profiles-')); + try { + await writeFile(join(root, 'greeter.js'), moduleSource); + const aclPath = join(root, 'global_acl.yaml'); + await writeFile(aclPath, 'default_effect: deny\nrules: []\n'); + const config = new Config({ extensions: { root }, acl: { root: aclPath } }); + const full = new FullAPCore({ config }); + const slim = new CoreAPCore(); + expect(slim.registry).toBeInstanceOf(CoreRegistry); + await expect(full.discover()).resolves.toBe(1); + expect(full.executor.governanceState().aclConfigured).toBe(true); + await expect(slim.discover()).rejects.toThrow(/filesystem registry operations/i); + expect(() => CoreACL.load(aclPath)).toThrow(/config subpath/i); + const fullAcl = FullACL.load(aclPath); + const explicitAcl = loadAclFile(aclPath); + expect(fullAcl).toBeInstanceOf(FullACL); + expect(fullAcl.check('sample.caller', 'sample.module')).toBe(false); + await writeFile(aclPath, 'default_effect: allow\nrules: []\n'); + fullAcl.reload(); + explicitAcl.reload(); + expect(fullAcl.check('sample.caller', 'sample.module')).toBe(true); + expect(explicitAcl.check('sample.caller', 'sample.module')).toBe(true); + expect(() => new CoreAPCore({ config })).toThrow(/ACL discovery plugin/i); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); + + it('generates an RFC 9562 UUID with Web Crypto entropy before randomUUID support', () => { + vi.stubGlobal('crypto', { + getRandomValues: (bytes: Uint8Array) => bytes.fill(0x56), + }); + try { + expect(uuidV4()).toBe('56565656-5656-4656-9656-565656565656'); + } finally { + vi.unstubAllGlobals(); + } + }); +}); diff --git a/typescript/tests/test-bindings-config-dir.test.ts b/typescript/tests/test-bindings-config-dir.test.ts index 02e5614f..bd8c983a 100644 --- a/typescript/tests/test-bindings-config-dir.test.ts +++ b/typescript/tests/test-bindings-config-dir.test.ts @@ -16,7 +16,7 @@ import { join } from 'node:path'; import { BindingLoader } from '../src/bindings.js'; import { Config } from '../src/config.js'; import { BindingFileInvalidError } from '../src/errors.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; let tmpDir: string; let originalCwd: string; diff --git a/typescript/tests/test-browser-compat.test.ts b/typescript/tests/test-browser-compat.test.ts index 163998f0..d073af4c 100644 --- a/typescript/tests/test-browser-compat.test.ts +++ b/typescript/tests/test-browser-compat.test.ts @@ -59,7 +59,7 @@ describe('module imports', () => { }); it('barrel index re-exports all lazy-loaded modules', async () => { - const mod = await import('../src/index.js'); + const mod = await import('../src/full.js'); expect(mod.ACL).toBeDefined(); expect(mod.BindingLoader).toBeDefined(); expect(mod.SchemaLoader).toBeDefined(); @@ -74,7 +74,7 @@ describe('module imports', () => { describe('ACL pure-logic (no filesystem)', () => { it('constructor and check() work without filesystem', async () => { - const { ACL } = await import('../src/acl.js'); + const { ACL } = await import('../src/full.js'); const acl = new ACL([ { callers: ['mod.a'], targets: ['mod.b'], effect: 'allow', description: 'test' }, { callers: ['*'], targets: ['*'], effect: 'deny', description: 'default' }, @@ -84,7 +84,7 @@ describe('ACL pure-logic (no filesystem)', () => { }); it('addRule() / removeRule() work without filesystem', async () => { - const { ACL } = await import('../src/acl.js'); + const { ACL } = await import('../src/full.js'); const acl = new ACL([], 'deny'); expect(acl.check('a', 'b')).toBe(false); @@ -231,11 +231,11 @@ describe('Registry pure-logic (no filesystem)', () => { // Verifies the Node-side build wires up node:fs / node:path correctly. describe('node: modules wired up in Node.js', () => { - it('ACL.load() uses lazy-loaded fs successfully', async () => { + it('the full Node ACL loads from disk', async () => { const { writeFileSync, mkdtempSync, rmSync } = await import('node:fs'); const { join } = await import('node:path'); const { tmpdir } = await import('node:os'); - const { ACL } = await import('../src/acl.js'); + const { ACL } = await import('../src/full.js'); const tmp = mkdtempSync(join(tmpdir(), 'acl-lazy-')); const yamlPath = join(tmp, 'acl.yaml'); diff --git a/typescript/tests/test-capture-point-redaction.test.ts b/typescript/tests/test-capture-point-redaction.test.ts index 96e7a00a..ac39199d 100644 --- a/typescript/tests/test-capture-point-redaction.test.ts +++ b/typescript/tests/test-capture-point-redaction.test.ts @@ -20,7 +20,7 @@ import { Type } from '@sinclair/typebox'; import { describe, it, expect } from 'vitest'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { Middleware } from '../src/middleware/base.js'; diff --git a/typescript/tests/test-client-registry-wiring.test.ts b/typescript/tests/test-client-registry-wiring.test.ts index 74f99d8a..22dc7524 100644 --- a/typescript/tests/test-client-registry-wiring.test.ts +++ b/typescript/tests/test-client-registry-wiring.test.ts @@ -1,3 +1,4 @@ +import { AutoApproveHandler } from '../src/approval.js'; /** * CLI-1 / CLI-3 — the client's Registry must be the executor's, and must be * built from the Config. @@ -20,9 +21,9 @@ import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { Type } from '@sinclair/typebox'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import { Executor } from '../src/executor.js'; const DUMMY = { @@ -62,7 +63,7 @@ describe('APCore adopts a supplied Executor’s Registry (CLI-1)', () => { it('client.disable() reaches the sys module when an executor was supplied', async () => { const registry = new Registry(); - const executor = new Executor({ registry }); + const executor = new Executor({ registry, approvalHandler: new AutoApproveHandler() }); const config = new Config({ sys_modules: { enabled: true, events: { enabled: true }, control: { enabled: true } }, }); diff --git a/typescript/tests/test-client.test.ts b/typescript/tests/test-client.test.ts index 0172a597..9ba3f268 100644 --- a/typescript/tests/test-client.test.ts +++ b/typescript/tests/test-client.test.ts @@ -9,7 +9,7 @@ import { describe, it, expect, vi } from 'vitest'; import { Type } from '@sinclair/typebox'; import { ACL } from '../src/acl.js'; import { AutoApproveHandler } from '../src/approval.js'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { FunctionModule } from '../src/decorator.js'; import { Executor } from '../src/executor.js'; @@ -17,7 +17,7 @@ import { ACLDeniedError, InvalidInputError, ModuleNotFoundError, SysModuleRegist import { EventEmitter, type ApCoreEvent } from '../src/events/emitter.js'; import { Middleware } from '../src/middleware/index.js'; import { ExecutionPolicy, PolicyRule } from '../src/policy.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import type { Context } from '../src/context.js'; import type { PipelineState, StepMiddleware } from '../src/pipeline.js'; @@ -765,7 +765,7 @@ describe('APCore.on() / off()', () => { describe('APCore.enable() / disable()', () => { it('updates the state used by the supplied executor when disabling a module', async () => { const config = new Config({ sys_modules: { enabled: true, events: { enabled: true } } }); - const executor = new Executor({ registry: new Registry(), config }); + const executor = new Executor({ registry: new Registry(), config, approvalHandler: new AutoApproveHandler() }); const client = new APCore({ config, executor }); registerAdd(client); @@ -785,6 +785,7 @@ describe('APCore.enable() / disable()', () => { sys_modules: { enabled: true, events: { enabled: true } }, }); const client = new APCore({ config }); + client.executor.setApprovalHandler(new AutoApproveHandler()); registerAdd(client); const disableResult = await client.disable('math.add', 'testing'); @@ -803,7 +804,7 @@ describe('APCore.enable() / disable()', () => { describe('APCore exports', () => { it('is exported from index', async () => { - const mod = await import('../src/index.js'); + const mod = await import('../src/full.js'); expect(mod.APCore).toBeDefined(); expect(typeof mod.APCore).toBe('function'); }); diff --git a/typescript/tests/test-config-project-root.test.ts b/typescript/tests/test-config-project-root.test.ts index 3e09780a..926c7a87 100644 --- a/typescript/tests/test-config-project-root.test.ts +++ b/typescript/tests/test-config-project-root.test.ts @@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import { Config, discoverConfigFile, userLevelConfigPaths } from '../src/config.js'; import { SchemaLoader } from '../src/schema/loader.js'; diff --git a/typescript/tests/test-control.test.ts b/typescript/tests/test-control.test.ts index a7ccd831..955820c7 100644 --- a/typescript/tests/test-control.test.ts +++ b/typescript/tests/test-control.test.ts @@ -1,3 +1,4 @@ +import { AutoApproveHandler } from '../src/approval.js'; import { describe, it, expect, vi, beforeEach } from 'vitest'; import { Type } from '@sinclair/typebox'; import { UpdateConfigModule, ReloadModule } from '../src/sys-modules/control.js'; @@ -40,7 +41,7 @@ describe('UpdateConfigModule store-XOR-path precedence', () => { const registry = new Registry(); await registry.registerInternal('system.control.update_config', new UpdateConfigModule(new Config({}), new EventEmitter())); let captured: unknown; - const executor = new Executor({ registry, middlewares: [new class extends Middleware { + const executor = new Executor({ registry, approvalHandler: new AutoApproveHandler(), middlewares: [new class extends Middleware { override before(_id: string, _input: Record, context: Context) { captured = context.redactedInputs?.['value']; return null; diff --git a/typescript/tests/test-deprecated-inert-keys.test.ts b/typescript/tests/test-deprecated-inert-keys.test.ts index af33b5da..4616ce0f 100644 --- a/typescript/tests/test-deprecated-inert-keys.test.ts +++ b/typescript/tests/test-deprecated-inert-keys.test.ts @@ -27,7 +27,7 @@ import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } fr import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { ACL } from '../src/acl.js'; +import { ACL } from '../src/full.js'; import { Config } from '../src/config.js'; /** diff --git a/typescript/tests/test-event-subscribers.test.ts b/typescript/tests/test-event-subscribers.test.ts index 1d449a55..35a3423e 100644 --- a/typescript/tests/test-event-subscribers.test.ts +++ b/typescript/tests/test-event-subscribers.test.ts @@ -10,7 +10,6 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { WebhookSubscriber, - A2ASubscriber, FileSubscriber, StdoutSubscriber, FilterSubscriber, @@ -194,161 +193,6 @@ describe('WebhookSubscriber HTTP retry contract (issue #69)', () => { }); // Regression lock for the 4xx-vs-5xx HTTP retry contract (apcore issue #69), -// A2A variant. Mirrors the WebhookSubscriber contract block above exactly: the -// A2ASubscriber must apply the same 5xx-retryable / 4xx-permanent distinction. -// -// Verified contract: -// * HTTP 4xx → permanent client error → NOT retried (fetch called once), -// no apcore.event.delivery_failed (DLQ) event. -// * HTTP 5xx → server error → retried to maxAttempts (fetch called N times), -// then a apcore.event.delivery_failed (DLQ) event is emitted -// with subscriber_type === "a2a". -describe('A2ASubscriber HTTP retry contract (issue #69)', () => { - const FAST_RETRY = { - maxAttempts: 3, - initialBackoffMs: 1, - maxBackoffMs: 10, - backoffMultiplier: 1, - }; - - beforeEach(() => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); - }); - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('HTTP 4xx (400) is permanent: fetch called exactly once, no DLQ event', async () => { - const fetchMock = vi.fn().mockResolvedValue({ status: 400 }); - vi.stubGlobal('fetch', fetchMock); - - const emitter = new EventEmitter(); - const dlqEvents: ApCoreEvent[] = []; - emitter.subscribe({ - eventPattern: 'apcore.event.delivery_failed', - onEvent: (e) => { dlqEvents.push(e); }, - }); - emitter.subscribe( - new A2ASubscriber('https://platform/x', undefined, { retry: FAST_RETRY }), - ); - - emitter.emit(createEvent('test.fourxx', null, 'info', { x: 1 })); - await emitter.flush(); - - // Core lock: a 4xx must NOT be retried. - expect(fetchMock).toHaveBeenCalledTimes(1); - // 4xx returns normally (warn, no throw) → delivery succeeds → no DLQ. - expect(dlqEvents).toHaveLength(0); - }); - - it('HTTP 5xx (503) is retryable: fetch called maxAttempts times, then DLQ event', async () => { - const fetchMock = vi.fn().mockResolvedValue({ status: 503 }); - vi.stubGlobal('fetch', fetchMock); - - const emitter = new EventEmitter(); - const dlqEvents: ApCoreEvent[] = []; - emitter.subscribe({ - eventPattern: 'apcore.event.delivery_failed', - onEvent: (e) => { dlqEvents.push(e); }, - }); - emitter.subscribe( - new A2ASubscriber('https://platform/x', undefined, { retry: FAST_RETRY }), - ); - - emitter.emit(createEvent('test.fivexx', null, 'info', { x: 1 })); - await emitter.flush(); - - // Core lock: a 5xx is retried to exhaustion (3 attempts). - expect(fetchMock).toHaveBeenCalledTimes(3); - // Retry exhaustion routes through the DLQ. - expect(dlqEvents).toHaveLength(1); - expect(dlqEvents[0].data['subscriber_type']).toBe('a2a'); - expect(dlqEvents[0].data['attempt_count']).toBe(3); - }); -}); - -describe('A2ASubscriber', () => { - beforeEach(() => { - vi.spyOn(console, 'warn').mockImplementation(() => {}); - }); - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('POSTs with skillId and Bearer auth when auth is a string', async () => { - const fetchMock = vi.fn().mockResolvedValue({ status: 200 }); - vi.stubGlobal('fetch', fetchMock); - - const sub = new A2ASubscriber('https://platform/x', 'tok-1', 5000); - await sub.onEvent(makeEvent()); - const headers = (fetchMock.mock.calls[0][1] as { headers: Record }).headers; - expect(headers['Authorization']).toBe('Bearer tok-1'); - const body = JSON.parse((fetchMock.mock.calls[0][1] as { body: string }).body); - expect(body.skillId).toBe('apevo.event_receiver'); - }); - - it('merges dict auth as header overrides and skips non-string values', async () => { - const fetchMock = vi.fn().mockResolvedValue({ status: 200 }); - vi.stubGlobal('fetch', fetchMock); - - const sub = new A2ASubscriber('https://platform/x', { 'X-API-Key': 'k', 'X-Skip': 42 as unknown as string }, 5000); - await sub.onEvent(makeEvent()); - const headers = (fetchMock.mock.calls[0][1] as { headers: Record }).headers; - expect(headers['X-API-Key']).toBe('k'); - expect(headers['X-Skip']).toBeUndefined(); - }); - - it('omits Authorization when no auth is given', async () => { - const fetchMock = vi.fn().mockResolvedValue({ status: 200 }); - vi.stubGlobal('fetch', fetchMock); - - const sub = new A2ASubscriber('https://platform/x'); - await sub.onEvent(makeEvent()); - const headers = (fetchMock.mock.calls[0][1] as { headers: Record }).headers; - expect(headers['Authorization']).toBeUndefined(); - }); - - it('rethrows on 5xx so EventEmitter retry+DLQ policy applies', async () => { - const fetchMock = vi.fn().mockResolvedValue({ status: 500 }); - vi.stubGlobal('fetch', fetchMock); - - const sub = new A2ASubscriber('https://platform/x'); - await expect(sub.onEvent(makeEvent())).rejects.toThrow(/status 500/); - }); - - it('warns but does not throw on 4xx (non-retryable client error)', async () => { - const fetchMock = vi.fn().mockResolvedValue({ status: 404 }); - vi.stubGlobal('fetch', fetchMock); - - const sub = new A2ASubscriber('https://platform/x'); - await sub.onEvent(makeEvent()); - expect(fetchMock).toHaveBeenCalledTimes(1); - }); - - it('rethrows on fetch rejection so EventEmitter retry+DLQ policy applies', async () => { - const fetchMock = vi.fn().mockRejectedValue(new Error('boom')); - vi.stubGlobal('fetch', fetchMock); - - const sub = new A2ASubscriber('https://platform/x'); - await expect(sub.onEvent(makeEvent())).rejects.toThrow('boom'); - }); - - it('exposes the spec-default retry config (3 attempts, 100ms initial)', () => { - const sub = new A2ASubscriber('https://platform/x'); - expect(sub.retry.maxAttempts).toBe(3); - expect(sub.retry.initialBackoffMs).toBe(100); - expect(sub.retry.backoffMultiplier).toBe(2); - expect(sub.retry.maxBackoffMs).toBe(30_000); - }); - - it('accepts a custom retry config via the opts argument', () => { - const sub = new A2ASubscriber('https://platform/x', undefined, { - retry: { maxAttempts: 5 }, - }); - expect(sub.retry.maxAttempts).toBe(5); - }); -}); - describe('FileSubscriber', () => { let tmpDir: string; let filePath: string; diff --git a/typescript/tests/test-executor-stream-post-validation-event.test.ts b/typescript/tests/test-executor-stream-post-validation-event.test.ts index 6a552014..37a69968 100644 --- a/typescript/tests/test-executor-stream-post-validation-event.test.ts +++ b/typescript/tests/test-executor-stream-post-validation-event.test.ts @@ -10,7 +10,7 @@ import { join } from 'node:path'; import { describe, it, expect, vi } from 'vitest'; import { Type } from '@sinclair/typebox'; import { CancelToken, ExecutionCancelledError } from '../src/cancel.js'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { Context } from '../src/context.js'; import { ModuleError, ModuleExecuteError } from '../src/errors.js'; diff --git a/typescript/tests/test-gate-provider-binding.test.ts b/typescript/tests/test-gate-provider-binding.test.ts index 80da43a3..b4125153 100644 --- a/typescript/tests/test-gate-provider-binding.test.ts +++ b/typescript/tests/test-gate-provider-binding.test.ts @@ -16,7 +16,7 @@ import { Executor, Registry, buildStandardStrategy, -} from '../src/index.js'; +} from '../src/full.js'; import { MiddlewareManager } from '../src/middleware/manager.js'; import { ModuleError } from '../src/errors.js'; diff --git a/typescript/tests/test-governance-state.test.ts b/typescript/tests/test-governance-state.test.ts index 42a55c8c..b62b7c5f 100644 --- a/typescript/tests/test-governance-state.test.ts +++ b/typescript/tests/test-governance-state.test.ts @@ -7,7 +7,7 @@ */ import { describe, expect, it } from 'vitest'; -import { ACL, APCore, ExecutionPolicy, Executor } from '../src/index.js'; +import { ACL, APCore, ExecutionPolicy, Executor } from '../src/full.js'; import { Config } from '../src/config.js'; import { ExecutionStrategy } from '../src/pipeline.js'; import type { Step, StepResult, PipelineContext } from '../src/pipeline.js'; @@ -53,7 +53,10 @@ describe('governanceState — registration observations', () => { }); it('control modules with no gates is the condition the flag exists for', () => { - const state = client(SYS_ON).executor.governanceState(); + const c = client(SYS_ON); + const strategy = new ExecutionStrategy('explicitly-gateless', []); + const state = new Executor({ registry: c.registry, strategy }).governanceState(); + expect(state.builtinApprovalGateWired).toBe(false); expect(state.controlModulesRegistered).toBe(true); expect(state.unprotectedControlSurface).toBe(true); }); diff --git a/typescript/tests/test-issue123-edge-cases.test.ts b/typescript/tests/test-issue123-edge-cases.test.ts index 7d41c9fa..bea389a7 100644 --- a/typescript/tests/test-issue123-edge-cases.test.ts +++ b/typescript/tests/test-issue123-edge-cases.test.ts @@ -1,17 +1,17 @@ /** Issue #123 regression guards beyond the shared fixture cases. */ -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { Type } from '@sinclair/typebox'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { Context } from '../src/context.js'; import { Executor } from '../src/executor.js'; import { CancelToken, ExecutionCancelledError } from '../src/cancel.js'; -import { Registry } from '../src/registry/registry.js'; +import { Registry } from '../src/full.js'; import { createEvent, type ApCoreEvent } from '../src/events/emitter.js'; -import { registerSubscriberType, resetSubscriberRegistry } from '../src/sys-modules/registration.js'; +import { createSysModulesPlugin } from '../src/sys-modules/entry.js'; import { SchemaValidator } from '../src/schema/validator.js'; import yaml from 'js-yaml'; import { ExecutionStrategy, PipelineEngine, type PipelineContext, type Step } from '../src/pipeline.js'; @@ -55,7 +55,7 @@ describe('D-151 conformance declaration', () => { const project = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }; expect(declaration.implementation).toMatchObject({ name: 'apcore-typescript', version: project.version, spec_version: '1.65.0' }); expect(declaration.conformance.level).toBe(0); - expect(declaration.conformance.fixture_results).toMatchObject({ fixtures: 9, cases: 79, passed: 79, failed: 0, skipped: 0 }); + expect(declaration.conformance.fixture_results).toMatchObject({ fixtures: 8, cases: 74, passed: 74, failed: 0, skipped: 0 }); expect(declaration.conformance.known_deviations).toContainEqual(expect.objectContaining({ feature: 'Full fixture verification', severity: 'major' })); }); }); @@ -164,14 +164,28 @@ describe('D-133 timeout owns an abort-listener race', () => { }); describe('configured subscriber circuit breaker standard bootstrap', () => { - afterEach(() => resetSubscriberRegistry()); it('honors circuit_breaker thresholds and suppresses delivery after opening', async () => { let attempts = 0; - registerSubscriberType('issue123-failing', () => ({ + const failingSubscriber = () => ({ subscriberId: 'fixture-failing-subscriber', subscriberType: 'fixture', eventPattern: 'fixture.delivery', onEvent() { attempts += 1; throw new Error('Fixture delivery failure'); }, - })); - const client = new APCore({ config: new Config({ sys_modules: { enabled: true, events: { enabled: true, subscribers: [{ type: 'issue123-failing', circuit_breaker: { timeout_ms: 50, open_threshold: 2, recovery_window_ms: 60000 } }] } } }) }); + }); + const config = new Config({ + sys_modules: { + enabled: true, + events: { + enabled: true, + subscribers: [{ + type: 'issue123-failing', + circuit_breaker: { timeout_ms: 50, open_threshold: 2, recovery_window_ms: 60000 }, + }], + }, + }, + }); + const client = new APCore({ + config, + plugins: [createSysModulesPlugin({ subscriberFactories: { 'issue123-failing': failingSubscriber } })], + }); const observed: ApCoreEvent[] = []; client.events!.subscribe({ eventPattern: 'apcore.subscriber.circuit_opened', onEvent(event) { observed.push(event); } }); for (let index = 0; index < 3; index += 1) { diff --git a/typescript/tests/test-module-schema-inference.test.ts b/typescript/tests/test-module-schema-inference.test.ts index a972d8ed..ab8f3a78 100644 --- a/typescript/tests/test-module-schema-inference.test.ts +++ b/typescript/tests/test-module-schema-inference.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import ts from 'typescript'; import { describe, expect, it } from 'vitest'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { inferModuleSchemas } from '../src/compiler.js'; import { module } from '../src/decorator.js'; diff --git a/typescript/tests/test-package-integrity.test.ts b/typescript/tests/test-package-integrity.test.ts index fd734e2a..cd91c0e7 100644 --- a/typescript/tests/test-package-integrity.test.ts +++ b/typescript/tests/test-package-integrity.test.ts @@ -54,26 +54,50 @@ describe('dist entry points exist', () => { expect(existsSync(typesPath), `${pkg.types} should exist`).toBe(true); }); - it('exports "." node entry exists', () => { - const nodeEntry = pkg.exports['.'].node; - expect(existsSync(resolve(ROOT, nodeEntry)), `${nodeEntry} should exist`).toBe(true); - }); - - it('exports "." browser entry exists', () => { - const browserEntry = pkg.exports['.'].browser; - expect(existsSync(resolve(ROOT, browserEntry)), `${browserEntry} should exist`).toBe(true); - }); + it('exports the same portable root for Node and browser', async () => { + const rootEntry = pkg.exports['.']; + expect(pkg.sideEffects).toBe(false); + expect(rootEntry.default).toBe(pkg.main); + expect(rootEntry.types).toBe(pkg.types); + expect(pkg.browser).toBe(rootEntry.default); + const root = await import(resolve(ROOT, rootEntry.default)); + const core = await import(resolve(ROOT, pkg.exports['./core'].default)); + expect(Object.keys(root)).toEqual(Object.keys(core)); + expect(root.APCore).toBe(core.APCore); + expect(root.Registry).toBe(core.Registry); + expect(root.ACL).toBe(core.ACL); + }, IMPORT_TIMEOUT_MS); - it('exports "." default entry exists', () => { - const defaultEntry = pkg.exports['.'].default; - expect(existsSync(resolve(ROOT, defaultEntry)), `${defaultEntry} should exist`).toBe(true); - }); + it('ships declarations and runtime targets for the explicit profiles', async () => { + const coreEntry = pkg.exports['./core']; + const fullEntry = pkg.exports['./full']; + for (const [subpath, condition] of [ + ['./core', 'default'], ['./full', 'node'], ['./config', 'node'], + ['./discovery', 'node'], ['./sys-modules', 'node'], ['./events', 'node'], + ]) { + const entry = pkg.exports[subpath]; + expect(existsSync(resolve(ROOT, entry.types)), subpath).toBe(true); + expect(existsSync(resolve(ROOT, entry[condition])), subpath).toBe(true); + } + const core = await import(resolve(ROOT, coreEntry.default)); + const full = await import(resolve(ROOT, fullEntry.node)); + expect(core.Context).toBe(full.Context); + expect(core.Executor).toBe(full.Executor); + expect(core).not.toHaveProperty('Config'); + expect(full.Config).toBeTypeOf('function'); + expect(full).not.toHaveProperty('PrometheusExporter'); + expect(full).not.toHaveProperty('A2ASubscriber'); + expect(full).not.toHaveProperty('registerSubscriberType'); + }, IMPORT_TIMEOUT_MS); - it('exports "." types entries exist for both conditions', () => { - const types = pkg.exports['.'].types; - expect(existsSync(resolve(ROOT, types.browser)), `${types.browser} should exist`).toBe(true); - expect(existsSync(resolve(ROOT, types.default)), `${types.default} should exist`).toBe(true); - }); + it('exports the portable observability declarations and runtime', async () => { + const entry = pkg.exports['./observability']; + expect(existsSync(resolve(ROOT, entry.types))).toBe(true); + const observability = await import(resolve(ROOT, entry.default)); + expect(observability.renderPrometheusMetrics({ exportPrometheus: () => 'sample 1\n' })) + .toBe('sample 1\n'); + expect(observability).not.toHaveProperty('PrometheusExporter'); + }, IMPORT_TIMEOUT_MS); it('top-level "browser" field points at the browser build', () => { expect(existsSync(resolve(ROOT, pkg.browser)), `${pkg.browser} should exist`).toBe(true); @@ -93,18 +117,18 @@ describe('dist exports are loadable', () => { expect(mod.Registry).toBeDefined(); expect(mod.Executor).toBeDefined(); expect(mod.Context).toBeDefined(); - expect(mod.Config).toBeDefined(); + expect(mod).not.toHaveProperty('Config'); expect(mod.ACL).toBeDefined(); expect(mod.CancelToken).toBeDefined(); expect(mod.MiddlewareManager).toBeDefined(); - expect(mod.ExtensionManager).toBeDefined(); - expect(mod.AsyncTaskManager).toBeDefined(); - expect(mod.BindingLoader).toBeDefined(); - expect(mod.SchemaLoader).toBeDefined(); + expect(mod).not.toHaveProperty('ExtensionManager'); + expect(mod).not.toHaveProperty('AsyncTaskManager'); + expect(mod).not.toHaveProperty('BindingLoader'); + expect(mod).not.toHaveProperty('SchemaLoader'); expect(mod.SchemaValidator).toBeDefined(); - expect(mod.TracingMiddleware).toBeDefined(); - expect(mod.MetricsCollector).toBeDefined(); - expect(mod.ContextLogger).toBeDefined(); + expect(mod).not.toHaveProperty('TracingMiddleware'); + expect(mod).not.toHaveProperty('MetricsCollector'); + expect(mod).not.toHaveProperty('ContextLogger'); expect(mod.TraceContext).toBeDefined(); // Error classes expect(mod.ModuleError).toBeDefined(); diff --git a/typescript/tests/test-pipeline-section-is-applied.test.ts b/typescript/tests/test-pipeline-section-is-applied.test.ts index a7268580..8d8ef507 100644 --- a/typescript/tests/test-pipeline-section-is-applied.test.ts +++ b/typescript/tests/test-pipeline-section-is-applied.test.ts @@ -19,7 +19,7 @@ import { describe, it, expect, vi } from 'vitest'; import { ACL } from '../src/acl.js'; import { AlwaysDenyHandler, AutoApproveHandler } from '../src/approval.js'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { Executor } from '../src/executor.js'; import { Registry } from '../src/registry/registry.js'; diff --git a/typescript/tests/test-registration.test.ts b/typescript/tests/test-registration.test.ts index 2c5c269d..b31d1ef7 100644 --- a/typescript/tests/test-registration.test.ts +++ b/typescript/tests/test-registration.test.ts @@ -1,4 +1,5 @@ -import { describe, it, expect, afterEach, afterAll } from 'vitest'; +import { APCore } from '../src/full.js'; +import { describe, it, expect, afterAll, vi } from 'vitest'; import { writeFileSync, mkdtempSync, rmSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -8,9 +9,7 @@ import { Registry } from '../src/registry/registry.js'; import { Executor } from '../src/executor.js'; import { registerSysModules, - registerSubscriberType, - unregisterSubscriberType, - resetSubscriberRegistry, + createSubscriberFromConfig, } from '../src/sys-modules/registration.js'; import { ToggleState } from '../src/sys-modules/toggle.js'; @@ -98,45 +97,65 @@ describe('registerSysModules', () => { expect(result['summary']).toBeDefined(); expect((result['summary'] as Record)['total_modules']).toBeGreaterThan(0); }); -}); - -describe('subscriber registry', () => { - afterEach(() => { - resetSubscriberRegistry(); + it.each([undefined, '2.3.4'])('reports configured project version %s in health summary', async (version) => { + const project = { name: 'sample', ...(version === undefined ? {} : { version }) }; + const client = new APCore({ + config: new Config({ project, sys_modules: { enabled: true } }), + failOnError: true, + }); + expect((await client.call('system.health.summary', {}))['project']).toEqual(project); }); - it('registers and uses a subscriber type', () => { - const factory = (cfg: Record) => ({ - onEvent: () => { void cfg; }, + it('honors usage retention and reports hourly buckets from normal calls', async () => { + const config = new Config({ + sys_modules: { enabled: true, usage: { retention_hours: 1, bucketing_strategy: 'hourly' } }, }); - registerSubscriberType('custom', factory); - // No error means registration succeeded + const client = new APCore({ config, failOnError: true }); + await client.register('sample.item', { + description: 'Return a sample', + inputSchema: Type.Object({}), + outputSchema: Type.Object({}), + execute: () => ({}), + }); + vi.useFakeTimers({ toFake: ['Date'] }); + try { + vi.setSystemTime(new Date('2026-01-12T10:20:00Z')); + await client.call('sample.item', {}); + vi.setSystemTime(new Date('2026-01-12T12:20:00Z')); + await client.call('sample.item', {}); + const detail = await client.call('system.usage.module', { module_id: 'sample.item' }); + expect(detail['call_count']).toBe(1); + expect((detail['hourly_distribution'] as Record[]).filter((hour) => hour['call_count'])) + .toEqual([{ hour: '2026-01-12T12', call_count: 1, error_count: 0 }]); + } finally { + vi.useRealTimers(); + } }); - it('unregisters a subscriber type', () => { - registerSubscriberType('temp', () => ({ onEvent: () => {} })); - unregisterSubscriberType('temp'); - expect(() => unregisterSubscriberType('temp')).toThrow('not registered'); + it.each([ + { key: 'bucketing_strategy', value: 'daily' }, + { key: 'retention_hours', value: 0 }, + ])('rejects invalid $key before registering system modules', ({ key, value }) => { + const registry = new Registry(); + const config = new Config({ sys_modules: { enabled: true, usage: { [key]: value } } }); + expect(() => new APCore({ registry, config, failOnError: true })).toThrow('sys_modules.usage.' + key); + expect(registry.list()).toEqual([]); }); +}); - it('throws when unregistering unknown type', () => { - expect(() => unregisterSubscriberType('unknown')).toThrow('not registered'); - }); +describe('configured subscriber factories', () => { + it('instantiates custom subscriber types only when provided to this call', () => { + const config = { type: 'custom' }; + const subscriber = { onEvent() {} }; - it('resets custom types but preserves built-in types', () => { - registerSubscriberType('custom1', () => ({ onEvent: () => {} })); - registerSubscriberType('custom2', () => ({ onEvent: () => {} })); - resetSubscriberRegistry(); - expect(() => unregisterSubscriberType('custom1')).toThrow('not registered'); - // Built-in types should survive reset - unregisterSubscriberType('webhook'); - unregisterSubscriberType('a2a'); + expect(createSubscriberFromConfig(config, { custom: () => subscriber })).toBe(subscriber); + expect(() => createSubscriberFromConfig(config)).toThrow("Unknown subscriber type 'custom'"); }); - it('has built-in webhook and a2a types', () => { - // Should not throw — they are pre-registered - unregisterSubscriberType('webhook'); - unregisterSubscriberType('a2a'); + it('has built-in webhook and requires a factory for a2a', () => { + const webhook = createSubscriberFromConfig({ type: 'webhook', url: 'https://example.com' }); + expect(webhook.subscriberType).toBe('webhook'); + expect(() => createSubscriberFromConfig({ type: 'a2a' })).toThrow("Unknown subscriber type 'a2a'"); }); }); diff --git a/typescript/tests/test-stream-completion.test.ts b/typescript/tests/test-stream-completion.test.ts index 786dd1ec..61e68b2f 100644 --- a/typescript/tests/test-stream-completion.test.ts +++ b/typescript/tests/test-stream-completion.test.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { Type } from '@sinclair/typebox'; import { describe, expect, it, vi } from 'vitest'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { CancelToken, ExecutionCancelledError } from '../src/cancel.js'; import { Config } from '../src/config.js'; import { Context } from '../src/context.js'; diff --git a/typescript/tests/test-subscriber-retry-config.test.ts b/typescript/tests/test-subscriber-retry-config.test.ts index 26541455..df04c20f 100644 --- a/typescript/tests/test-subscriber-retry-config.test.ts +++ b/typescript/tests/test-subscriber-retry-config.test.ts @@ -11,17 +11,14 @@ * (maxAttempts=3, initialBackoffMs=100, maxBackoffMs=30000, backoffMultiplier=2.0) * — otherwise the test would pass whether or not the config was ever read. */ -import { afterEach, describe, expect, it } from 'vitest'; +import { describe, expect, it } from 'vitest'; import * as os from 'node:os'; import * as path from 'node:path'; import { createSubscriberFromConfig, - registerSubscriberType, - resetSubscriberRegistry, } from '../src/sys-modules/registration.js'; import { WebhookSubscriber, - A2ASubscriber, FileSubscriber, StdoutSubscriber, FilterSubscriber, @@ -63,10 +60,6 @@ function makeEvent(): ApCoreEvent { }; } -afterEach(() => { - resetSubscriberRegistry(); -}); - describe('nested retry: block — one case per built-in subscriber type', () => { it('webhook reads the nested retry block', () => { const sub = createSubscriberFromConfig({ @@ -78,15 +71,6 @@ describe('nested retry: block — one case per built-in subscriber type', () => expectNonDefaultPolicy(sub.retry); }); - it('a2a reads the nested retry block', () => { - const sub = createSubscriberFromConfig({ - type: 'a2a', - platform_url: 'https://platform.example.com', - retry: NON_DEFAULT_RETRY, - }); - expect(sub).toBeInstanceOf(A2ASubscriber); - expectNonDefaultPolicy(sub.retry); - }); it('file reads the nested retry block', () => { const sub = createSubscriberFromConfig({ @@ -234,7 +218,7 @@ describe('the declared policy actually governs delivery', () => { constructor(readonly retry?: RetryConfig) {} async onEvent(_event: ApCoreEvent): Promise {} } - registerSubscriberType('custom_sink', (config) => { + const factory = (config: Record) => { const raw = config['retry'] as Record; return new CustomSink({ maxAttempts: raw['max_attempts'], @@ -242,8 +226,11 @@ describe('the declared policy actually governs delivery', () => { maxBackoffMs: raw['max_backoff_ms'], backoffMultiplier: raw['backoff_multiplier'], }); - }); - const sub = createSubscriberFromConfig({ type: 'custom_sink', retry: NON_DEFAULT_RETRY }); + }; + const sub = createSubscriberFromConfig( + { type: 'custom_sink', retry: NON_DEFAULT_RETRY }, + { custom_sink: factory }, + ); expectNonDefaultPolicy(sub.retry); }); }); diff --git a/typescript/tests/test-sync-policy-registry-fixes.test.ts b/typescript/tests/test-sync-policy-registry-fixes.test.ts index 8f69d920..69340579 100644 --- a/typescript/tests/test-sync-policy-registry-fixes.test.ts +++ b/typescript/tests/test-sync-policy-registry-fixes.test.ts @@ -36,10 +36,10 @@ describe('W3: ExecutionPolicy.fromObject rejects non-boolean governance switches expect(policy.strict).toBe(false); }); - it('defaults both switches to false when absent', () => { + it('defaults both switches to true when absent', () => { const policy = ExecutionPolicy.fromObject({}); - expect(policy.gateDestructive).toBe(false); - expect(policy.strict).toBe(false); + expect(policy.gateDestructive).toBe(true); + expect(policy.strict).toBe(true); }); it('rejects an empty array for gate_destructive (JS truthiness would say true)', () => { @@ -60,8 +60,8 @@ describe('W3: ExecutionPolicy.fromObject rejects non-boolean governance switches it('accepts an explicit null as "unset"', () => { const policy = ExecutionPolicy.fromObject({ gate_destructive: null, strict: null }); - expect(policy.gateDestructive).toBe(false); - expect(policy.strict).toBe(false); + expect(policy.gateDestructive).toBe(true); + expect(policy.strict).toBe(true); }); }); diff --git a/typescript/tests/test-tracing-from-config.test.ts b/typescript/tests/test-tracing-from-config.test.ts index fd726551..58fa9a0c 100644 --- a/typescript/tests/test-tracing-from-config.test.ts +++ b/typescript/tests/test-tracing-from-config.test.ts @@ -17,7 +17,7 @@ import { describe, it, expect, vi } from 'vitest'; import { Type } from '@sinclair/typebox'; -import { APCore } from '../src/client.js'; +import { APCore } from '../src/full.js'; import { Config } from '../src/config.js'; import { ConfigError } from '../src/errors.js'; import { DEFAULTS } from '../src/config-defaults.js'; diff --git a/typescript/tsconfig.examples.json b/typescript/tsconfig.examples.json index fc97d890..df1ac009 100644 --- a/typescript/tsconfig.examples.json +++ b/typescript/tsconfig.examples.json @@ -8,7 +8,11 @@ "baseUrl": ".", "paths": { "apcore-js": ["./src/index.ts"], - "apcore-js/context-keys": ["./src/context-keys.ts"] + "apcore-js/context-keys": ["./src/context-keys.ts"], + "apcore-js/config": ["./src/config-entry.ts"], + "apcore-js/events": ["./src/events/entry.ts"], + "apcore-js/full": ["./src/full.ts"], + "apcore-js/observability": ["./src/observability/portable.ts"] } }, "include": ["examples/**/*.ts"], diff --git a/typescript/vitest.config.ts b/typescript/vitest.config.ts index fcb46c8c..826c2c70 100644 --- a/typescript/vitest.config.ts +++ b/typescript/vitest.config.ts @@ -10,12 +10,6 @@ export default defineConfig({ // against the implicit default, close enough that a loaded CI runner could // trip it and report a transform cost as a test failure. testTimeout: 20000, - // Side-effect setup: wire Node-only file readers onto the - // browser-safe runtime modules (ACL.load, registerSysModules, the - // sys-modules overrides loader). Tests that import individual source - // files directly (e.g. `from '../src/acl.js'`) - // bypass the package's Node entry, so we install them here instead. - setupFiles: ['./tests/setup-node-installers.ts'], coverage: { provider: 'v8', include: ['src/**/*.ts'], From 8b9006a421adfa295f74a5d6035caa7f03898436 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:31:40 +0800 Subject: [PATCH 04/10] refactor(rust): isolate ACL files and registry watchers Signed-off-by: tercel --- rust/src/acl.rs | 492 +------------------------ rust/src/acl/file.rs | 494 ++++++++++++++++++++++++++ rust/src/executor.rs | 6 +- rust/src/registry/filesystem_watch.rs | 338 ++++++++++++++++++ rust/src/registry/registry.rs | 339 +----------------- rust/tests/core_profile.rs | 2 +- 6 files changed, 844 insertions(+), 827 deletions(-) create mode 100644 rust/src/acl/file.rs create mode 100644 rust/src/registry/filesystem_watch.rs diff --git a/rust/src/acl.rs b/rust/src/acl.rs index 87d5c03b..f4cb480f 100644 --- a/rust/src/acl.rs +++ b/rust/src/acl.rs @@ -3,12 +3,8 @@ use chrono::Utc; use serde::{Deserialize, Serialize}; -#[cfg(feature = "config")] -use serde_yaml_ng as serde_yaml; use std::collections::{HashMap, HashSet}; use std::future::Future; -#[cfg(feature = "config")] -use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Once}; @@ -21,19 +17,8 @@ use crate::context::Context; use crate::errors::{ErrorCode, ModuleError}; use crate::utils::match_pattern; -/// The complete set of keys an ACL rule may carry (PROTOCOL_SPEC §6.1). -/// -/// Closed on purpose: a key nothing evaluates is otherwise dropped in silence, -/// which widens an `allow` rule with no warning (#107). #[cfg(feature = "config")] -const RULE_KEYS: &[&str] = &[ - "callers", - "targets", - "effect", - "approval", - "description", - "conditions", -]; +mod file; /// The complete set of values a rule's `effect` may carry (PROTOCOL_SPEC §6.1). /// @@ -46,14 +31,6 @@ const RULE_KEYS: &[&str] = &[ /// field up and is validated against this set too. const EFFECTS: &[&str] = &["allow", "deny"]; -/// Reserved in earlier revisions of §6.1 and evaluated by no implementation. -/// -/// Rejected like any other unknown key, but named as reserved in the message: -/// an operator who wrote `actions: ["describe"]` meant to restrict the rule and -/// is better served by "not implemented" than by "unknown key". -#[cfg(feature = "config")] -const RESERVED_RULE_KEYS: &[&str] = &["id", "actions", "priority"]; - /// The caller identity an absent `caller_id` resolves to (PROTOCOL_SPEC §6.5). /// /// A call that carries no caller — an inbound external request, or an @@ -71,52 +48,6 @@ const RESERVED_RULE_KEYS: &[&str] = &["id", "actions", "priority"]; /// apcore#37's follow-up: guidance that named an identity no rule could match. pub const EXTERNAL_CALLER: &str = "@external"; -/// Reject any rule key outside [`RULE_KEYS`]. -#[cfg(feature = "config")] -fn reject_unknown_rule_keys( - index: usize, - path: &str, - obj: &serde_json::Map, -) -> Result<(), ModuleError> { - let mut unknown: Vec<&str> = obj - .keys() - .map(String::as_str) - .filter(|k| !RULE_KEYS.contains(k)) - .collect(); - if unknown.is_empty() { - return Ok(()); - } - unknown.sort_unstable(); - let (reserved, other): (Vec<&str>, Vec<&str>) = unknown - .into_iter() - .partition(|k| RESERVED_RULE_KEYS.contains(k)); - let quote = |ks: &[&str]| { - ks.iter() - .map(|k| format!("'{k}'")) - .collect::>() - .join(", ") - }; - let mut parts: Vec = Vec::new(); - if !reserved.is_empty() { - parts.push(format!( - "{} reserved for a future specification version and evaluated by no implementation", - quote(&reserved) - )); - } - if !other.is_empty() { - parts.push(format!("{} unrecognised", quote(&other))); - } - Err(ModuleError::new( - ErrorCode::ACLRuleError, - format!( - "ACL rule {index} in '{path}' carries {}. The rule key set is closed ({}); \ - a key nothing evaluates would be dropped silently and leave the rule wider than written.", - parts.join("; "), - RULE_KEYS.join(", ") - ), - )) -} - /// The tokens a `callers` / `targets` array reserves for its compound /// operators (PROTOCOL_SPEC §6.2.1). /// @@ -936,96 +867,6 @@ pub(crate) fn warn_audit_block_overridden( ); } -/// Validate an ACL file's `audit:` block (§6.3.2 requirement 8). -/// -/// Returns `None` only when the document declares no `audit` key at all. -/// **Presence, not truthiness**: `audit:` with nothing under it parses to null, -/// and the operator still wrote the block — a declaration with every setting at -/// its default, not an absence. -/// -/// Validates the SUBTREE only: types and unknown keys inside the block. Every -/// other unrecognised root key in an ACL file keeps being ignored. -#[cfg(feature = "config")] -pub(crate) fn parse_audit_block( - raw: &serde_json::Value, - path: &str, -) -> Result, ModuleError> { - let Some(value) = raw.get("audit") else { - return Ok(None); - }; - if value.is_null() { - return Ok(Some(AuditConfig::default())); - } - let Some(block) = value.as_object() else { - return Err(ModuleError::new( - ErrorCode::ConfigInvalid, - format!("{path}: 'audit' must be a mapping (PROTOCOL_SPEC §6.3.2)"), - )); - }; - - let mut unknown: Vec<&str> = block - .keys() - .map(String::as_str) - .filter(|k| !AUDIT_FIELDS.contains(k)) - .collect(); - unknown.sort_unstable(); - if !unknown.is_empty() { - return Err(ModuleError::new( - ErrorCode::ConfigInvalid, - format!( - "{path}: unknown key(s) in the 'audit' block: {}. The block accepts exactly \ - {} ($defs/AuditConfig in schemas/acl-config.schema.json).", - unknown.join(", "), - AUDIT_FIELDS.join(", ") - ), - )); - } - - let mut config = AuditConfig::default(); - for key in ["enabled", "include_denied"] { - if let Some(v) = block.get(key) { - let Some(b) = v.as_bool() else { - return Err(ModuleError::new( - ErrorCode::ConfigInvalid, - format!("{path}: 'audit.{key}' must be a boolean, got {v}"), - )); - }; - if key == "enabled" { - config.enabled = b; - } else { - config.include_denied = b; - } - } - } - if let Some(v) = block.get("log_level") { - let levels = ["trace", "debug", "info", "warn", "error"]; - let ok = v.as_str().is_some_and(|s| levels.contains(&s)); - if !ok { - return Err(ModuleError::new( - ErrorCode::ConfigInvalid, - format!( - "{path}: 'audit.log_level' must be one of {}, got {v}", - levels.join(", ") - ), - )); - } - config.log_level = v.as_str().unwrap_or("info").to_string(); - } - - if !config.include_denied { - // §6.3.2 requirement 6 — a notice, not a refusal. It withholds the - // security-relevant half of the record, so an operator who wrote it - // deliberately gets told once per load rather than stopped. - tracing::warn!( - path = %path, - "This ACL file sets audit.include_denied: false, so DENIED access attempts will \ - not be recorded by the default audit sink (PROTOCOL_SPEC §6.3.2 requirement 6). \ - Allowed calls are still recorded. Remove the entry to restore denials." - ); - } - Ok(Some(config)) -} - /// One rule that fails PROTOCOL_SPEC §6.1.4's structural and registry /// precheck. /// @@ -1980,261 +1821,6 @@ impl ACL { self.finalize_default_effect(&default_effect, caller, target_id, ctx, pending_approval) } - /// Load ACL rules from a YAML file. - #[cfg(feature = "config")] - pub fn load(path: &str) -> Result { - let content = std::fs::read_to_string(path).map_err(|e| { - ModuleError::new( - ErrorCode::ConfigNotFound, - format!("Failed to read ACL file '{path}': {e}"), - ) - })?; - - // Sync finding A-D-022: structural ACL parse/validation errors carry - // `ErrorCode::ACLRuleError` per spec contract — apcore-python and - // apcore-typescript both raise `ACLRuleError`. Previously Rust used - // `ErrorCode::ConfigInvalid`, which broke cross-language fixtures - // asserting on the error code. - let raw: serde_json::Value = serde_yaml::from_str(&content).map_err(|e| { - ModuleError::new( - ErrorCode::ACLRuleError, - format!("Failed to parse ACL file '{path}': {e}"), - ) - })?; - - // PROTOCOL_SPEC §9.2.4.1 (aiperceivable/apcore#118): an `audit:` block - // in an ACL file has never been read. Deleting it from - // `acl-config.schema.json` would produce no signal at all — no - // implementation validates an ACL file against that schema, and this - // loader parses into a `serde_json::Value` and takes the fields it - // wants, so any unknown root key is dropped in silence. The diagnostic - // therefore has to live here. - // - // Scoped to `audit` deliberately: §6.3.2 requirement 8 validates this - // SUBTREE and nothing else, so every other unrecognised root key in an - // ACL file keeps being ignored exactly as before. This was never - // unknown-key closure for ACL files, and wiring the block does not make - // it one. - // - // The §9.2.4.1 deprecation notice that used to stand here is gone: spec - // v1.45.0 gave the block a delivery contract, and a key that has gained - // a consumer must stop being announced as going away. - let audit_config = parse_audit_block(&raw, path)?; - - // §6.2.1 point 2: `default_effect` is judged FIRST — ahead of the - // individual rules AND ahead of the file-level checks on the `rules` - // collection itself. It used to sit behind the missing-`rules` check - // below, so a document wrong in both was refused for the absent - // `rules` key at this door while `ACL::try_new`, which cannot see that - // fault at all, named the `default_effect`. A non-list `rules` is - // caught further down still, by the deserialization, and was already - // behind this. - // - // Distinguish "key absent" (→ canonical default `deny`) from "key - // present but not a string". The previous - // `.and_then(as_str).unwrap_or("deny")` silently coerced a non-string - // such as `default_effect: true` into a valid value, so `try_new`'s - // validation never fired and an operator typo went unreported. - // apcore-python and apcore-typescript both raise `ACLRuleError` here. - // The outcome was fail-closed either way, so this is a diagnostics fix, - // not a bypass. - // - // An explicit `default_effect: null` is NOT the same as an absent key: - // `schemas/acl-config.schema.json` declares `default_effect` as a plain - // `allow` / `deny` string enum, not nullable, so a written `null` is a - // type violation the operator asked for, not a request for the - // canonical default. Only OMISSION defaults to `deny`; `Value::Null` - // falls through to the same rejection as any other non-string value. - let default_effect = match raw.get("default_effect") { - None => "deny".to_string(), - Some(serde_json::Value::String(s)) => s.clone(), - Some(other) => { - return Err(ModuleError::new( - ErrorCode::ACLRuleError, - format!( - "ACL file '{path}': default_effect must be the string 'allow' or 'deny' (got {other})" - ), - )) - } - }; - - // PROTOCOL_SPEC §6.2.1 point 2 (spec v1.31.0, #112): the RULE INDEX - // dominates every axis, so a file with more than one bad rule is - // refused for the LOWEST-INDEXED one. The `default_effect` is not a - // rule and has no index, so it is judged first — which is also the - // order `try_new` uses, and this door and that one have to agree. - // - // Checked here rather than left to `try_new` below because the rule - // loop that follows now raises the rule-level refusals itself: leaving - // `default_effect` to `try_new` would put every rule fault ahead of it - // at THIS door and behind it at the constructor, which is precisely - // the cross-door disagreement §6.2.1 point 2 exists to end. - if !EFFECTS.contains(&default_effect.as_str()) { - return Err(ModuleError::new( - ErrorCode::ACLRuleError, - format!( - "Invalid ACL config in '{path}': Invalid default_effect \ - '{default_effect}': must be 'allow' or 'deny'" - ), - )); - } - - // Expect top-level "rules" key — the first file-level check on the - // collection, and behind `default_effect` on §6.2.1 point 2. - let rules_val = raw.get("rules").ok_or_else(|| { - ModuleError::new( - ErrorCode::ACLRuleError, - format!("ACL file '{path}' missing 'rules' key"), - ) - })?; - - // A12-ACL: every rule MUST explicitly declare `callers` and `targets`. - // `#[serde(default)]` on those fields would otherwise let an omitted - // key load as an empty Vec, silently turning a deny rule inert. Reject - // a missing key here (the key may be an empty list — only OMISSION is - // rejected), matching apcore-python acl.py:270 and apcore-typescript - // acl.ts:74 which raise ACLRuleError at load (sync finding A-D-09). - // - // Every axis for rule `i` is judged before rule `i + 1` is looked at. - // The loop used to run the key checks across the WHOLE list and leave - // the rest to `try_new`, so a file whose rule 0 carried an unrecognised - // `effect` and whose rule 1 carried an unknown key was refused for - // rule 1 — an axis swept across every rule ahead of the next axis, - // which §6.2.1 point 2 forbids by name. - if let Some(rules_arr) = rules_val.as_array() { - for (i, raw_rule) in rules_arr.iter().enumerate() { - let Some(obj) = raw_rule.as_object() else { - return Err(ModuleError::new( - ErrorCode::ACLRuleError, - format!("ACL rule {i} in '{path}' must be a mapping"), - )); - }; - for key in ["callers", "targets"] { - if !obj.contains_key(key) { - return Err(ModuleError::new( - ErrorCode::ACLRuleError, - format!("ACL rule {i} in '{path}' missing required key '{key}'"), - )); - } - } - - // A missing key was already rejected above so an omission cannot - // render a rule inert; an unknown key is the same hazard pointing - // the other way, and was dropped in silence until #107. - reject_unknown_rule_keys(i, path, obj)?; - - // ...and this rule's `effect` / `approval` / patterns, in - // §6.2.1 point 2's order, through the same `validate_rule` - // every other door uses. `try_new` re-runs it below; that is - // deliberate — the funnel stays the single place the three - // axes are defined, and this loop only decides WHEN it runs. - let rule: ACLRule = serde_json::from_value(raw_rule.clone()).map_err(|e| { - ModuleError::new( - ErrorCode::ACLRuleError, - format!("Invalid ACL rules in '{path}': {e}"), - ) - })?; - Self::validate_rule(i, &rule).map_err(|e| { - ModuleError::new( - ErrorCode::ACLRuleError, - format!("Invalid ACL config in '{path}': {}", e.message), - ) - })?; - } - } - - let rules: Vec = serde_json::from_value(rules_val.clone()).map_err(|e| { - ModuleError::new( - ErrorCode::ACLRuleError, - format!("Invalid ACL rules in '{path}': {e}"), - ) - })?; - - // Propagate try_new validation errors as Result rather than panicking - // — YAML errors must not crash the host process (sync finding A-D-302). - let mut acl = Self::try_new(rules, default_effect, None).map_err(|e| { - ModuleError::new( - ErrorCode::ACLRuleError, - format!("Invalid ACL config in '{path}': {}", e.message), - ) - })?; - acl.yaml_path = Some(path.to_string()); - // §6.3.2 requirement 2 — the declared block becomes the default sink's - // configuration. `try_new` above built a sink with no config because it - // knows nothing about files. - acl.audit_config = audit_config; - acl.audit_sink = AuditSink::new(acl.audit_logger.clone(), acl.audit_config.clone()); - Ok(acl) - } - - /// Activate `acl.root` config-driven ACL discovery (D-64, Recommendation A). - /// - /// Resolves the `acl.root` config key (default `"./acl"`) and loads an ACL - /// from it when the path exists. Relative values use the project root - /// captured by [`crate::config::Config::project_root`]. - /// - /// `acl.root` is a directory by spec convention (`acl/{scope}_acl.yaml`, - /// PROTOCOL_SPEC §3.1). When the resolved path is a directory, the - /// conventional `global_acl.yaml` within it is loaded; if that file is - /// absent the result is `None` (the missing-path no-op still holds). When - /// the resolved path is itself a file, it is loaded directly. Either way the - /// actual load goes through [`ACL::load`]. - /// - /// **Critical invariant:** a missing path returns `None` and attaches - /// NOTHING. It MUST NOT synthesize an empty default-deny ACL — doing so - /// would silently deny every inter-module call in every project that lacks - /// an `acl` dir. Missing path means "no enforcement", identical to pre-D-64 - /// behavior. [`ACL::load`] reads `default_effect` from the ACL file itself. - /// - /// # Errors - /// Returns [`ModuleError`] when a policy path cannot be inspected or - /// the policy cannot be loaded. A missing path yields `Ok(None)`. - #[cfg(feature = "config")] - pub fn discover(config: &crate::config::Config) -> Result, ModuleError> { - let Some(root_path) = config.get_path("acl.root") else { - return Ok(None); - }; - - let Some(metadata) = Self::discover_metadata(&root_path)? else { - return Ok(None); - }; - - let (path, metadata) = if metadata.is_dir() { - let path = root_path.join("global_acl.yaml"); - let Some(metadata) = Self::discover_metadata(&path)? else { - return Ok(None); - }; - (path, metadata) - } else { - (root_path, metadata) - }; - if !metadata.is_file() { - return Err(ModuleError::new( - ErrorCode::ConfigInvalid, - format!("ACL path '{}' is not a regular file", path.display()), - )); - } - Self::load(&path.to_string_lossy()).map(Some) - } - - #[cfg(feature = "config")] - fn discover_metadata(path: &Path) -> Result, ModuleError> { - let inspect_error = |error: std::io::Error| { - ModuleError::new( - ErrorCode::ConfigInvalid, - format!("Cannot inspect ACL path '{}': {error}", path.display()), - ) - }; - match std::fs::symlink_metadata(path) { - Ok(meta) if meta.is_symlink() => { - std::fs::metadata(path).map(Some).map_err(inspect_error) - } - Ok(meta) => Ok(Some(meta)), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), - Err(error) => Err(inspect_error(error)), - } - } - /// Register a custom condition handler. Delegates to `acl_handlers::register_condition`. pub fn register_condition( key: impl Into, @@ -2259,56 +1845,6 @@ impl ACL { crate::acl_handlers::register_async_condition(key, handler); } - /// Reload rules from the stored YAML path. - /// - /// **Deadlock avoidance:** the borrow on `self.yaml_path` is released - /// (via clone + scope) *before* the blocking file I/O in [`Self::load`] - /// begins. This matters when the caller holds the ACL inside an - /// `Arc>`-style wrapper and an audit logger or condition - /// handler tries to read the same lock from another thread mid-reload. - /// Holding `&mut self` across `Self::load` would block any concurrent - /// reader for the duration of the file read; the brace scope below - /// makes that explicitly impossible (sync finding A-D-303). - #[cfg(feature = "config")] - pub fn reload(&mut self) -> Result<(), ModuleError> { - let path = { - // Narrow scope: the immutable borrow on `self.yaml_path` ends - // at the closing brace, *before* file I/O is initiated below. - self.yaml_path.clone().ok_or_else(|| { - ModuleError::new( - ErrorCode::ACLRuleError, - "Cannot reload: ACL was not loaded from a YAML file".to_string(), - ) - })? - }; - - // File I/O happens here with no outstanding borrow on `self`. - let reloaded = Self::load(&path)?; - - self.rules = reloaded.rules; - self.default_effect = reloaded.default_effect; - // §6.3.2 requirement 7: a reload refreshes the `audit:` block and - // PRESERVES a programmatic callback, which was never read from the - // file. Before v1.45.0 this method refreshed only the rules and the - // default effect, so the audit block was the one part of the document a - // reload did not pick up. - // - // Building a NEW sink is also what scopes requirement 5's - // once-per-failure suppression: a reload that changes the sink's - // configuration starts a fresh report rather than hiding a new failure - // behind an old one. - self.audit_config = reloaded.audit_config; - self.audit_sink = AuditSink::new(self.audit_logger.clone(), self.audit_config.clone()); - warn_audit_block_overridden(self.audit_logger.as_ref(), self.audit_config.as_ref()); - // D-88: the reload may have repointed every index at a different rule. - self.clear_missing_context_warnings(); - // `self.yaml_path` is intentionally left untouched: reload re-reads the - // *stored* path, so reassigning it is a no-op (reloaded.yaml_path always - // equals the existing path). Matches apcore-python / apcore-typescript, - // which do not re-set the path on reload. - Ok(()) - } - /// The current rule list, in definition order (PROTOCOL_SPEC §6.8). /// /// Read-only introspection: an immutable slice, so a caller can neither @@ -3035,32 +2571,6 @@ impl Default for ACL { } } -#[cfg(all(test, feature = "config"))] -mod reload_tests { - use super::*; - use std::io::Write; - - // [acl-reload-yamlpath] reload() must leave `yaml_path` unchanged (it - // re-reads the stored path). Matches apcore-python / apcore-typescript, - // which do not re-set the path on reload. - #[test] - fn reload_leaves_yaml_path_unchanged() { - let mut tmp = tempfile::NamedTempFile::new().expect("create tempfile"); - writeln!(tmp, "default_effect: deny\nrules: []\n").expect("write tempfile"); - let path = tmp.path().to_str().expect("utf8").to_string(); - - let mut acl = ACL::load(&path).expect("initial load"); - let before = acl.yaml_path.clone(); - assert_eq!(before, Some(path.clone())); - - acl.reload().expect("reload"); - assert_eq!( - acl.yaml_path, before, - "reload must not change the stored yaml_path" - ); - } -} - #[cfg(test)] mod projection_forgery_tests { //! PROTOCOL_SPEC §6.1.8 rule 3 — the governance projection MUST NOT be diff --git a/rust/src/acl/file.rs b/rust/src/acl/file.rs new file mode 100644 index 00000000..4e98c653 --- /dev/null +++ b/rust/src/acl/file.rs @@ -0,0 +1,494 @@ +//! YAML loading and discovery for access control lists. + +use std::path::Path; + +use serde_yaml_ng as serde_yaml; + +use crate::errors::{ErrorCode, ModuleError}; + +use super::{ + warn_audit_block_overridden, ACLRule, AuditConfig, AuditSink, ACL, AUDIT_FIELDS, EFFECTS, +}; + +/// The complete set of keys an ACL rule may carry (PROTOCOL_SPEC §6.1). +/// +/// Closed on purpose: a key nothing evaluates is otherwise dropped in silence, +/// which widens an `allow` rule with no warning (#107). +const RULE_KEYS: &[&str] = &[ + "callers", + "targets", + "effect", + "approval", + "description", + "conditions", +]; + +/// Reserved in earlier revisions of §6.1 and evaluated by no implementation. +/// +/// Rejected like any other unknown key, but named as reserved in the message: +/// an operator who wrote `actions: ["describe"]` meant to restrict the rule and +/// is better served by "not implemented" than by "unknown key". +const RESERVED_RULE_KEYS: &[&str] = &["id", "actions", "priority"]; + +/// Reject any rule key outside [`RULE_KEYS`]. +fn reject_unknown_rule_keys( + index: usize, + path: &str, + obj: &serde_json::Map, +) -> Result<(), ModuleError> { + let mut unknown: Vec<&str> = obj + .keys() + .map(String::as_str) + .filter(|k| !RULE_KEYS.contains(k)) + .collect(); + if unknown.is_empty() { + return Ok(()); + } + unknown.sort_unstable(); + let (reserved, other): (Vec<&str>, Vec<&str>) = unknown + .into_iter() + .partition(|k| RESERVED_RULE_KEYS.contains(k)); + let quote = |ks: &[&str]| { + ks.iter() + .map(|k| format!("'{k}'")) + .collect::>() + .join(", ") + }; + let mut parts: Vec = Vec::new(); + if !reserved.is_empty() { + parts.push(format!( + "{} reserved for a future specification version and evaluated by no implementation", + quote(&reserved) + )); + } + if !other.is_empty() { + parts.push(format!("{} unrecognised", quote(&other))); + } + Err(ModuleError::new( + ErrorCode::ACLRuleError, + format!( + "ACL rule {index} in '{path}' carries {}. The rule key set is closed ({}); \ + a key nothing evaluates would be dropped silently and leave the rule wider than written.", + parts.join("; "), + RULE_KEYS.join(", ") + ), + )) +} + +/// Validate an ACL file's `audit:` block (§6.3.2 requirement 8). +/// +/// Returns `None` only when the document declares no `audit` key at all. +/// **Presence, not truthiness**: `audit:` with nothing under it parses to null, +/// and the operator still wrote the block — a declaration with every setting at +/// its default, not an absence. +/// +/// Validates the SUBTREE only: types and unknown keys inside the block. Every +/// other unrecognised root key in an ACL file keeps being ignored. +fn parse_audit_block( + raw: &serde_json::Value, + path: &str, +) -> Result, ModuleError> { + let Some(value) = raw.get("audit") else { + return Ok(None); + }; + if value.is_null() { + return Ok(Some(AuditConfig::default())); + } + let Some(block) = value.as_object() else { + return Err(ModuleError::new( + ErrorCode::ConfigInvalid, + format!("{path}: 'audit' must be a mapping (PROTOCOL_SPEC §6.3.2)"), + )); + }; + + let mut unknown: Vec<&str> = block + .keys() + .map(String::as_str) + .filter(|k| !AUDIT_FIELDS.contains(k)) + .collect(); + unknown.sort_unstable(); + if !unknown.is_empty() { + return Err(ModuleError::new( + ErrorCode::ConfigInvalid, + format!( + "{path}: unknown key(s) in the 'audit' block: {}. The block accepts exactly \ + {} ($defs/AuditConfig in schemas/acl-config.schema.json).", + unknown.join(", "), + AUDIT_FIELDS.join(", ") + ), + )); + } + + let mut config = AuditConfig::default(); + for key in ["enabled", "include_denied"] { + if let Some(v) = block.get(key) { + let Some(b) = v.as_bool() else { + return Err(ModuleError::new( + ErrorCode::ConfigInvalid, + format!("{path}: 'audit.{key}' must be a boolean, got {v}"), + )); + }; + if key == "enabled" { + config.enabled = b; + } else { + config.include_denied = b; + } + } + } + if let Some(v) = block.get("log_level") { + let levels = ["trace", "debug", "info", "warn", "error"]; + let ok = v.as_str().is_some_and(|s| levels.contains(&s)); + if !ok { + return Err(ModuleError::new( + ErrorCode::ConfigInvalid, + format!( + "{path}: 'audit.log_level' must be one of {}, got {v}", + levels.join(", ") + ), + )); + } + config.log_level = v.as_str().unwrap_or("info").to_string(); + } + + if !config.include_denied { + // §6.3.2 requirement 6 — a notice, not a refusal. It withholds the + // security-relevant half of the record, so an operator who wrote it + // deliberately gets told once per load rather than stopped. + tracing::warn!( + path = %path, + "This ACL file sets audit.include_denied: false, so DENIED access attempts will \ + not be recorded by the default audit sink (PROTOCOL_SPEC §6.3.2 requirement 6). \ + Allowed calls are still recorded. Remove the entry to restore denials." + ); + } + Ok(Some(config)) +} + +impl ACL { + /// Load ACL rules from a YAML file. + pub fn load(path: &str) -> Result { + let content = std::fs::read_to_string(path).map_err(|e| { + ModuleError::new( + ErrorCode::ConfigNotFound, + format!("Failed to read ACL file '{path}': {e}"), + ) + })?; + + // Sync finding A-D-022: structural ACL parse/validation errors carry + // `ErrorCode::ACLRuleError` per spec contract — apcore-python and + // apcore-typescript both raise `ACLRuleError`. Previously Rust used + // `ErrorCode::ConfigInvalid`, which broke cross-language fixtures + // asserting on the error code. + let raw: serde_json::Value = serde_yaml::from_str(&content).map_err(|e| { + ModuleError::new( + ErrorCode::ACLRuleError, + format!("Failed to parse ACL file '{path}': {e}"), + ) + })?; + + // PROTOCOL_SPEC §9.2.4.1 (aiperceivable/apcore#118): an `audit:` block + // in an ACL file has never been read. Deleting it from + // `acl-config.schema.json` would produce no signal at all — no + // implementation validates an ACL file against that schema, and this + // loader parses into a `serde_json::Value` and takes the fields it + // wants, so any unknown root key is dropped in silence. The diagnostic + // therefore has to live here. + // + // Scoped to `audit` deliberately: §6.3.2 requirement 8 validates this + // SUBTREE and nothing else, so every other unrecognised root key in an + // ACL file keeps being ignored exactly as before. This was never + // unknown-key closure for ACL files, and wiring the block does not make + // it one. + // + // The §9.2.4.1 deprecation notice that used to stand here is gone: spec + // v1.45.0 gave the block a delivery contract, and a key that has gained + // a consumer must stop being announced as going away. + let audit_config = parse_audit_block(&raw, path)?; + + // §6.2.1 point 2: `default_effect` is judged FIRST — ahead of the + // individual rules AND ahead of the file-level checks on the `rules` + // collection itself. It used to sit behind the missing-`rules` check + // below, so a document wrong in both was refused for the absent + // `rules` key at this door while `ACL::try_new`, which cannot see that + // fault at all, named the `default_effect`. A non-list `rules` is + // caught further down still, by the deserialization, and was already + // behind this. + // + // Distinguish "key absent" (→ canonical default `deny`) from "key + // present but not a string". The previous + // `.and_then(as_str).unwrap_or("deny")` silently coerced a non-string + // such as `default_effect: true` into a valid value, so `try_new`'s + // validation never fired and an operator typo went unreported. + // apcore-python and apcore-typescript both raise `ACLRuleError` here. + // The outcome was fail-closed either way, so this is a diagnostics fix, + // not a bypass. + // + // An explicit `default_effect: null` is NOT the same as an absent key: + // `schemas/acl-config.schema.json` declares `default_effect` as a plain + // `allow` / `deny` string enum, not nullable, so a written `null` is a + // type violation the operator asked for, not a request for the + // canonical default. Only OMISSION defaults to `deny`; `Value::Null` + // falls through to the same rejection as any other non-string value. + let default_effect = match raw.get("default_effect") { + None => "deny".to_string(), + Some(serde_json::Value::String(s)) => s.clone(), + Some(other) => { + return Err(ModuleError::new( + ErrorCode::ACLRuleError, + format!( + "ACL file '{path}': default_effect must be the string 'allow' or 'deny' (got {other})" + ), + )) + } + }; + + // PROTOCOL_SPEC §6.2.1 point 2 (spec v1.31.0, #112): the RULE INDEX + // dominates every axis, so a file with more than one bad rule is + // refused for the LOWEST-INDEXED one. The `default_effect` is not a + // rule and has no index, so it is judged first — which is also the + // order `try_new` uses, and this door and that one have to agree. + // + // Checked here rather than left to `try_new` below because the rule + // loop that follows now raises the rule-level refusals itself: leaving + // `default_effect` to `try_new` would put every rule fault ahead of it + // at THIS door and behind it at the constructor, which is precisely + // the cross-door disagreement §6.2.1 point 2 exists to end. + if !EFFECTS.contains(&default_effect.as_str()) { + return Err(ModuleError::new( + ErrorCode::ACLRuleError, + format!( + "Invalid ACL config in '{path}': Invalid default_effect \ + '{default_effect}': must be 'allow' or 'deny'" + ), + )); + } + + // Expect top-level "rules" key — the first file-level check on the + // collection, and behind `default_effect` on §6.2.1 point 2. + let rules_val = raw.get("rules").ok_or_else(|| { + ModuleError::new( + ErrorCode::ACLRuleError, + format!("ACL file '{path}' missing 'rules' key"), + ) + })?; + + // A12-ACL: every rule MUST explicitly declare `callers` and `targets`. + // `#[serde(default)]` on those fields would otherwise let an omitted + // key load as an empty Vec, silently turning a deny rule inert. Reject + // a missing key here (the key may be an empty list — only OMISSION is + // rejected), matching apcore-python acl.py:270 and apcore-typescript + // acl.ts:74 which raise ACLRuleError at load (sync finding A-D-09). + // + // Every axis for rule `i` is judged before rule `i + 1` is looked at. + // The loop used to run the key checks across the WHOLE list and leave + // the rest to `try_new`, so a file whose rule 0 carried an unrecognised + // `effect` and whose rule 1 carried an unknown key was refused for + // rule 1 — an axis swept across every rule ahead of the next axis, + // which §6.2.1 point 2 forbids by name. + if let Some(rules_arr) = rules_val.as_array() { + for (i, raw_rule) in rules_arr.iter().enumerate() { + let Some(obj) = raw_rule.as_object() else { + return Err(ModuleError::new( + ErrorCode::ACLRuleError, + format!("ACL rule {i} in '{path}' must be a mapping"), + )); + }; + for key in ["callers", "targets"] { + if !obj.contains_key(key) { + return Err(ModuleError::new( + ErrorCode::ACLRuleError, + format!("ACL rule {i} in '{path}' missing required key '{key}'"), + )); + } + } + + // A missing key was already rejected above so an omission cannot + // render a rule inert; an unknown key is the same hazard pointing + // the other way, and was dropped in silence until #107. + reject_unknown_rule_keys(i, path, obj)?; + + // ...and this rule's `effect` / `approval` / patterns, in + // §6.2.1 point 2's order, through the same `validate_rule` + // every other door uses. `try_new` re-runs it below; that is + // deliberate — the funnel stays the single place the three + // axes are defined, and this loop only decides WHEN it runs. + let rule: ACLRule = serde_json::from_value(raw_rule.clone()).map_err(|e| { + ModuleError::new( + ErrorCode::ACLRuleError, + format!("Invalid ACL rules in '{path}': {e}"), + ) + })?; + Self::validate_rule(i, &rule).map_err(|e| { + ModuleError::new( + ErrorCode::ACLRuleError, + format!("Invalid ACL config in '{path}': {}", e.message), + ) + })?; + } + } + + let rules: Vec = serde_json::from_value(rules_val.clone()).map_err(|e| { + ModuleError::new( + ErrorCode::ACLRuleError, + format!("Invalid ACL rules in '{path}': {e}"), + ) + })?; + + // Propagate try_new validation errors as Result rather than panicking + // — YAML errors must not crash the host process (sync finding A-D-302). + let mut acl = Self::try_new(rules, default_effect, None).map_err(|e| { + ModuleError::new( + ErrorCode::ACLRuleError, + format!("Invalid ACL config in '{path}': {}", e.message), + ) + })?; + acl.yaml_path = Some(path.to_string()); + // §6.3.2 requirement 2 — the declared block becomes the default sink's + // configuration. `try_new` above built a sink with no config because it + // knows nothing about files. + acl.audit_config = audit_config; + acl.audit_sink = AuditSink::new(acl.audit_logger.clone(), acl.audit_config.clone()); + Ok(acl) + } + + /// Activate `acl.root` config-driven ACL discovery (D-64, Recommendation A). + /// + /// Resolves the `acl.root` config key (default `"./acl"`) and loads an ACL + /// from it when the path exists. Relative values use the project root + /// captured by [`crate::config::Config::project_root`]. + /// + /// `acl.root` is a directory by spec convention (`acl/{scope}_acl.yaml`, + /// PROTOCOL_SPEC §3.1). When the resolved path is a directory, the + /// conventional `global_acl.yaml` within it is loaded; if that file is + /// absent the result is `None` (the missing-path no-op still holds). When + /// the resolved path is itself a file, it is loaded directly. Either way the + /// actual load goes through [`ACL::load`]. + /// + /// **Critical invariant:** a missing path returns `None` and attaches + /// NOTHING. It MUST NOT synthesize an empty default-deny ACL — doing so + /// would silently deny every inter-module call in every project that lacks + /// an `acl` dir. Missing path means "no enforcement", identical to pre-D-64 + /// behavior. [`ACL::load`] reads `default_effect` from the ACL file itself. + /// + /// # Errors + /// Returns [`ModuleError`] when a policy path cannot be inspected or + /// the policy cannot be loaded. A missing path yields `Ok(None)`. + pub fn discover(config: &crate::config::Config) -> Result, ModuleError> { + let Some(root_path) = config.get_path("acl.root") else { + return Ok(None); + }; + + let Some(metadata) = Self::discover_metadata(&root_path)? else { + return Ok(None); + }; + + let (path, metadata) = if metadata.is_dir() { + let path = root_path.join("global_acl.yaml"); + let Some(metadata) = Self::discover_metadata(&path)? else { + return Ok(None); + }; + (path, metadata) + } else { + (root_path, metadata) + }; + if !metadata.is_file() { + return Err(ModuleError::new( + ErrorCode::ConfigInvalid, + format!("ACL path '{}' is not a regular file", path.display()), + )); + } + Self::load(&path.to_string_lossy()).map(Some) + } + + fn discover_metadata(path: &Path) -> Result, ModuleError> { + let inspect_error = |error: std::io::Error| { + ModuleError::new( + ErrorCode::ConfigInvalid, + format!("Cannot inspect ACL path '{}': {error}", path.display()), + ) + }; + match std::fs::symlink_metadata(path) { + Ok(meta) if meta.is_symlink() => { + std::fs::metadata(path).map(Some).map_err(inspect_error) + } + Ok(meta) => Ok(Some(meta)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(inspect_error(error)), + } + } + + /// Reload rules from the stored YAML path. + /// + /// **Deadlock avoidance:** the borrow on `self.yaml_path` is released + /// (via clone + scope) *before* the blocking file I/O in [`Self::load`] + /// begins. This matters when the caller holds the ACL inside an + /// `Arc>`-style wrapper and an audit logger or condition + /// handler tries to read the same lock from another thread mid-reload. + /// Holding `&mut self` across `Self::load` would block any concurrent + /// reader for the duration of the file read; the brace scope below + /// makes that explicitly impossible (sync finding A-D-303). + pub fn reload(&mut self) -> Result<(), ModuleError> { + let path = { + // Narrow scope: the immutable borrow on `self.yaml_path` ends + // at the closing brace, *before* file I/O is initiated below. + self.yaml_path.clone().ok_or_else(|| { + ModuleError::new( + ErrorCode::ACLRuleError, + "Cannot reload: ACL was not loaded from a YAML file".to_string(), + ) + })? + }; + + // File I/O happens here with no outstanding borrow on `self`. + let reloaded = Self::load(&path)?; + + self.rules = reloaded.rules; + self.default_effect = reloaded.default_effect; + // §6.3.2 requirement 7: a reload refreshes the `audit:` block and + // PRESERVES a programmatic callback, which was never read from the + // file. Before v1.45.0 this method refreshed only the rules and the + // default effect, so the audit block was the one part of the document a + // reload did not pick up. + // + // Building a NEW sink is also what scopes requirement 5's + // once-per-failure suppression: a reload that changes the sink's + // configuration starts a fresh report rather than hiding a new failure + // behind an old one. + self.audit_config = reloaded.audit_config; + self.audit_sink = AuditSink::new(self.audit_logger.clone(), self.audit_config.clone()); + warn_audit_block_overridden(self.audit_logger.as_ref(), self.audit_config.as_ref()); + // D-88: the reload may have repointed every index at a different rule. + self.clear_missing_context_warnings(); + // `self.yaml_path` is intentionally left untouched: reload re-reads the + // *stored* path, so reassigning it is a no-op (reloaded.yaml_path always + // equals the existing path). Matches apcore-python / apcore-typescript, + // which do not re-set the path on reload. + Ok(()) + } +} + +#[cfg(test)] +mod reload_tests { + use super::*; + use std::io::Write; + + // [acl-reload-yamlpath] reload() must leave `yaml_path` unchanged (it + // re-reads the stored path). Matches apcore-python / apcore-typescript, + // which do not re-set the path on reload. + #[test] + fn reload_leaves_yaml_path_unchanged() { + let mut tmp = tempfile::NamedTempFile::new().expect("create tempfile"); + writeln!(tmp, "default_effect: deny\nrules: []\n").expect("write tempfile"); + let path = tmp.path().to_str().expect("utf8").to_string(); + + let mut acl = ACL::load(&path).expect("initial load"); + let before = acl.yaml_path.clone(); + assert_eq!(before, Some(path.clone())); + + acl.reload().expect("reload"); + assert_eq!( + acl.yaml_path, before, + "reload must not change the stored yaml_path" + ); + } +} diff --git a/rust/src/executor.rs b/rust/src/executor.rs index 2b68fb9a..a1aab4cd 100644 --- a/rust/src/executor.rs +++ b/rust/src/executor.rs @@ -2377,7 +2377,11 @@ impl Executor { // cannot drift from the gate. let acl_configured = self.acl.is_some(); let approval_handler_configured = self.approval_handler.is_some(); - let policy_strict = ExecutionPolicy::effective(self.policy.as_deref()).strict; + let policy_strict = if builtin_approval_gate_wired { + ExecutionPolicy::effective(self.policy.as_deref()).strict + } else { + self.policy.as_deref().is_some_and(|policy| policy.strict) + }; // PROTOCOL_SPEC 6.6.5.1. The approval conjunct carries // `all_control_modules_require_approval` because `approval_gate` is diff --git a/rust/src/registry/filesystem_watch.rs b/rust/src/registry/filesystem_watch.rs new file mode 100644 index 00000000..062d1077 --- /dev/null +++ b/rust/src/registry/filesystem_watch.rs @@ -0,0 +1,338 @@ +//! Platform filesystem watching and application of discovery updates. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use crate::errors::ModuleError; +use crate::events::emitter::ApCoreEvent; +use crate::lifecycle::{lifecycle_runtime, ReloadOptions}; + +use super::{DiscoveredModule, Registry}; + +#[derive(Default)] +pub(super) struct FilesystemWatch { + /// Live filesystem watcher (sync finding A-D-010). `None` when + /// `watch()` has not been called or has been stopped via `unwatch()`. + watcher: parking_lot::Mutex>, + /// Background task handle that consumes notify events and triggers + /// debounced re-discovery. Cleared on `unwatch()`. + watch_handle: parking_lot::Mutex>>, +} + +/// A watched path in the form the platform watcher reports it. +/// +/// Watchers report resolved paths (`/private/var/...` on macOS for a root under +/// `/var/...`), so both sides of a comparison are canonicalised. A removed file +/// can no longer be canonicalised, so its parent is instead. +fn normalize_watched_path(path: &std::path::Path) -> std::path::PathBuf { + if let Ok(resolved) = std::fs::canonicalize(path) { + return resolved; + } + match (path.parent(), path.file_name()) { + (Some(parent), Some(name)) => { + std::fs::canonicalize(parent).map_or_else(|_| path.to_path_buf(), |dir| dir.join(name)) + } + _ => path.to_path_buf(), + } +} + +impl Registry { + /// Watch the extension roots and apply file changes to the registry. + /// + /// Watches every path in `extension_roots` recursively. File events are + /// grouped after 300 ms of quiet and handled through the configured + /// discoverer. New candidates are registered. When an existing source or + /// its metadata sidecar changes, the old instance is suspended and + /// unregistered before the replacement is registered. The replacement + /// receives `on_resume` if suspension returned state. A deleted source is + /// unregistered when its module is absent from the discovery results. + /// + /// # Caller obligations + /// + /// `watch()` requires `&Arc` because the spawned background task + /// holds a `Weak` to drive re-discovery; the registry must + /// already live behind `Arc`. Calling on a non-Arc Registry is a + /// compile-time error. + /// + /// # Errors + /// + /// - `Err(ModuleError(code=ReloadFailed))` if the platform watcher cannot + /// be created (kernel resource exhaustion, missing permissions, etc.) + /// + /// # Idempotency + /// + /// Calling `watch()` while already watching is a no-op (returns `Ok(())`). + /// Use [`Self::unwatch`] to stop and re-call `watch()` to pick up new + /// `extension_roots`. + // Keep the async API for existing callers. Startup installs the watcher + // and spawns its Tokio task; the task consumes events after this returns. + // Rust 1.98 split the lint. The unknown-lints allowance keeps the new lint + // name compatible with older toolchains. + #[allow(unknown_lints)] + #[allow(clippy::unused_async)] + #[allow(clippy::unused_async_trait_impl)] + pub async fn watch(self: &Arc) -> Result<(), ModuleError> { + self.start_watcher(None) + } + + /// Watch configured roots with managed, generation-aware replacement. + pub fn watch_with_lifecycle( + self: &Arc, + options: ReloadOptions, + ) -> Result<(), ModuleError> { + self.start_watcher(Some(options.validate()?)) + } + + fn start_watcher( + self: &Arc, + lifecycle: Option, + ) -> Result<(), ModuleError> { + use notify::{RecursiveMode, Watcher}; + + if self.core.read().closed { + return Err(Self::closed_error()); + } + + { + let watcher_slot = self.filesystem_watch.watcher.lock(); + if watcher_slot.is_some() { + return Ok(()); // already watching + } + } + + let extension_roots: Vec = self.extension_roots.read().clone(); + if extension_roots.is_empty() { + tracing::warn!( + "Registry::watch() called with no extension_roots — call set_extension_roots() first" + ); + return Ok(()); + } + + let (tx, rx) = tokio::sync::mpsc::unbounded_channel::>(); + + let mut watcher = notify::recommended_watcher(move |res: notify::Result| { + // Best-effort send; if the receiver is gone, the watcher will be + // dropped shortly after. + let _ = tx.send(res); + }) + .map_err(|e| { + ModuleError::new( + crate::errors::ErrorCode::ReloadFailed, + format!("Failed to create file watcher: {e}"), + ) + })?; + + for root in &extension_roots { + let path = std::path::Path::new(root); + if let Err(e) = watcher.watch(path, RecursiveMode::Recursive) { + tracing::warn!( + root = %root, + error = %e, + "Registry::watch failed for root, skipping" + ); + } + } + + let core = self.core.read(); + if core.closed { + return Err(Self::closed_error()); + } + let mut watcher_slot = self.filesystem_watch.watcher.lock(); + if watcher_slot.is_none() { + let runtime = lifecycle_runtime()?; + let handle = runtime.spawn(Self::watch_loop(rx, Arc::downgrade(self), lifecycle)); + *watcher_slot = Some(watcher); + *self.filesystem_watch.watch_handle.lock() = Some(handle); + } + + Ok(()) + } + + /// Background task body that consumes notify events and applies each + /// debounced batch of changed paths. Exits when the receiver channel + /// closes or the `Weak` can no longer be upgraded. + async fn watch_loop( + mut rx: tokio::sync::mpsc::UnboundedReceiver>, + weak: std::sync::Weak, + lifecycle: Option, + ) { + use std::time::Duration; + + const DEBOUNCE: Duration = Duration::from_millis(300); + + fn relevant(event: ¬ify::Event) -> bool { + matches!( + event.kind, + notify::EventKind::Create(_) + | notify::EventKind::Modify(_) + | notify::EventKind::Remove(_) + ) + } + + while let Some(res) = rx.recv().await { + let Ok(event) = res else { + continue; + }; + if !relevant(&event) { + continue; + } + // Collapse a burst (editors writing through temp file + rename) + // into one pass, keeping every path the burst touched. + let mut paths: Vec = event.paths; + while let Ok(Some(res)) = tokio::time::timeout(DEBOUNCE, rx.recv()).await { + if let Ok(event) = res { + if relevant(&event) { + paths.extend(event.paths); + } + } + } + + let Some(reg) = weak.upgrade() else { + break; + }; + let task = tokio::spawn(async move { reg.apply_file_changes(&paths, lifecycle).await }); + if let Ok(Err(e)) = task.await { + tracing::warn!( + error = %e.message, + "Registry watch: applying file changes failed during hot-reload" + ); + } + } + } + + /// Apply a batch of changed file paths: register new modules, replace the + /// modules whose source (or `_meta.yaml` sidecar) changed, and unregister + /// those whose source file is gone. + async fn apply_file_changes( + self: &Arc, + paths: &[std::path::PathBuf], + lifecycle: Option, + ) -> Result<(), ModuleError> { + let changed: HashSet = + paths.iter().map(|p| normalize_watched_path(p)).collect(); + let touches = |source: &str| { + let source = normalize_watched_path(std::path::Path::new(source)); + if changed.contains(&source) { + return true; + } + let (Some(dir), Some(stem)) = (source.parent(), source.file_stem()) else { + return false; + }; + changed.contains(&dir.join(format!("{}_meta.yaml", stem.to_string_lossy()))) + }; + + let discovered = self.run_discoverer().await?; + + let removed: Vec = { + let core = self.core.read(); + core.sources + .iter() + .filter(|(id, source)| { + !std::path::Path::new(source).exists() + && touches(source) + && !discovered.iter().any(|dm| &dm.name == *id) + }) + .map(|(id, _)| id.clone()) + .collect() + }; + for id in removed { + self.safe_unregister(&id, 5000).await?; + } + + let batch_ids = discovered.iter().map(|entry| entry.name.clone()).collect(); + for dm in discovered { + if !self.has(&dm.name) { + self.register_discovered_batch( + std::iter::once(dm), + &batch_ids, + &HashMap::new(), + true, + ) + .await; + } else if touches(&dm.source) { + if let Some(options) = lifecycle { + self.start_managed_reload_with_candidate( + vec![dm.name.clone()], + options, + Some(dm), + )? + .wait(None) + .await?; + } else { + self.replace_discovered(dm, &batch_ids).await?; + } + } + } + Ok(()) + } + + /// Replace a registered module with a freshly discovered instance, + /// handing its `on_suspend` state to the new instance's `on_resume`. The + /// previous instance is put back if the new one fails to register. + async fn replace_discovered( + &self, + dm: DiscoveredModule, + batch_ids: &HashSet, + ) -> Result<(), ModuleError> { + let name = dm.name.clone(); + let Some(previous) = self.unload_for_reload(&name).await? else { + return Ok(()); + }; + let states: HashMap<_, _> = previous + .state + .as_ref() + .map(|state| (name.clone(), state.clone())) + .into_iter() + .collect(); + if self + .register_discovered_batch(std::iter::once(dm), batch_ids, &states, true) + .await + == 0 + { + tracing::warn!( + module_id = %name, + "Registry watch: the changed module failed to register; keeping the previous instance" + ); + let restoration = self.restore_reload(&name, previous).await; + if let Some(emitter) = self.event_emitter.read().clone() { + emitter.emit_delivery_semantics(ApCoreEvent::with_module( + "apcore.registry.module_reload_failed", + serde_json::json!({ + "operation_id": uuid::Uuid::new_v4().to_string(), + "phase": "loading", "error_code": "RELOAD_FAILED", + "compensation": if restoration.is_ok() { "restored" } else { "failed" }, + }), + &name, + "error", + )); + } + restoration?; + + return Ok(()); + } + + Ok(()) + } + + /// Stop filesystem watching. The background task is aborted and the + /// platform watcher is dropped. Idempotent — calling on a non-watching + /// Registry is a no-op. + pub fn unwatch(&self) { + self.stop_watching(); + } + + pub(super) fn stop_watching(&self) -> Option> { + let (watcher, handle) = { + let mut watcher = self.filesystem_watch.watcher.lock(); + ( + watcher.take(), + self.filesystem_watch.watch_handle.lock().take(), + ) + }; + drop(watcher); + if let Some(handle) = &handle { + handle.abort(); + } + handle + } +} diff --git a/rust/src/registry/registry.rs b/rust/src/registry/registry.rs index a31c821a..9e994aac 100644 --- a/rust/src/registry/registry.rs +++ b/rust/src/registry/registry.rs @@ -14,8 +14,6 @@ use std::sync::{ use crate::cancel::CancelToken; use crate::errors::ModuleError; use crate::events::emitter::{ApCoreEvent, EventEmitter}; -#[cfg(feature = "discovery")] -use crate::lifecycle::{lifecycle_runtime, ReloadOptions}; use crate::lifecycle::{lifecycle_worker, REGISTRY_CALLBACK}; use crate::module::{ Module, ModuleAnnotations, ModuleExample, ValidationErrorDetail, ValidationResult, @@ -27,6 +25,9 @@ use crate::registry::version::try_matches_version_hint; #[path = "async_lifecycle.rs"] mod async_lifecycle; +#[cfg(feature = "discovery")] +#[path = "filesystem_watch.rs"] +mod filesystem_watch; #[path = "managed_lifecycle.rs"] mod managed_lifecycle; @@ -952,14 +953,8 @@ pub struct Registry { /// [`set_extension_roots`](Self::set_extension_roots); passed verbatim to /// `Discoverer::discover(roots)` in `discover_internal()`. extension_roots: RwLock>, - /// Live filesystem watcher (sync finding A-D-010). `None` when - /// `watch()` has not been called or has been stopped via `unwatch()`. - #[cfg(feature = "discovery")] - watcher: parking_lot::Mutex>, - /// Background task handle that consumes notify events and triggers - /// debounced re-discovery. Cleared on `unwatch()`. #[cfg(feature = "discovery")] - watch_handle: parking_lot::Mutex>>, + filesystem_watch: filesystem_watch::FilesystemWatch, /// Tracks unpublished registrations and excludes concurrent registrations /// of the same ID, including while rejected loads are being cleaned up. in_flight: LoadingRegistrations, @@ -987,24 +982,6 @@ struct DiscovererRestoreGuard<'a> { discoverer: Option>, } -/// A watched path in the form the platform watcher reports it. -/// -/// Watchers report resolved paths (`/private/var/...` on macOS for a root under -/// `/var/...`), so both sides of a comparison are canonicalised. A removed file -/// can no longer be canonicalised, so its parent is instead. -#[cfg(feature = "discovery")] -fn normalize_watched_path(path: &std::path::Path) -> std::path::PathBuf { - if let Ok(resolved) = std::fs::canonicalize(path) { - return resolved; - } - match (path.parent(), path.file_name()) { - (Some(parent), Some(name)) => { - std::fs::canonicalize(parent).map_or_else(|_| path.to_path_buf(), |dir| dir.join(name)) - } - _ => path.to_path_buf(), - } -} - impl Drop for DiscovererRestoreGuard<'_> { fn drop(&mut self) { if let Some(d) = self.discoverer.take() { @@ -1069,9 +1046,7 @@ impl Registry { validator: RwLock::new(None), extension_roots: RwLock::new(Vec::new()), #[cfg(feature = "discovery")] - watcher: parking_lot::Mutex::new(None), - #[cfg(feature = "discovery")] - watch_handle: parking_lot::Mutex::new(None), + filesystem_watch: filesystem_watch::FilesystemWatch::default(), in_flight: LoadingRegistrations::default(), load_failed_callbacks: RwLock::new(Vec::new()), event_emitter: Arc::new(RwLock::new(None)), @@ -2663,310 +2638,6 @@ impl Registry { self.discover_internal().await } - /// Watch the extension roots and apply file changes to the registry. - /// - /// Watches every path in `extension_roots` recursively. File events are - /// grouped after 300 ms of quiet and handled through the configured - /// discoverer. New candidates are registered. When an existing source or - /// its metadata sidecar changes, the old instance is suspended and - /// unregistered before the replacement is registered. The replacement - /// receives `on_resume` if suspension returned state. A deleted source is - /// unregistered when its module is absent from the discovery results. - /// - /// # Caller obligations - /// - /// `watch()` requires `&Arc` because the spawned background task - /// holds a `Weak` to drive re-discovery; the registry must - /// already live behind `Arc`. Calling on a non-Arc Registry is a - /// compile-time error. - /// - /// # Errors - /// - /// - `Err(ModuleError(code=ReloadFailed))` if the platform watcher cannot - /// be created (kernel resource exhaustion, missing permissions, etc.) - /// - /// # Idempotency - /// - /// Calling `watch()` while already watching is a no-op (returns `Ok(())`). - /// Use [`Self::unwatch`] to stop and re-call `watch()` to pick up new - /// `extension_roots`. - // Keep the async API for existing callers. Startup installs the watcher - // and spawns its Tokio task; the task consumes events after this returns. - // Rust 1.98 split the lint. The unknown-lints allowance keeps the new lint - // name compatible with older toolchains. - #[allow(unknown_lints)] - #[allow(clippy::unused_async)] - #[allow(clippy::unused_async_trait_impl)] - #[cfg(feature = "discovery")] - pub async fn watch(self: &Arc) -> Result<(), ModuleError> { - self.start_watcher(None) - } - - /// Watch configured roots with managed, generation-aware replacement. - #[cfg(feature = "discovery")] - pub fn watch_with_lifecycle( - self: &Arc, - options: ReloadOptions, - ) -> Result<(), ModuleError> { - self.start_watcher(Some(options.validate()?)) - } - - #[cfg(feature = "discovery")] - fn start_watcher( - self: &Arc, - lifecycle: Option, - ) -> Result<(), ModuleError> { - use notify::{RecursiveMode, Watcher}; - - if self.core.read().closed { - return Err(Self::closed_error()); - } - - { - let watcher_slot = self.watcher.lock(); - if watcher_slot.is_some() { - return Ok(()); // already watching - } - } - - let extension_roots: Vec = self.extension_roots.read().clone(); - if extension_roots.is_empty() { - tracing::warn!( - "Registry::watch() called with no extension_roots — call set_extension_roots() first" - ); - return Ok(()); - } - - let (tx, rx) = tokio::sync::mpsc::unbounded_channel::>(); - - let mut watcher = notify::recommended_watcher(move |res: notify::Result| { - // Best-effort send; if the receiver is gone, the watcher will be - // dropped shortly after. - let _ = tx.send(res); - }) - .map_err(|e| { - ModuleError::new( - crate::errors::ErrorCode::ReloadFailed, - format!("Failed to create file watcher: {e}"), - ) - })?; - - for root in &extension_roots { - let path = std::path::Path::new(root); - if let Err(e) = watcher.watch(path, RecursiveMode::Recursive) { - tracing::warn!( - root = %root, - error = %e, - "Registry::watch failed for root, skipping" - ); - } - } - - let core = self.core.read(); - if core.closed { - return Err(Self::closed_error()); - } - let mut watcher_slot = self.watcher.lock(); - if watcher_slot.is_none() { - let runtime = lifecycle_runtime()?; - let handle = runtime.spawn(Self::watch_loop(rx, Arc::downgrade(self), lifecycle)); - *watcher_slot = Some(watcher); - *self.watch_handle.lock() = Some(handle); - } - - Ok(()) - } - - /// Background task body that consumes notify events and applies each - /// debounced batch of changed paths. Exits when the receiver channel - /// closes or the `Weak` can no longer be upgraded. - #[cfg(feature = "discovery")] - async fn watch_loop( - mut rx: tokio::sync::mpsc::UnboundedReceiver>, - weak: std::sync::Weak, - lifecycle: Option, - ) { - use std::time::Duration; - - const DEBOUNCE: Duration = Duration::from_millis(300); - - fn relevant(event: ¬ify::Event) -> bool { - matches!( - event.kind, - notify::EventKind::Create(_) - | notify::EventKind::Modify(_) - | notify::EventKind::Remove(_) - ) - } - - while let Some(res) = rx.recv().await { - let Ok(event) = res else { - continue; - }; - if !relevant(&event) { - continue; - } - // Collapse a burst (editors writing through temp file + rename) - // into one pass, keeping every path the burst touched. - let mut paths: Vec = event.paths; - while let Ok(Some(res)) = tokio::time::timeout(DEBOUNCE, rx.recv()).await { - if let Ok(event) = res { - if relevant(&event) { - paths.extend(event.paths); - } - } - } - - let Some(reg) = weak.upgrade() else { - break; - }; - let task = tokio::spawn(async move { reg.apply_file_changes(&paths, lifecycle).await }); - if let Ok(Err(e)) = task.await { - tracing::warn!( - error = %e.message, - "Registry watch: applying file changes failed during hot-reload" - ); - } - } - } - - /// Apply a batch of changed file paths: register new modules, replace the - /// modules whose source (or `_meta.yaml` sidecar) changed, and unregister - /// those whose source file is gone. - #[cfg(feature = "discovery")] - async fn apply_file_changes( - self: &Arc, - paths: &[std::path::PathBuf], - lifecycle: Option, - ) -> Result<(), ModuleError> { - let changed: HashSet = - paths.iter().map(|p| normalize_watched_path(p)).collect(); - let touches = |source: &str| { - let source = normalize_watched_path(std::path::Path::new(source)); - if changed.contains(&source) { - return true; - } - let (Some(dir), Some(stem)) = (source.parent(), source.file_stem()) else { - return false; - }; - changed.contains(&dir.join(format!("{}_meta.yaml", stem.to_string_lossy()))) - }; - - let discovered = self.run_discoverer().await?; - - let removed: Vec = { - let core = self.core.read(); - core.sources - .iter() - .filter(|(id, source)| { - !std::path::Path::new(source).exists() - && touches(source) - && !discovered.iter().any(|dm| &dm.name == *id) - }) - .map(|(id, _)| id.clone()) - .collect() - }; - for id in removed { - self.safe_unregister(&id, 5000).await?; - } - - let batch_ids = discovered.iter().map(|entry| entry.name.clone()).collect(); - for dm in discovered { - if !self.has(&dm.name) { - self.register_discovered_batch( - std::iter::once(dm), - &batch_ids, - &HashMap::new(), - true, - ) - .await; - } else if touches(&dm.source) { - if let Some(options) = lifecycle { - self.start_managed_reload_with_candidate( - vec![dm.name.clone()], - options, - Some(dm), - )? - .wait(None) - .await?; - } else { - self.replace_discovered(dm, &batch_ids).await?; - } - } - } - Ok(()) - } - - /// Replace a registered module with a freshly discovered instance, - /// handing its `on_suspend` state to the new instance's `on_resume`. The - /// previous instance is put back if the new one fails to register. - #[cfg(feature = "discovery")] - async fn replace_discovered( - &self, - dm: DiscoveredModule, - batch_ids: &HashSet, - ) -> Result<(), ModuleError> { - let name = dm.name.clone(); - let Some(previous) = self.unload_for_reload(&name).await? else { - return Ok(()); - }; - let states: HashMap<_, _> = previous - .state - .as_ref() - .map(|state| (name.clone(), state.clone())) - .into_iter() - .collect(); - if self - .register_discovered_batch(std::iter::once(dm), batch_ids, &states, true) - .await - == 0 - { - tracing::warn!( - module_id = %name, - "Registry watch: the changed module failed to register; keeping the previous instance" - ); - let restoration = self.restore_reload(&name, previous).await; - if let Some(emitter) = self.event_emitter.read().clone() { - emitter.emit_delivery_semantics(ApCoreEvent::with_module( - "apcore.registry.module_reload_failed", - serde_json::json!({ - "operation_id": uuid::Uuid::new_v4().to_string(), - "phase": "loading", "error_code": "RELOAD_FAILED", - "compensation": if restoration.is_ok() { "restored" } else { "failed" }, - }), - &name, - "error", - )); - } - restoration?; - - return Ok(()); - } - - Ok(()) - } - - /// Stop filesystem watching. The background task is aborted and the - /// platform watcher is dropped. Idempotent — calling on a non-watching - /// Registry is a no-op. - #[cfg(feature = "discovery")] - pub fn unwatch(&self) { - self.stop_watching(); - } - - #[cfg(feature = "discovery")] - fn stop_watching(&self) -> Option> { - let (watcher, handle) = { - let mut watcher = self.watcher.lock(); - (watcher.take(), self.watch_handle.lock().take()) - }; - drop(watcher); - if let Some(handle) = &handle { - handle.abort(); - } - handle - } - /// Discover modules using the internally-set discoverer. /// /// Returns the number of newly registered modules. diff --git a/rust/tests/core_profile.rs b/rust/tests/core_profile.rs index 12362802..06670fd8 100644 --- a/rust/tests/core_profile.rs +++ b/rust/tests/core_profile.rs @@ -189,6 +189,6 @@ fn a_custom_strategy_without_the_builtin_gate_reports_that_boundary() { build_minimal_strategy(), ); let state = executor.governance_state(); - assert!(state.policy_strict); + assert!(!state.policy_strict); assert!(!state.builtin_approval_gate_wired); } From 0384a3d4e7688c47eaa1feea6032fb4739813f20 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:31:40 +0800 Subject: [PATCH 05/10] fix(typescript): report explicit policy for a gate-less strategy Signed-off-by: tercel --- typescript/src/executor.ts | 2 +- typescript/tests/test-governance-state.test.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/typescript/src/executor.ts b/typescript/src/executor.ts index 6cc1d3c3..0e40d74e 100644 --- a/typescript/src/executor.ts +++ b/typescript/src/executor.ts @@ -826,7 +826,7 @@ export class Executor { : this._approvalHandler !== null; const policyStrict = builtinApprovalGateWired ? approvalGates.every((gate) => gate.policy.strict) - : (this._policy ?? DEFAULT_EXECUTION_POLICY).strict; + : this._policy?.strict === true; // PROTOCOL_SPEC 6.6.5.1. The approval conjunct carries // `allControlModulesRequireApproval` because `approval_gate` is per-module diff --git a/typescript/tests/test-governance-state.test.ts b/typescript/tests/test-governance-state.test.ts index b62b7c5f..b70d9346 100644 --- a/typescript/tests/test-governance-state.test.ts +++ b/typescript/tests/test-governance-state.test.ts @@ -57,6 +57,7 @@ describe('governanceState — registration observations', () => { const strategy = new ExecutionStrategy('explicitly-gateless', []); const state = new Executor({ registry: c.registry, strategy }).governanceState(); expect(state.builtinApprovalGateWired).toBe(false); + expect(state.policyStrict).toBe(false); expect(state.controlModulesRegistered).toBe(true); expect(state.unprotectedControlSurface).toBe(true); }); From dc61dd575a3d76a113f55a84175b6f36ba35e894 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:39:43 +0800 Subject: [PATCH 06/10] refactor(python): isolate file adapters and finish sync cleanup Signed-off-by: tercel --- python/src/apcore/acl.py | 256 +---------------- python/src/apcore/acl_loader.py | 263 ++++++++++++++++++ python/src/apcore/builtin_steps.py | 21 +- python/src/apcore/registry/registry.py | 99 +------ python/src/apcore/registry/scanner.py | 28 ++ python/src/apcore/registry/watcher.py | 87 ++++++ .../conformance/test_acl_rule_key_closure.py | 2 +- python/tests/registry/test_registry.py | 4 +- .../test_acl_argument_scoped_approval.py | 2 +- python/tests/test_full_assembly.py | 10 +- python/tests/test_global_timeout.py | 45 +++ 11 files changed, 467 insertions(+), 350 deletions(-) create mode 100644 python/src/apcore/acl_loader.py create mode 100644 python/src/apcore/registry/watcher.py diff --git a/python/src/apcore/acl.py b/python/src/apcore/acl.py index 88904ab7..fd028dff 100644 --- a/python/src/apcore/acl.py +++ b/python/src/apcore/acl.py @@ -9,13 +9,10 @@ import contextvars import inspect import logging -import os -import stat import threading from copy import deepcopy from dataclasses import asdict, dataclass, field from datetime import datetime, timezone -from pathlib import Path from typing import Any, Callable, ClassVar from apcore.acl_handlers import ( @@ -37,7 +34,7 @@ ) from apcore.config import Config from apcore.context import Context -from apcore.errors import ACLRuleError, ConfigError, ConfigNotFoundError +from apcore.errors import ACLRuleError from apcore.utils.pattern import match_pattern __all__ = [ @@ -458,41 +455,6 @@ def __post_init__(self) -> None: _validate_rule(self, where="ACLRule") -#: The complete set of keys an ACL rule may carry (PROTOCOL_SPEC §6.1). -#: Closed on purpose: a key nothing evaluates is otherwise dropped in silence, -#: which widens an ``allow`` rule with no warning (#107). ``approval`` joined -#: the set in spec v1.28.0 (§6.1.6) — adding it was only safe *because* the set -#: was closed first, since an SDK that still dropped unknown keys would read a -#: ``deny``-with-``approval`` rule as a bare rule and act on half of it. -_RULE_KEYS: frozenset[str] = frozenset({"callers", "targets", "effect", "description", "conditions", "approval"}) - -#: Reserved in earlier revisions of §6.1 and evaluated by no implementation. -#: Rejected like any other unknown key, but named as reserved in the message: -#: an operator who wrote ``actions: ["describe"]`` meant to restrict the rule and -#: is better served by "not implemented" than by "unknown key". -_RESERVED_RULE_KEYS: frozenset[str] = frozenset({"id", "actions", "priority"}) - - -def _reject_unknown_rule_keys(index: int, raw_rule: dict) -> None: - """Raise ``ACLRuleError`` for any key outside :data:`_RULE_KEYS`.""" - unknown = sorted(set(raw_rule) - _RULE_KEYS) - if not unknown: - return - reserved = [k for k in unknown if k in _RESERVED_RULE_KEYS] - other = [k for k in unknown if k not in _RESERVED_RULE_KEYS] - parts = [] - if reserved: - names = ", ".join(repr(k) for k in reserved) - parts.append(f"{names} reserved for a future specification version and evaluated " f"by no implementation") - if other: - parts.append(f"{', '.join(repr(k) for k in other)} unrecognised") - raise ACLRuleError( - f"Rule {index} carries {'; '.join(parts)}. The rule key set is closed " - f"({', '.join(sorted(_RULE_KEYS))}); a key nothing evaluates would be " - f"dropped silently and leave the rule wider than written." - ) - - @dataclass(frozen=True) class AuditEntry: """Structured record of an ACL check decision.""" @@ -622,7 +584,6 @@ class _Fault: #: The three settings of an ACL file's `audit:` block, and their defaults. _AUDIT_FIELDS = ("enabled", "include_denied", "log_level") -_AUDIT_DEFAULTS: dict[str, Any] = {"enabled": True, "include_denied": True, "log_level": "info"} _AUDIT_LEVELS = { "trace": logging.DEBUG, "debug": logging.DEBUG, @@ -741,66 +702,6 @@ def _report_failure(self, exc: BaseException) -> None: ) -def _parse_audit_block(data: dict[str, Any], yaml_path: str) -> dict[str, Any] | None: - """Validate an ACL file's ``audit:`` block (§6.3.2 requirement 8). - - Returns ``None`` only when the document declares no ``audit`` key at all — - the distinction requirement 2 turns on, because `enabled` defaults to - ``True`` and reading the merged view would switch a log record per check on - for every ACL file in existence. - - **Presence, not truthiness.** ``audit:`` with nothing under it parses to - ``None``, and the operator still wrote the block: that is a declaration with - every setting at its default, not an absence. - - Validates the SUBTREE only: types and unknown keys inside the block. Every - other unrecognised root key in an ACL file keeps being ignored. - """ - if "audit" not in data: - return None - raw = data["audit"] - if raw is None: - return dict(_AUDIT_DEFAULTS) - if not isinstance(raw, dict): - raise ConfigError( - f"{yaml_path}: 'audit' must be a mapping (PROTOCOL_SPEC §6.3.2), got " f"{type(raw).__name__}" - ) - - unknown = sorted(set(raw) - set(_AUDIT_FIELDS)) - if unknown: - raise ConfigError( - f"{yaml_path}: unknown key(s) in the 'audit' block: {', '.join(unknown)}. " - f"The block accepts exactly {', '.join(_AUDIT_FIELDS)} " - f"($defs/AuditConfig in schemas/acl-config.schema.json)." - ) - - config = dict(_AUDIT_DEFAULTS) - for key in ("enabled", "include_denied"): - if key in raw: - if not isinstance(raw[key], bool): - raise ConfigError(f"{yaml_path}: 'audit.{key}' must be a boolean, got {raw[key]!r}") - config[key] = raw[key] - if "log_level" in raw: - if raw["log_level"] not in _AUDIT_LEVELS: - raise ConfigError( - f"{yaml_path}: 'audit.log_level' must be one of " - f"{', '.join(_AUDIT_LEVELS)}, got {raw['log_level']!r}" - ) - config["log_level"] = raw["log_level"] - - if not config["include_denied"]: - # §6.3.2 requirement 6 — a notice, not a refusal. It withholds the - # security-relevant half of the record, so an operator who wrote it - # deliberately gets told once per load rather than stopped. - _logger.warning( - "%s sets audit.include_denied: false, so DENIED access attempts will not be " - "recorded by the default audit sink (PROTOCOL_SPEC §6.3.2 requirement 6). " - "Allowed calls are still recorded. Remove the entry to restore denials.", - yaml_path, - ) - return config - - def _warn_audit_block_overridden( callback: Callable[[AuditEntry], None] | None, config: dict[str, Any] | None, @@ -1635,125 +1536,9 @@ def load( shape (spec v1.31.0, #112), which loaded clean and left the rule inert. """ - if not os.path.isfile(yaml_path): - raise ConfigNotFoundError(config_path=yaml_path) - - import yaml - - with open(yaml_path, encoding="utf-8") as f: - try: - data = yaml.safe_load(f) - except yaml.YAMLError as e: - raise ACLRuleError(f"Invalid YAML in {yaml_path}: {e}") from e - - if not isinstance(data, dict): - raise ACLRuleError(f"ACL config must be a mapping, got {type(data).__name__}") - - # PROTOCOL_SPEC §9.2.4.1 (apcore#118): an `audit:` block in an ACL file - # has never been read. Deleting it from `acl-config.schema.json` would - # produce no signal at all — no implementation validates an ACL file - # against that schema, and this loader parses into an open mapping and - # takes the fields it wants, so any unknown root key is dropped in - # silence. The diagnostic therefore has to live here. - # - # Scoped to `audit` deliberately: §6.3.2 requirement 8 validates this - # SUBTREE and nothing else, so every other unrecognised root key in an - # ACL file keeps being ignored exactly as before. This was never - # unknown-key closure for ACL files, and wiring the block does not make - # it one. - # - # The §9.2.4.1 deprecation notice that used to stand here is gone: spec - # v1.45.0 gave the block a delivery contract, and a key that has gained - # a consumer must stop being announced as going away. - audit_config = _parse_audit_block(data, yaml_path) - - # PROTOCOL_SPEC §6.2.1: `default_effect` is judged FIRST, before any - # rule, at every door. It is not a rule and has no index, so the rule - # ordering below never reaches it — and this used to be left entirely to - # the `ACL` constructor at the bottom of this method, which runs after - # every rule has been parsed and validated, so a file carrying a bad - # `default_effect` AND a bad rule 0 was refused for the RULE here and - # for `default_effect` through direct construction: one configuration, - # two answers, from two doors of the same SDK. - # - # Placed above the `rules` checks and not merely above the loop: - # "first" is ahead of the file-level checks on the `rules` COLLECTION - # too, so a document both missing `rules` and carrying a bad - # `default_effect` names the `default_effect`. - default_effect: str = data.get("default_effect", "deny") - _validate_default_effect(default_effect) - - if "rules" not in data: - raise ACLRuleError("ACL config missing required 'rules' key") - - raw_rules = data["rules"] - if not isinstance(raw_rules, list): - raise ACLRuleError(f"'rules' must be a list, got {type(raw_rules).__name__}") - - rules: list[ACLRule] = [] - - for i, raw_rule in enumerate(raw_rules): - if not isinstance(raw_rule, dict): - raise ACLRuleError(f"Rule {i} must be a mapping, got {type(raw_rule).__name__}") - - for key in ("callers", "targets", "effect"): - if key not in raw_rule: - raise ACLRuleError(f"Rule {i} missing required key '{key}'") - - # A missing key was already rejected above so an omission cannot - # render a rule inert; an unknown key is the same hazard pointing - # the other way, and was dropped in silence until #107. - _reject_unknown_rule_keys(i, raw_rule) - - # PROTOCOL_SPEC §6.1.5. Checked here as well as in - # ACLRule.__post_init__ so a file fault names the offending rule's - # index, which the dataclass cannot know — the same split - # _validate_approval already uses. - effect = raw_rule["effect"] - _validate_effect(effect, where=f"Rule {i}") - - # PROTOCOL_SPEC §6.1.6. Checked here as well as in ACLRule.__post_init__ - # so a file fault names the offending rule's index, which the - # dataclass cannot know. - approval = raw_rule.get("approval", APPROVAL_NOT_REQUIRED) - _validate_approval(approval, effect, where=f"Rule {i}") - - # PROTOCOL_SPEC §6.2.1 (spec v1.31.0, #112). Checked here as well as - # in ACLRule.__post_init__ so a file fault names the offending rule's - # index, which the dataclass cannot know — the same split - # _validate_effect and _validate_approval already use. `ACL.load` - # rejected an OMITTED callers / targets and permitted an EMPTY one, - # so a plain YAML file reached the fail-open; the arity closure is - # what shuts that route. - callers = raw_rule["callers"] - if not isinstance(callers, list): - raise ACLRuleError(f"Rule {i} 'callers' must be a list, got {type(callers).__name__}") - _validate_pattern_array(callers, "callers", where=f"Rule {i}") - - targets = raw_rule["targets"] - if not isinstance(targets, list): - raise ACLRuleError(f"Rule {i} 'targets' must be a list, got {type(targets).__name__}") - _validate_pattern_array(targets, "targets", where=f"Rule {i}") - - raw_conditions = raw_rule.get("conditions") - if raw_conditions is not None and not isinstance(raw_conditions, dict): - # A YAML file cannot reach §6.1.1 case 5 — the parser rejects it - # here, as apcore-typescript's `_parseAclRule` does. Direct - # construction and add_rule() still can, which is what the - # runtime precheck (§6.1.4) is for. - raise ACLRuleError(f"Rule {i} 'conditions' must be a mapping, got {type(raw_conditions).__name__}") - - rules.append( - ACLRule( - callers=callers, - targets=targets, - effect=effect, - description=raw_rule.get("description", ""), - conditions=raw_conditions, - approval=approval, - ) - ) + from apcore.acl_loader import read_acl_file + rules, default_effect, audit_config = read_acl_file(yaml_path) acl = cls( rules=rules, default_effect=default_effect, @@ -1800,39 +1585,10 @@ def discover(cls, config: Config) -> ACL | None: ConfigError: If the configured policy path cannot be inspected or is not a file. ACLRuleError: If the ACL file is structurally invalid. """ - root = config.get("acl.root", Config.get_default("acl.root")) - if root is None: - return None - if root == "": - root = Config.get_default("acl.root") - - path = Path(config.resolve_path(str(root))) - mode = cls._discovery_mode(path) - if mode is None: - return None - if stat.S_ISDIR(mode): - path /= "global_acl.yaml" - mode = cls._discovery_mode(path) - if mode is None: - return None - if not stat.S_ISREG(mode): - raise ConfigError(f"ACL path {str(path)!r} is not a regular file") - return cls.load(str(path)) + from apcore.acl_loader import find_acl_file - @staticmethod - def _discovery_mode(path: Path) -> int | None: - try: - mode = path.lstat().st_mode - except FileNotFoundError: - return None - except OSError as error: - raise ConfigError(f"Cannot inspect ACL path {str(path)!r}: {error}") from error - if stat.S_ISLNK(mode): - try: - return path.stat().st_mode - except OSError as error: - raise ConfigError(f"Cannot resolve ACL path {str(path)!r}: {error}") from error - return mode + path = find_acl_file(config) + return cls.load(path) if path is not None else None def check( self, diff --git a/python/src/apcore/acl_loader.py b/python/src/apcore/acl_loader.py new file mode 100644 index 00000000..c842cc19 --- /dev/null +++ b/python/src/apcore/acl_loader.py @@ -0,0 +1,263 @@ +"""Read and validate filesystem-backed ACL configuration.""" + +from __future__ import annotations + +import logging +import os +import stat +from pathlib import Path +from typing import Any + +from apcore.acl import ( + APPROVAL_NOT_REQUIRED, + ACLRule, + _AUDIT_FIELDS, + _AUDIT_LEVELS, + _validate_approval, + _validate_default_effect, + _validate_effect, + _validate_pattern_array, +) +from apcore.config import Config +from apcore.errors import ACLRuleError, ConfigError, ConfigNotFoundError + +# Keep the ACL diagnostics on the same logger for file-backed and in-memory use. +_logger = logging.getLogger("apcore.acl") + +_AUDIT_DEFAULTS: dict[str, Any] = {"enabled": True, "include_denied": True, "log_level": "info"} + +#: The complete set of keys an ACL rule may carry (PROTOCOL_SPEC §6.1). +#: Closed on purpose: a key nothing evaluates is otherwise dropped in silence, +#: which widens an ``allow`` rule with no warning (#107). ``approval`` joined +#: the set in spec v1.28.0 (§6.1.6) — adding it was only safe *because* the set +#: was closed first, since an SDK that still dropped unknown keys would read a +#: ``deny``-with-``approval`` rule as a bare rule and act on half of it. +_RULE_KEYS: frozenset[str] = frozenset({"callers", "targets", "effect", "description", "conditions", "approval"}) + +#: Reserved in earlier revisions of §6.1 and evaluated by no implementation. +#: Rejected like any other unknown key, but named as reserved in the message: +#: an operator who wrote ``actions: ["describe"]`` meant to restrict the rule and +#: is better served by "not implemented" than by "unknown key". +_RESERVED_RULE_KEYS: frozenset[str] = frozenset({"id", "actions", "priority"}) + + +def _reject_unknown_rule_keys(index: int, raw_rule: dict) -> None: + """Raise ``ACLRuleError`` for any key outside :data:`_RULE_KEYS`.""" + unknown = sorted(set(raw_rule) - _RULE_KEYS) + if not unknown: + return + reserved = [k for k in unknown if k in _RESERVED_RULE_KEYS] + other = [k for k in unknown if k not in _RESERVED_RULE_KEYS] + parts = [] + if reserved: + names = ", ".join(repr(k) for k in reserved) + parts.append(f"{names} reserved for a future specification version and evaluated by no implementation") + if other: + parts.append(f"{', '.join(repr(k) for k in other)} unrecognised") + raise ACLRuleError( + f"Rule {index} carries {'; '.join(parts)}. The rule key set is closed " + f"({', '.join(sorted(_RULE_KEYS))}); a key nothing evaluates would be " + f"dropped silently and leave the rule wider than written." + ) + + +def _parse_audit_block(data: dict[str, Any], yaml_path: str) -> dict[str, Any] | None: + """Validate an ACL file's ``audit:`` block (§6.3.2 requirement 8). + + Returns ``None`` only when the document declares no ``audit`` key at all — + the distinction requirement 2 turns on, because `enabled` defaults to + ``True`` and reading the merged view would switch a log record per check on + for every ACL file in existence. + + **Presence, not truthiness.** ``audit:`` with nothing under it parses to + ``None``, and the operator still wrote the block: that is a declaration with + every setting at its default, not an absence. + + Validates the SUBTREE only: types and unknown keys inside the block. Every + other unrecognised root key in an ACL file keeps being ignored. + """ + if "audit" not in data: + return None + raw = data["audit"] + if raw is None: + return dict(_AUDIT_DEFAULTS) + if not isinstance(raw, dict): + raise ConfigError(f"{yaml_path}: 'audit' must be a mapping (PROTOCOL_SPEC §6.3.2), got {type(raw).__name__}") + + unknown = sorted(set(raw) - set(_AUDIT_FIELDS)) + if unknown: + raise ConfigError( + f"{yaml_path}: unknown key(s) in the 'audit' block: {', '.join(unknown)}. " + f"The block accepts exactly {', '.join(_AUDIT_FIELDS)} " + f"($defs/AuditConfig in schemas/acl-config.schema.json)." + ) + + config = dict(_AUDIT_DEFAULTS) + for key in ("enabled", "include_denied"): + if key in raw: + if not isinstance(raw[key], bool): + raise ConfigError(f"{yaml_path}: 'audit.{key}' must be a boolean, got {raw[key]!r}") + config[key] = raw[key] + if "log_level" in raw: + if raw["log_level"] not in _AUDIT_LEVELS: + raise ConfigError( + f"{yaml_path}: 'audit.log_level' must be one of {', '.join(_AUDIT_LEVELS)}, got {raw['log_level']!r}" + ) + config["log_level"] = raw["log_level"] + + if not config["include_denied"]: + # §6.3.2 requirement 6 — a notice, not a refusal. It withholds the + # security-relevant half of the record, so an operator who wrote it + # deliberately gets told once per load rather than stopped. + _logger.warning( + "%s sets audit.include_denied: false, so DENIED access attempts will not be " + "recorded by the default audit sink (PROTOCOL_SPEC §6.3.2 requirement 6). " + "Allowed calls are still recorded. Remove the entry to restore denials.", + yaml_path, + ) + return config + + +def read_acl_file(yaml_path: str) -> tuple[list[ACLRule], str, dict[str, Any] | None]: + """Parse one ACL file before publishing its rules or audit settings.""" + if not os.path.isfile(yaml_path): + raise ConfigNotFoundError(config_path=yaml_path) + + import yaml + + with open(yaml_path, encoding="utf-8") as f: + try: + data = yaml.safe_load(f) + except yaml.YAMLError as e: + raise ACLRuleError(f"Invalid YAML in {yaml_path}: {e}") from e + + if not isinstance(data, dict): + raise ACLRuleError(f"ACL config must be a mapping, got {type(data).__name__}") + + audit_config = _parse_audit_block(data, yaml_path) + + # PROTOCOL_SPEC §6.2.1: `default_effect` is judged FIRST, before any + # rule, at every door. It is not a rule and has no index, so the rule + # ordering below never reaches it — and this used to be left entirely to + # the `ACL` constructor at the bottom of this method, which runs after + # every rule has been parsed and validated, so a file carrying a bad + # `default_effect` AND a bad rule 0 was refused for the RULE here and + # for `default_effect` through direct construction: one configuration, + # two answers, from two doors of the same SDK. + # + # Placed above the `rules` checks and not merely above the loop: + # "first" is ahead of the file-level checks on the `rules` COLLECTION + # too, so a document both missing `rules` and carrying a bad + # `default_effect` names the `default_effect`. + default_effect: str = data.get("default_effect", "deny") + _validate_default_effect(default_effect) + + if "rules" not in data: + raise ACLRuleError("ACL config missing required 'rules' key") + + raw_rules = data["rules"] + if not isinstance(raw_rules, list): + raise ACLRuleError(f"'rules' must be a list, got {type(raw_rules).__name__}") + + rules: list[ACLRule] = [] + + for i, raw_rule in enumerate(raw_rules): + if not isinstance(raw_rule, dict): + raise ACLRuleError(f"Rule {i} must be a mapping, got {type(raw_rule).__name__}") + + for key in ("callers", "targets", "effect"): + if key not in raw_rule: + raise ACLRuleError(f"Rule {i} missing required key '{key}'") + + # A missing key was already rejected above so an omission cannot + # render a rule inert; an unknown key is the same hazard pointing + # the other way, and was dropped in silence until #107. + _reject_unknown_rule_keys(i, raw_rule) + + # PROTOCOL_SPEC §6.1.5. Checked here as well as in + # ACLRule.__post_init__ so a file fault names the offending rule's + # index, which the dataclass cannot know — the same split + # _validate_approval already uses. + effect = raw_rule["effect"] + _validate_effect(effect, where=f"Rule {i}") + + # PROTOCOL_SPEC §6.1.6. Checked here as well as in ACLRule.__post_init__ + # so a file fault names the offending rule's index, which the + # dataclass cannot know. + approval = raw_rule.get("approval", APPROVAL_NOT_REQUIRED) + _validate_approval(approval, effect, where=f"Rule {i}") + + # PROTOCOL_SPEC §6.2.1 (spec v1.31.0, #112). Checked here as well as + # in ACLRule.__post_init__ so a file fault names the offending rule's + # index, which the dataclass cannot know — the same split + # _validate_effect and _validate_approval already use. `ACL.load` + # rejected an OMITTED callers / targets and permitted an EMPTY one, + # so a plain YAML file reached the fail-open; the arity closure is + # what shuts that route. + callers = raw_rule["callers"] + if not isinstance(callers, list): + raise ACLRuleError(f"Rule {i} 'callers' must be a list, got {type(callers).__name__}") + _validate_pattern_array(callers, "callers", where=f"Rule {i}") + + targets = raw_rule["targets"] + if not isinstance(targets, list): + raise ACLRuleError(f"Rule {i} 'targets' must be a list, got {type(targets).__name__}") + _validate_pattern_array(targets, "targets", where=f"Rule {i}") + + raw_conditions = raw_rule.get("conditions") + if raw_conditions is not None and not isinstance(raw_conditions, dict): + # A YAML file cannot reach §6.1.1 case 5 — the parser rejects it + # here, as apcore-typescript's `_parseAclRule` does. Direct + # construction and add_rule() still can, which is what the + # runtime precheck (§6.1.4) is for. + raise ACLRuleError(f"Rule {i} 'conditions' must be a mapping, got {type(raw_conditions).__name__}") + + rules.append( + ACLRule( + callers=callers, + targets=targets, + effect=effect, + description=raw_rule.get("description", ""), + conditions=raw_conditions, + approval=approval, + ) + ) + + return rules, default_effect, audit_config + + +def find_acl_file(config: Config) -> str | None: + """Resolve a configured file or the global ACL under its root directory.""" + root = config.get("acl.root", Config.get_default("acl.root")) + if root is None: + return None + if root == "": + root = Config.get_default("acl.root") + + path = Path(config.resolve_path(str(root))) + mode = _discovery_mode(path) + if mode is None: + return None + if stat.S_ISDIR(mode): + path /= "global_acl.yaml" + mode = _discovery_mode(path) + if mode is None: + return None + if not stat.S_ISREG(mode): + raise ConfigError(f"ACL path {str(path)!r} is not a regular file") + return str(path) + + +def _discovery_mode(path: Path) -> int | None: + try: + mode = path.lstat().st_mode + except FileNotFoundError: + return None + except OSError as error: + raise ConfigError(f"Cannot inspect ACL path {str(path)!r}: {error}") from error + if stat.S_ISLNK(mode): + try: + return path.stat().st_mode + except OSError as error: + raise ConfigError(f"Cannot resolve ACL path {str(path)!r}: {error}") from error + return mode diff --git a/python/src/apcore/builtin_steps.py b/python/src/apcore/builtin_steps.py index 6e2e9d52..3f6ac088 100644 --- a/python/src/apcore/builtin_steps.py +++ b/python/src/apcore/builtin_steps.py @@ -1358,7 +1358,7 @@ async def execute(self, ctx: PipelineContext) -> StepResult: coro = execute(inputs, ctx.context) else: loop = asyncio.get_event_loop() - coro = loop.run_in_executor(None, execute, inputs, ctx.context) + coro = loop.run_in_executor(None, _execute_sync_module, execute, inputs, ctx.context) task = ctx.module_task = asyncio.ensure_future(coro) # Consume late failures even when the call was cancelled while @@ -1380,6 +1380,8 @@ async def execute(self, ctx: PipelineContext) -> StepResult: else: # Cancelling the asyncio wrapper does not stop a worker thread. output = await task if is_async else await asyncio.shield(task) + if not is_async and isinstance(output, _SyncExecutionFailure): + raise output.error output = normalize_module_output(output) if output is None: raise ModuleExecuteError(module_id=ctx.module_id, message="Return value cannot be None") @@ -1397,6 +1399,23 @@ async def execute(self, ctx: PipelineContext) -> StepResult: return StepResult(action="continue") +@dataclasses.dataclass(frozen=True, slots=True) +class _SyncExecutionFailure: + error: BaseException + + +def _execute_sync_module( + execute: Callable[[dict[str, Any], Context], Any], inputs: dict[str, Any], context: Context +) -> Any: + try: + return execute(inputs, context) + except BaseException as error: + # The sync bridge can park or close the loop before its next-turn + # callbacks run. Transfer a value so a late worker failure can be + # discarded while an active waiter still receives the original error. + return _SyncExecutionFailure(error) + + def _discard_late_execution(task: asyncio.Future[Any]) -> None: """Consume a timed-out invocation's eventual exception or output.""" if not task.cancelled(): diff --git a/python/src/apcore/registry/registry.py b/python/src/apcore/registry/registry.py index 35ad15b4..b80c01e4 100644 --- a/python/src/apcore/registry/registry.py +++ b/python/src/apcore/registry/registry.py @@ -6,7 +6,6 @@ import inspect import json import logging -import os import re import threading import time @@ -54,7 +53,7 @@ merge_module_metadata, parse_dependencies, ) -from apcore.registry.scanner import _companion_metadata_path, _watched_source, scan_extensions, scan_multi_root +from apcore.registry.scanner import scan_extensions, scan_multi_root, scan_watched_source from apcore.registry.types import DependencyInfo, DiscoveredModule, ModuleDescriptor from apcore.registry.validation import validate_module from apcore.registry.version import VersionedStore, matches_version_hint @@ -419,64 +418,6 @@ def _validate_module_id(module_id: str, *, allow_reserved: bool = False) -> None ) -class _ModuleChangeHandler: - """Watchdog event handler for file-system events on extension roots. - - Hoisted to module scope (from an inline class inside ``Registry.watch``) - so it can be unit-tested directly and so the debounce dict stays on a - long-lived object with bounded memory. Registry is held via a weakref to - avoid extending its lifetime beyond the caller's expectation. - """ - - _DEBOUNCE_WINDOW_SEC: float = 0.3 - _MAX_DEBOUNCE_ENTRIES: int = 1024 - _DEBOUNCE_PRUNE_KEEP: int = 256 - - def __init__(self, registry: "Registry") -> None: - import weakref - - self._registry_ref: Any = weakref.ref(registry) - self._debounce_timer: dict[str, float] = {} - - def _registry(self) -> "Registry | None": - return self._registry_ref() - - def _should_process(self, path: str) -> bool: - if not path.endswith(".py"): - return False - now = time.time() - last = self._debounce_timer.get(path, 0.0) - if now - last < self._DEBOUNCE_WINDOW_SEC: - return False - self._debounce_timer[path] = now - # Bounded memory: prune oldest entries when the dict grows too large. - if len(self._debounce_timer) > self._MAX_DEBOUNCE_ENTRIES: - sorted_by_age = sorted(self._debounce_timer.items(), key=lambda kv: kv[1]) - self._debounce_timer = dict(sorted_by_age[-self._DEBOUNCE_PRUNE_KEEP :]) - return True - - def on_modified(self, event: Any) -> None: - if event.is_directory: - return - path = str(event.src_path) - reg = self._registry() - if reg is not None and not reg._defer_watched_change(path) and self._should_process(path): - reg._handle_file_change(path) - - def on_created(self, event: Any) -> None: - self.on_modified(event) - - def on_deleted(self, event: Any) -> None: - if event.is_directory: - return - path = str(event.src_path) - if not path.endswith(".py"): - return - reg = self._registry() - if reg is not None: - reg._handle_file_deletion(path) - - def _run_on_load(module: Any, module_id: str) -> None: """Invoke ``module.on_load()``, refusing an awaitable rather than dropping it. @@ -3439,25 +3380,15 @@ def watch(self, *, lifecycle: ReloadOptions | None = None) -> None: raise InvalidInputError(message="Invalid watch lifecycle policy") if _has_running_loop(): hook_loop = asyncio.get_running_loop() - try: - from watchdog.events import FileSystemEventHandler - from watchdog.observers import Observer # type: ignore[import-not-found] - except ImportError: - raise ImportError("watchdog is required for hot reload. Install it with: pip install watchdog") + from apcore.registry.watcher import load_observer_factory - class WatchdogHandler(_ModuleChangeHandler, FileSystemEventHandler): - pass + create_observer = load_observer_factory() with self._lock: self._require_open() if hasattr(self, "_observer") and self._observer is not None: return - observer = Observer() - handler = WatchdogHandler(self) - for root_config in self._extension_roots: - root_path = root_config.get("root", "") - if root_path and os.path.isdir(root_path): - observer.schedule(handler, root_path, recursive=True) + observer = create_observer(self, self._extension_roots) self._watch_lifecycle = lifecycle self._watch_hook_loop = hook_loop observer.start() @@ -3563,28 +3494,12 @@ def _publish_snapshot(self, module_id: str, registration: _RegistrationSnapshot) def _watched_candidate(self, path: Path) -> DiscoveredModule | None: max_depth, follow_symlinks, ignore_patterns = self._scan_params() - prefixed = len(self._extension_roots) > 1 or any("namespace" in r for r in self._extension_roots) - for root_config in self._extension_roots: - root = Path(root_config["root"]) - source = _watched_source(path, root, max_depth, follow_symlinks, ignore_patterns) - if source is None: - continue - real_root = root.resolve() - canonical_id = str(source.relative_to(real_root).with_suffix("")).replace(os.sep, ".") - namespace = (root_config.get("namespace") or root.name) if prefixed else None - if namespace is not None: - canonical_id = f"{namespace}.{canonical_id}" - candidate = DiscoveredModule( - file_path=source, - canonical_id=canonical_id, - meta_path=_companion_metadata_path(source, real_root, follow_symlinks), - namespace=namespace, - ) + candidate = scan_watched_source(path, self._extension_roots, max_depth, follow_symlinks, ignore_patterns) + if candidate is not None: self._reject_ephemeral_discoveries([candidate]) self._apply_id_map_overrides([candidate]) _validate_module_id(candidate.canonical_id) - return candidate - return None + return candidate def _handle_file_change(self, path: str) -> None: """Handle a file modification or creation event. diff --git a/python/src/apcore/registry/scanner.py b/python/src/apcore/registry/scanner.py index b0c080c4..7ad42e24 100644 --- a/python/src/apcore/registry/scanner.py +++ b/python/src/apcore/registry/scanner.py @@ -55,6 +55,34 @@ def _watched_source( return None +def scan_watched_source( + path: Path, + roots: Sequence[dict[str, Any]], + max_depth: int, + follow_symlinks: bool, + ignore_patterns: Sequence[str], +) -> DiscoveredModule | None: + """Find the first eligible watched source and metadata within the configured roots.""" + prefixed = len(roots) > 1 or any("namespace" in r for r in roots) + for root_config in roots: + root = Path(root_config["root"]) + source = _watched_source(path, root, max_depth, follow_symlinks, ignore_patterns) + if source is None: + continue + real_root = root.resolve() + canonical_id = str(source.relative_to(real_root).with_suffix("")).replace(os.sep, ".") + namespace = (root_config.get("namespace") or root.name) if prefixed else None + if namespace is not None: + canonical_id = f"{namespace}.{canonical_id}" + return DiscoveredModule( + file_path=source, + canonical_id=canonical_id, + meta_path=_companion_metadata_path(source, real_root, follow_symlinks), + namespace=namespace, + ) + return None + + def _companion_metadata_path(module_path: Path, root: Path, follow_symlinks: bool) -> Path | None: candidate = module_path.with_name(f"{module_path.stem}_meta.yaml") if (candidate.is_symlink() and not follow_symlinks) or not candidate.is_file(): diff --git a/python/src/apcore/registry/watcher.py b/python/src/apcore/registry/watcher.py new file mode 100644 index 00000000..bd36c321 --- /dev/null +++ b/python/src/apcore/registry/watcher.py @@ -0,0 +1,87 @@ +"""Optional watchdog integration for filesystem-backed registry reloads.""" + +from __future__ import annotations + +import os +import time +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any +from weakref import ref + +if TYPE_CHECKING: + from watchdog.observers.api import BaseObserver + + from apcore.registry.registry import Registry + + +class _ModuleChangeHandler: + """Debounce extension events and dispatch them without retaining the registry.""" + + _DEBOUNCE_WINDOW_SEC: float = 0.3 + _MAX_DEBOUNCE_ENTRIES: int = 1024 + _DEBOUNCE_PRUNE_KEEP: int = 256 + + def __init__(self, registry: Registry) -> None: + self._registry_ref = ref(registry) + self._debounce_timer: dict[str, float] = {} + + def _registry(self) -> Registry | None: + return self._registry_ref() + + def _should_process(self, path: str) -> bool: + if not path.endswith(".py"): + return False + now = time.time() + last = self._debounce_timer.get(path, 0.0) + if now - last < self._DEBOUNCE_WINDOW_SEC: + return False + self._debounce_timer[path] = now + # Bounded memory: prune oldest entries when the dict grows too large. + if len(self._debounce_timer) > self._MAX_DEBOUNCE_ENTRIES: + sorted_by_age = sorted(self._debounce_timer.items(), key=lambda kv: kv[1]) + self._debounce_timer = dict(sorted_by_age[-self._DEBOUNCE_PRUNE_KEEP :]) + return True + + def on_modified(self, event: Any) -> None: + if event.is_directory: + return + path = str(event.src_path) + reg = self._registry() + if reg is not None and not reg._defer_watched_change(path) and self._should_process(path): + reg._handle_file_change(path) + + def on_created(self, event: Any) -> None: + self.on_modified(event) + + def on_deleted(self, event: Any) -> None: + if event.is_directory: + return + path = str(event.src_path) + if not path.endswith(".py"): + return + reg = self._registry() + if reg is not None: + reg._handle_file_deletion(path) + + +def load_observer_factory() -> Callable[[Registry, Sequence[dict[str, Any]]], BaseObserver]: + """Import watchdog before taking the registry lock and prepare its observer factory.""" + try: + from watchdog.events import FileSystemEventHandler + from watchdog.observers import Observer # type: ignore[import-not-found] + except ImportError: + raise ImportError("watchdog is required for hot reload. Install it with: pip install watchdog") + + class WatchdogHandler(_ModuleChangeHandler, FileSystemEventHandler): + pass + + def create_observer(registry: Registry, roots: Sequence[dict[str, Any]]) -> BaseObserver: + observer = Observer() + handler = WatchdogHandler(registry) + for root_config in roots: + root_path = root_config.get("root", "") + if root_path and os.path.isdir(root_path): + observer.schedule(handler, root_path, recursive=True) + return observer + + return create_observer diff --git a/python/tests/conformance/test_acl_rule_key_closure.py b/python/tests/conformance/test_acl_rule_key_closure.py index 8600e9eb..d0df30e6 100644 --- a/python/tests/conformance/test_acl_rule_key_closure.py +++ b/python/tests/conformance/test_acl_rule_key_closure.py @@ -40,7 +40,7 @@ def _cases() -> list[dict[str, Any]]: def test_closed_key_set_matches_the_fixture() -> None: """The canonical set lives in the fixture, not in this SDK.""" - from apcore.acl import _RESERVED_RULE_KEYS, _RULE_KEYS + from apcore.acl_loader import _RESERVED_RULE_KEYS, _RULE_KEYS fixture = load_fixture(FIXTURE) assert set(fixture["closed_rule_keys"]) == set(_RULE_KEYS) diff --git a/python/tests/registry/test_registry.py b/python/tests/registry/test_registry.py index 3202f04c..5aed06e2 100644 --- a/python/tests/registry/test_registry.py +++ b/python/tests/registry/test_registry.py @@ -1163,7 +1163,7 @@ def test_unwatch_safe_when_not_watching(self) -> None: def test_module_change_handler_is_module_level(self) -> None: """_ModuleChangeHandler is hoisted out of watch() so it is testable.""" - from apcore.registry.registry import _ModuleChangeHandler + from apcore.registry.watcher import _ModuleChangeHandler reg = Registry() handler = _ModuleChangeHandler(reg) @@ -1173,7 +1173,7 @@ def test_module_change_handler_is_module_level(self) -> None: def test_module_change_handler_debounce_bounds_memory(self) -> None: """Debounce dict is pruned when it exceeds the bound.""" - from apcore.registry.registry import _ModuleChangeHandler + from apcore.registry.watcher import _ModuleChangeHandler reg = Registry() handler = _ModuleChangeHandler(reg) diff --git a/python/tests/test_acl_argument_scoped_approval.py b/python/tests/test_acl_argument_scoped_approval.py index 64823fd5..5efe5e8a 100644 --- a/python/tests/test_acl_argument_scoped_approval.py +++ b/python/tests/test_acl_argument_scoped_approval.py @@ -133,7 +133,7 @@ def test_loader_accepts_explicit_not_required(self) -> None: def test_approval_is_in_the_closed_rule_key_set(self) -> None: """§6.1.6 rule 3: adding the field was only safe once §6.1.5 closed the set.""" - from apcore.acl import _RULE_KEYS + from apcore.acl_loader import _RULE_KEYS assert "approval" in _RULE_KEYS diff --git a/python/tests/test_full_assembly.py b/python/tests/test_full_assembly.py index a76d2ae1..a072b6aa 100644 --- a/python/tests/test_full_assembly.py +++ b/python/tests/test_full_assembly.py @@ -23,13 +23,17 @@ def test_root_runs_in_memory_without_importing_optional_dependencies() -> None: class BlockOptionalImports(MetaPathFinder): def find_spec(self, fullname, path=None, target=None): - if fullname == 'http.server' or fullname.split('.')[0] in { - 'yaml', 'watchdog', 'aiohttp', 'opentelemetry' - }: + optional_modules = {'http.server', 'apcore.acl_loader', 'apcore.registry.watcher'} + optional_packages = {'yaml', 'watchdog', 'aiohttp', 'opentelemetry'} + if fullname in optional_modules or fullname.split('.')[0] in optional_packages: raise AssertionError(f'Kernel imported optional dependency {fullname}') sys.meta_path.insert(0, BlockOptionalImports()) from apcore import APCore + from apcore.acl import ACL, ACLRule + + acl = ACL([ACLRule(callers=['app.*'], targets=['example.add'], effect='allow')]) + assert acl.check('app.worker', 'example.add') app = APCore() diff --git a/python/tests/test_global_timeout.py b/python/tests/test_global_timeout.py index 9e1825e0..7f74cbdf 100644 --- a/python/tests/test_global_timeout.py +++ b/python/tests/test_global_timeout.py @@ -3,7 +3,11 @@ from __future__ import annotations import asyncio +import gc +import threading import time +from collections.abc import Callable +from contextvars import Context as ContextVarsContext from typing import Any import pytest @@ -173,6 +177,47 @@ def test_chain_global_timeout(self) -> None: with pytest.raises(ModuleTimeoutError): executor.call("chain.mod", {"sleep_seconds": 0.15}) + def test_late_nested_timeout_does_not_leave_an_unretrieved_future(self, monkeypatch: pytest.MonkeyPatch) -> None: + allow_child = threading.Event() + completion_queued = threading.Event() + diagnostics: list[str] = [] + + class DelayedChainer(ChainingModule): + def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, Any]: + assert allow_child.wait(5) + return context.executor.call(self._target_module_id, inputs, context) + + executor = _make_executor( + {"chain.mod": DelayedChainer("fast.mod"), "fast.mod": FastModule()}, global_timeout=50 + ) + try: + with pytest.raises(ModuleTimeoutError): + executor.call("chain.mod", {}) + + loop = executor._sync_bridge._local.owner.loop + loop.set_exception_handler(lambda _, context: diagnostics.append(context["message"])) + schedule = loop.call_soon_threadsafe + + def track_completion( + callback: Callable[..., object], *args: object, context: ContextVarsContext | None = None + ) -> asyncio.Handle: + handle = schedule(callback, *args, context=context) + completion_queued.set() + return handle + + monkeypatch.setattr(loop, "call_soon_threadsafe", track_completion) + allow_child.set() + assert completion_queued.wait(5) + # Process the worker's result without running its next-turn callbacks. + loop.stop() + loop.run_forever() + finally: + allow_child.set() + executor.close() + + gc.collect() + assert "Future exception was never retrieved" not in diagnostics + class TestContextSerializationExcludesDeadline: def test_serialize_excludesglobal_deadline(self) -> None: From 250fad5529aa28cafab5abd8de52bb22d6f540a1 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:50:02 +0800 Subject: [PATCH 07/10] docs(core): record alpha.2 profiles, migration and acceptance Signed-off-by: tercel --- .github/workflows/case-pinning.yml | 2 +- .github/workflows/packages.yml | 18 +- .github/workflows/sdk-python.yml | 4 +- .github/workflows/sdk-rust.yml | 5 + CHANGELOG.md | 19 ++ conformance/README.md | 9 +- conformance/check_config_key_consumers.py | 65 ++++++ conformance/config_key_consumers.json | 25 ++- conformance/decision_coverage.json | 28 +-- conformance/fixtures/approval_gate.json | 6 +- .../fixtures/approval_startup_report.json | 8 + .../fixtures/core_profile_governance.json | 46 ++++ .../fixtures/event_delivery_semantics.json | 26 +-- conformance/fixtures/export_profiles.json | 187 ---------------- conformance/fixtures/reload_path_filter.json | 13 +- conformance/skip_asymmetry_baseline.json | 8 +- docs/features/acl-system.md | 4 +- docs/features/apcore-client.md | 4 +- docs/features/approval-system.md | 8 +- docs/features/async-tasks.md | 12 +- docs/features/call-chain-guard.md | 2 +- docs/features/config-bus.md | 31 ++- docs/features/core-executor.md | 2 +- docs/features/decorator-bindings.md | 2 +- docs/features/error-history.md | 4 +- docs/features/event-system.md | 211 ++++-------------- docs/features/execution-pipeline.md | 2 +- docs/features/extension-system.md | 2 +- docs/features/metrics-and-usage.md | 133 ++--------- docs/features/observability.md | 6 +- docs/features/redaction.md | 2 +- docs/features/schema-system.md | 32 +-- docs/features/streaming.md | 2 +- docs/features/system-modules.md | 73 +----- docs/getting-started.md | 4 +- docs/guides/acl-configuration.md | 10 +- docs/guides/cookbook-approval-flow.md | 35 +-- docs/guides/cookbook-observability.md | 4 +- docs/guides/creating-modules.md | 4 +- docs/guides/index.md | 2 + docs/guides/multi-language.md | 2 +- docs/guides/runtime-profiles.md | 113 ++++++++++ docs/guides/troubleshooting.md | 6 +- docs/index.md | 8 +- docs/spec/api-surface-conventions.md | 4 +- docs/spec/conformance.md | 11 +- docs/spec/design-durability-boundary.md | 2 +- docs/spec/protocol-spec.md | 124 ++++++---- docs/spec/security-considerations.md | 2 +- mkdocs.yml | 1 + planning/microkernel-delivery/alpha-2.md | 101 +++++++++ planning/microkernel-delivery/bench-alpha2.py | 120 ++++++++++ planning/microkernel-delivery/bench-alpha2.rs | 49 ++++ schemas/sys-modules.schema.json | 2 +- 54 files changed, 835 insertions(+), 770 deletions(-) create mode 100644 conformance/fixtures/core_profile_governance.json delete mode 100644 conformance/fixtures/export_profiles.json create mode 100644 docs/guides/runtime-profiles.md create mode 100644 planning/microkernel-delivery/alpha-2.md create mode 100644 planning/microkernel-delivery/bench-alpha2.py create mode 100644 planning/microkernel-delivery/bench-alpha2.rs diff --git a/.github/workflows/case-pinning.yml b/.github/workflows/case-pinning.yml index 6e6b0b82..3153a1dd 100644 --- a/.github/workflows/case-pinning.yml +++ b/.github/workflows/case-pinning.yml @@ -61,7 +61,7 @@ jobs: - name: Install SDKs run: | - python3 -m pip install --quiet -e "./python[dev]" + python3 -m pip install --quiet -e "./python[all,dev]" pnpm --dir typescript install --frozen-lockfile cargo build --manifest-path rust/Cargo.toml --tests --all-features diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 997d4ea1..99a48190 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -41,11 +41,15 @@ jobs: cd "$temporary" "$temporary/venv/bin/python" -m pip install "${wheel[0]}" "$temporary/venv/bin/python" -m pip check - "$temporary/venv/bin/python" -c 'from apcore import APCore, Registry' + "$temporary/venv/bin/python" -c 'from apcore import APCore, Registry; from importlib.util import find_spec; assert all(find_spec(name) is None for name in ("yaml", "watchdog", "aiohttp", "opentelemetry"))' "$temporary/venv/bin/python" -c 'from importlib.resources import files; assert files("apcore").joinpath("py.typed").is_file(), "installed wheel is missing apcore/py.typed"' python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" python "$temporary" (cd quick-start && "$temporary/venv/bin/python" -I example.py) - (cd governed-stream && "$temporary/venv/bin/python" -I example.py) + python -m venv "$temporary/full" + "$temporary/full/bin/python" -m pip install "${wheel[0]}[all]" + "$temporary/full/bin/python" -m pip check + "$temporary/full/bin/python" -c 'from apcore.full import APCore, Config; from apcore.events import SubscriberRegistry; assert APCore(config=Config.from_defaults()).registry is not None' + (cd governed-stream && "$temporary/full/bin/python" -I example.py) - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with: name: core-python-distributions @@ -82,7 +86,7 @@ jobs: rust-version = "1.86" [dependencies] - apcore = { path = "sdk", features = ["events"] } + apcore = { path = "sdk", features = ["config", "events"] } async-trait = "0.1.92" futures-util = "0.3" serde_json = "1" @@ -137,11 +141,13 @@ jobs: node --input-type=module -e 'import {APCore} from "apcore-js"; import "apcore-js/context-keys"; if (!APCore) throw new Error("APCore is missing");' cat > verify-browser.mjs <<'EOF' const url = await import.meta.resolve("apcore-js"); - if (!url.endsWith("/dist/browser/index.js")) throw new Error("browser entry did not resolve"); - await import("apcore-js"); + if (!url.endsWith("/dist/index.js")) throw new Error("browser entry did not resolve to the portable root"); + const core = await import("apcore-js"); + if (!core.APCore || "Config" in core) throw new Error("invalid Core Profile exports"); EOF node --conditions=browser --experimental-import-meta-resolve verify-browser.mjs - node --input-type=module -e 'import {accessSync} from "node:fs"; for (const entry of ["index", "browser/index", "context-keys"]) accessSync(`node_modules/apcore-js/dist/${entry}.d.ts`);' + node --input-type=module -e 'import {accessSync} from "node:fs"; for (const entry of ["index", "core", "full", "config-entry", "discovery", "events/entry", "context-keys"]) accessSync(`node_modules/apcore-js/dist/${entry}.d.ts`);' + node --input-type=module -e 'import {APCore} from "apcore-js/full"; import {Config} from "apcore-js/config"; import {createFilesystemDiscoveryPlugin} from "apcore-js/discovery"; if (!new APCore({config: new Config(), plugins: [createFilesystemDiscoveryPlugin()]}).registry) throw new Error("invalid full assembly");' python3 "$GITHUB_WORKSPACE/conformance/extract_doc_examples.py" typescript "$temporary" ./node_modules/.bin/tsc --strict --module NodeNext --target ES2022 --rootDir . --outDir compiled \ quick-start/example.ts governed-stream/example.ts diff --git a/.github/workflows/sdk-python.yml b/.github/workflows/sdk-python.yml index d5734a79..df6b5ccb 100644 --- a/.github/workflows/sdk-python.yml +++ b/.github/workflows/sdk-python.yml @@ -38,9 +38,9 @@ jobs: python -m pip install --upgrade pip # If a constraints.txt file is present, use it to pin critical dependency versions. if [ -f constraints.txt ]; then - pip install -e ".[dev]" -c constraints.txt + pip install -e ".[all,dev]" -c constraints.txt else - pip install -e ".[dev]" + pip install -e ".[all,dev]" fi - name: Verify canonical conformance fixture checkout diff --git a/.github/workflows/sdk-rust.yml b/.github/workflows/sdk-rust.yml index 962b891d..b17c2415 100644 --- a/.github/workflows/sdk-rust.yml +++ b/.github/workflows/sdk-rust.yml @@ -68,6 +68,11 @@ jobs: - name: Build run: cargo build --locked --all-features + - name: Test the in-memory Core Profile + run: cargo test --locked --no-default-features --lib --test core_profile + env: + CONFORMANCE_SPEC_REPO: ${{ github.workspace }} + - name: Run tests run: cargo test --locked --all-features env: diff --git a/CHANGELOG.md b/CHANGELOG.md index bdac3711..354a8801 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- 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. + +### Changed + +- **Protocol 3.0.0 draft.** The default Core Profile supports in-memory execution, with file-backed capabilities and host integrations supplied by explicit extension profiles. The built-in approval gate rejects calls that require approval when no handler is configured and requires approval for destructive modules by default. An explicit policy with `strict = false` and `gate_destructive = false` retains the earlier behavior during migration. +- Report the configured project version in the health summary and use the configured usage retention period. + +### Fixed + +- Reuse one Python synchronous event loop per calling thread. Bound nested workers and retain in-flight execution until its worker completes after timeouts. + +### Removed + +- Move Prometheus HTTP listening, A2A delivery, and provider-specific tool projections to Surfaces. Core retains text rendering, generic schema export, and strict schema conversion. +- Remove the deprecated `reload_dependents` input. Use `path_filter` to select dependent modules. + ## [1.0.0-alpha.1] This prerelease delivers the cross-repository governance and streaming fixes ahead of the microkernel package split. SDK installations use `1.0.0a1` for Python and `1.0.0-alpha.1` for TypeScript and Rust. The full package and configuration entry points remain available for adapter migration. diff --git a/conformance/README.md b/conformance/README.md index 33942978..e146ee52 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -12,6 +12,11 @@ All fixture files use **JSON** format (`.json`), with one intentional exception: SDK conformance runners **must** load `.json` files with a JSON parser. The `.yaml` file is consumed directly by binding-loader tests, not by the generic conformance runner. +The `profile` field identifies the runtime profile exercised by a fixture. +`core` fixtures can run against a default in-memory SDK installation. +Configuration, Discovery, Events, and System Modules fixtures use their +declared extension. Adapter wire projections are verified in Surfaces. + > **Note for tooling authors:** Some ecosystem skill docs describe conformance fixtures as YAML; this is incorrect. The canonical format for all conformance test cases is JSON. The README is the authoritative format reference. ## Fixtures @@ -62,7 +67,8 @@ SDK conformance runners **must** load `.json` files with a JSON parser. The `.ya | `stream_aggregation.json` | — | Stream chunk deep-merge aggregation algorithm | | `stream_post_processing.json` | D-20 | Native streams propagate cancellation from after-middleware and report ordinary post-processing failures as events | | `stream_completion.json` | SDK streaming completion | One invocation reports its canonical output, individual post-processing outcomes, and termination through the opt-in stream handle | -| `approval_gate.json` | A05 | Approval gate Step 5: skip/fire conditions, result-status outcomes, and scoped resumption | +| `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 | | `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 | @@ -112,7 +118,6 @@ SDK conformance runners **must** load `.json` files with a JSON parser. The `.ya | `preflight_check_reporting.json` | §12.8, D-134, D-141 | `validate()` reports every check: a failure does not stop later checks and passed checks are never dropped; no module-dependent check when the module is unknown; `preview()` returning null adds no check; `predicted_changes` always present | | `json_input_native_types.json` | type-mapping §17.3, D-136 | A module declared from native date-time / UUID / enum types accepts the JSON strings its schema accepts and still rejects what it rejects (a number for a date-time, a string outside the enum) | | `binding_file_validation.json` | §5.12.2, §5.12.5, D-139 | Binding files fail loudly: unknown top-level / entry keys, a one-sided schema pair and an invalid `auto_schema` are `BINDING_FILE_INVALID`; an uninferable schema is `BINDING_SCHEMA_INFERENCE_FAILED` in every mode, implicit included; a complete entry with free-form `metadata` still loads | -| `export_profiles.json` | §4.17, Appendix D.1, D-140 | `anthropic` strips every `x-*` keyword but keeps a property NAMED `x-…`; `mcp` carries `requiresApproval` / `streaming` in `_meta` only when true, never in `annotations`, and keeps `x-*` | | `env_prefix_dispatch.json` | §9.8.2, D-146 | `APCORE` is reserved for the `apcore` namespace (`CONFIG_NAMESPACE_RESERVED`), `APCORE_` prefixes are legal, a variable is dispatched to exactly one namespace by longest prefix, an unmatched `APCORE_` variable belongs to `apcore` | | `ephemeral_modules.json` | §2.5.1, D-148 | Exactly one registry audit event per ephemeral register / unregister under the standard bootstrap with `caller_id`, `identity` (or null) and `namespace_class`; the bare ID `ephemeral`; `INVALID_MODULE_ID` rejections from `register_internal` and discovery | | `error_details_shape.json` | §8.1, D-149 | `SCHEMA_VALIDATION_ERROR` `details.errors` items are exactly `{path, keyword, message}`, `path` an RFC 6901 pointer (`""` for the root); serialized `details` keys are snake_case | diff --git a/conformance/check_config_key_consumers.py b/conformance/check_config_key_consumers.py index 34ceaae8..4992313d 100644 --- a/conformance/check_config_key_consumers.py +++ b/conformance/check_config_key_consumers.py @@ -155,6 +155,54 @@ def _usage_enabled() -> str | None: return _group_probe("usage", {"system.usage.summary", "system.usage.module"}) +@probe("sys_modules.usage.retention_hours") +def _usage_retention() -> str | None: + from datetime import datetime, timedelta, timezone + + from apcore import Executor + from apcore.config import Config + from apcore.registry import Registry + from apcore.sys_modules.registration import register_sys_modules + + def call_count(retention_hours: int) -> int: + config = Config.from_defaults() + config.set("sys_modules.enabled", True) + config.set("sys_modules.usage.retention_hours", retention_hours) + registry = Registry() + executor = Executor(registry, config=config) + context = register_sys_modules(registry, executor, config) + collector = context["usage_collector"] + now = datetime.now(timezone.utc) + for age in (5, 0): + collector.record("usage.sample", "probe", 1.0, True, (now - timedelta(hours=age)).isoformat()) + return executor.call("system.usage.summary", {"period": "24h"})["total_calls"] + + short, long = call_count(2), call_count(12) + if (short, long) != (1, 2): + return f"usage retention of 2h and 12h produced {(short, long)!r} calls, expected (1, 2)" + return None + + +@probe("sys_modules.usage.bucketing_strategy") +def _usage_bucketing() -> str | None: + from apcore.config import Config + from apcore.errors import ConfigError + from apcore.full import APCore + + config = Config.from_defaults() + config.set("sys_modules.enabled", True) + config.set("sys_modules.usage.bucketing_strategy", "hourly") + APCore(config=config, fail_on_error=True).call("system.usage.summary", {}) + + config.set("sys_modules.usage.bucketing_strategy", "invalid") + try: + APCore(config=config, fail_on_error=True) + except ConfigError as exc: + if "bucketing_strategy" in str(exc): + return None + return "the system-module startup path accepted an invalid usage bucketing strategy" + + @probe("sys_modules.control.enabled") def _control_enabled() -> str | None: """The Level 2 write plane (6.7). The one an operator turns off deliberately.""" @@ -1214,6 +1262,23 @@ def manifest(name: str) -> object: return None +@probe("project.version") +def _project_version() -> str | None: + from apcore.config import Config + from apcore.full import APCore + + for version in ("1.2.3", "2.3.4"): + config = Config.from_defaults() + config.set("sys_modules.enabled", True) + config.set("project.name", "fixture") + config.set("project.version", version) + client = APCore(config=config, fail_on_error=True) + project = client.call("system.health.summary", {})["project"] + if project != {"name": "fixture", "version": version}: + return f"project.version={version!r} produced {project!r}" + return None + + @probe("version") def _config_version() -> str | None: """§9.3 requiredness: a document without it is rejected, one with it loads. diff --git a/conformance/config_key_consumers.json b/conformance/config_key_consumers.json index 8337624e..7e05a98e 100644 --- a/conformance/config_key_consumers.json +++ b/conformance/config_key_consumers.json @@ -1,7 +1,7 @@ { "_comment": "What reads each declared configuration key. Enforced by conformance/check_config_key_consumers.py.\n\nconfig_key_governance.json pins that every declared key is ACCEPTED — the three SDKs agree on the key set and the default table. Nothing pinned that any key is READ, and 29 of 61 were not (apcore#118). This file is the missing half: every key states what consumes it, or states that nothing does and why.\n\nSTATUSES\n live — a probe in the checker SETS THE KEY through Config.set (enforced: the checker records what each probe writes and rejects one that never writes its own key) and observes an effect OUTSIDE Config, on a path the LIBRARY ITSELF drives — APCore(config=...), BindingLoader.load_bindings(..., cfg), the executor's stream merge. Three things have each produced a false `live` and each is excluded by one clause above: reading the value back from Config proves plumbing, not consumption (four observability.* keys round-trip perfectly and are consumed by nothing); reaching the behaviour by another door proves the behaviour, not the key (acl.default_effect's probe built ACL(default_effect=...) directly); and driving a helper nothing else calls proves the helper, not the library (obs.redaction.* is read only by RedactionConfig.from_config, which no SDK's src/ invokes).\n partial — something reads it, but not on the path an operator would expect. The reason must say what the gap is.\n inert — nothing reads it. A written decision, not an accident; the reason must say what was measured.\n unaudited — not yet examined. NOT a claim that the key works.\n\nThe `ratchet` counts may fall and may not rise. Lower a ceiling in the same change that fixes or audits a key; that is what turns apcore#118 from a report into a number that has to go down.\n\nTHE RATCHET IS A LEDGER, NOT A NUMBER. Each `ratchet` ceiling MUST equal the `to` of the last `ratchet_history` entry for that status, and the entries MUST chain (`from` == the previous `to`). Editing a ceiling on its own therefore fails the checker: the number and the ledger stop agreeing. A RISE additionally requires a `reason` and a `keys` list naming the keys that moved, and each named key must actually hold that status. Falls need an entry too, so the chain stays continuous, but no `keys`.\n\nThis exists because the previous rule — \"may fall, may not rise\" — was enforced by a code comment, and the first raise under it (inert 18 -> 19 on 2026-09-10) was made in the same commit that changed the number. A ceiling guarded only by review is guarded only when someone looks.", "ratchet": { - "inert": 16, + "inert": 13, "unaudited": 0 }, "keys": { @@ -254,9 +254,8 @@ "probe": "project.name" }, "project.version": { - "status": "inert", - "reason": "No code path reads it.", - "tracking": "https://github.com/aiperceivable/apcore/issues/118" + "status": "live", + "probe": "project.version" }, "schema.max_ref_depth": { "status": "live", @@ -319,18 +318,16 @@ "probe": "sys_modules.manifest.enabled" }, "sys_modules.usage.bucketing_strategy": { - "status": "inert", - "reason": "No code path reads it.", - "tracking": "https://github.com/aiperceivable/apcore/issues/118" + "status": "live", + "probe": "sys_modules.usage.bucketing_strategy" }, "sys_modules.usage.enabled": { "status": "live", "probe": "sys_modules.usage.enabled" }, "sys_modules.usage.retention_hours": { - "status": "inert", - "reason": "No code path reads it.", - "tracking": "https://github.com/aiperceivable/apcore/issues/118" + "status": "live", + "probe": "sys_modules.usage.retention_hours" }, "validation.binding.description_max_length": { "status": "live", @@ -540,6 +537,14 @@ "_config.allow_unknown" ], "reason": "D-69 (spec v1.46.0), and the last key of the #118 audit to be wired. The probe drives BOTH halves of §9.6.3's row: a probe checking only the drop would pass on an implementation that never emits the warning the same row requires, which is the state all three SDKs were in." + }, + { + "status": "inert", + "from": 16, + "to": 13, + "date": "2026-11-27", + "keys": ["project.version", "sys_modules.usage.bucketing_strategy", "sys_modules.usage.retention_hours"], + "reason": "System modules report project versions and use the declared hourly usage retention settings." } ] } diff --git a/conformance/decision_coverage.json b/conformance/decision_coverage.json index 1a8278bb..046b25fd 100644 --- a/conformance/decision_coverage.json +++ b/conformance/decision_coverage.json @@ -687,23 +687,12 @@ "discriminates": "The expectation is a REGEX, not a value: a timestamp is generated at call time, so the only thing a fixture can pin is its SHAPE — ^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$. Asserting the Z suffix alone would leave three precisions behind one suffix: the same divergence, harder to see, which is why the decision fixes the precision too and why the case does.\n\nMeasured before implementing, and the recorded status quo was already stale: apcore-python wrote +00:00 with microseconds, apcore-typescript already wrote Z with milliseconds, and apcore-rust wrote Z with MICROSECONDS rather than the +00:00 nanoseconds the decision text recorded.\n\nAll THREE timestamp fields are asserted (timestamp, first_occurred, last_occurred): a fix applied to one of them is the same divergence at one field's remove. The assertion runs against the record the PRODUCER writes rather than a health summary — apcore-rust's health module reformatted the same entry with to_rfc3339() into a THIRD form, so a reader-side assertion would have passed while the stored record diverged, which is the failure mode the decision calls out by name.\n\nVerified red in apcore-python by restoring isoformat() and in apcore-rust by dropping the serialize_with attribute." }, "D-121": { - "title": "`reload_dependents` is deprecated for removal", + "title": "Removed reload_dependents field is rejected", "kind": "behavioural", "cases": [ - "reload_path_filter.json#reload_dependents_is_accepted_and_inert" + "reload_path_filter.json#removed_reload_dependents_is_rejected" ], - "sdk_tests": { - "python": [ - "tests/sys_modules/test_reload_dependents_deprecation.py" - ], - "typescript": [ - "tests/sys-modules/test-reload-dependents-deprecation.test.ts" - ], - "rust": [ - "tests/test_reload_dependents_deprecation.rs" - ] - }, - "discriminates": "Split deliberately between a case and per-SDK tests, because the decision has two halves with different testable shapes.\n\nTHE CASE pins the cross-SDK invariant: passing `reload_dependents: true` changes nothing. Its expected reloaded set is asserted IDENTICAL to `glob_filter_restricts_rediscovery`, which runs the same filter WITHOUT the field — asserting only that the call succeeds would pass for an SDK that started honouring it and pulled the dependents in, which is the one outcome the maintainer decision forbids.\n\nTHE PER-SDK TESTS pin the deprecation notice, which a fixture cannot observe: the guard is INSTANCE state, so a case would depend on which case ran first in the process — the same process-global trap that let one test's ACL condition handler decide another's control. Each SDK asserts the notice fires, names the replacement (`path_filter`), names the release (2.0) and says the field becomes a VALIDATION ERROR rather than a no-op — a notice that omits any of those leaves the caller to discover it. Cadence is per INSTANCE, not per process, for the reason D-90's notice is per token and D-89's dedupe is per registry instance: a process-wide one-shot tells the first caller and leaves every later one to find out in production. A separate assertion reads the INPUT SCHEMA, because a host must be able to see the deprecation without calling with the field.\n\nControls: omitting the field, and passing `false`, must both say nothing — without which 'it warns' is satisfied by warning on every reload.\n\nVerified red in all three: removing the warning, making the guard process-wide, warning unconditionally, and dropping the schema marker each redden exactly the assertions that stand on them.\n\nAT 2.0 THE CASE FLIPS rather than being deleted: the field is removed, `additionalProperties: false` applies, and the same input becomes a validation error." + "discriminates": "The old reload input now raises SCHEMA_VALIDATION_ERROR while the adjacent glob case still reloads the selected modules." }, "D-122": { "title": "`shutdown()` attempts every cancellation before it reports", @@ -947,15 +936,8 @@ }, "D-140": { "title": "export profiles follow 4.17 and Appendix D.1", - "kind": "behavioural", - "cases": [ - "export_profiles.json#anthropic_strips_every_x_keyword", - "export_profiles.json#anthropic_keeps_a_property_named_like_an_extension", - "export_profiles.json#mcp_carries_requires_approval_and_streaming_in_meta", - "export_profiles.json#mcp_omits_false_hints_from_meta", - "export_profiles.json#mcp_preserves_x_keywords" - ], - "discriminates": "anthropic_strips_every_x_keyword is red in apcore-rust (x-* passed through). mcp_carries_requires_approval_and_streaming_in_meta is red in all three (streaming in annotations, no requiresApproval). mcp_omits_false_hints_from_meta is red for an exporter that always writes both hints; mcp_preserves_x_keywords is red for one that strips x-* in the mcp profile too. anthropic_keeps_a_property_named_like_an_extension is red in apcore-python and apcore-typescript, whose strip deleted every `x-` key including a property NAME, and so is the anthropic case's keyword check for an implementation that strips nothing under `properties`." + "kind": "adapter", + "note": "The apcore-surfaces MCP test suites drive mcp/conformance/fixtures/tool_projection.json through their public provider converters and MCP tool factories in all three languages." }, "D-141": { "title": "preflight check reporting", diff --git a/conformance/fixtures/approval_gate.json b/conformance/fixtures/approval_gate.json index eaf7d223..29dcc202 100644 --- a/conformance/fixtures/approval_gate.json +++ b/conformance/fixtures/approval_gate.json @@ -1,12 +1,14 @@ { - "description": "Approval gate enforcement at Executor Step 5. Verifies gate fires only when both handler is configured and module declares requires_approval=true, and that all four result statuses map to the correct outcomes. Since D-96 (spec v1.50.0) the three `governance_sources` cases state the module and descriptor declarations SEPARATELY: the original `module_requires_approval` boolean could be satisfied from either source, so all three SDKs passed it while disagreeing about which one decides.", + "description": "Approval gate enforcement at Executor Step 5, including the explicit compatibility policy, handler outcomes, and scoped resumption.", + "profile": "core", "algorithm": "A05", "test_cases": [ { "id": "skip_when_no_handler", - "description": "Gate is skipped entirely when no ApprovalHandler is configured", + "description": "An explicit compatibility policy permits a call without an approval handler.", "approval_handler_configured": false, "module_requires_approval": true, + "execution_policy": {"strict": false, "gate_destructive": false}, "approval_result": null, "expected": { "gate_invoked": false, diff --git a/conformance/fixtures/approval_startup_report.json b/conformance/fixtures/approval_startup_report.json index 0a6f778e..8d961bc9 100644 --- a/conformance/fixtures/approval_startup_report.json +++ b/conformance/fixtures/approval_startup_report.json @@ -1,5 +1,6 @@ { "description": "Executor startup diagnostic for registered modules whose requires_approval declaration has no effective built-in approval gate.", + "profile": "core", "modules": [ {"module_id": "orders.metadata", "live_approval": false, "declared_approval": true, "discoverable": false}, {"module_id": "orders.view", "live_approval": false, "declared_approval": false, "discoverable": true}, @@ -11,6 +12,13 @@ "strategy": "standard", "handler_attached": false, "policy": {}, + "expected": {"ungated_modules": []} + }, + { + "id": "warn_and_continue_without_provider", + "strategy": "standard", + "handler_attached": false, + "policy": {"strict": false}, "expected": {"ungated_modules": ["orders.confirm", "orders.metadata"]} }, { diff --git a/conformance/fixtures/core_profile_governance.json b/conformance/fixtures/core_profile_governance.json new file mode 100644 index 00000000..b091ea52 --- /dev/null +++ b/conformance/fixtures/core_profile_governance.json @@ -0,0 +1,46 @@ +{ + "description": "In-memory client execution and preflight use the same approval requirement. With no approval handler, the default gate keeps every approval-required call out of the module.", + "profile": "core", + "test_cases": [ + { + "id": "ordinary_module", + "input": {"approval_source": "none", "client": "default"}, + "expected": {"requires_approval": false, "error_code": null, "executions": 1} + }, + { + "id": "module_approval", + "input": {"approval_source": "annotation", "client": "default"}, + "expected": {"requires_approval": true, "error_code": "APPROVAL_DENIED", "executions": 0} + }, + { + "id": "acl_approval", + "input": {"approval_source": "acl", "client": "default"}, + "expected": {"requires_approval": true, "error_code": "APPROVAL_DENIED", "executions": 0} + }, + { + "id": "explicit_policy_rule_approval", + "input": {"approval_source": "policy_rule", "client": "default"}, + "expected": {"requires_approval": true, "error_code": "APPROVAL_DENIED", "executions": 0} + }, + { + "id": "destructive_default", + "input": {"approval_source": "destructive", "client": "default"}, + "expected": {"requires_approval": true, "error_code": "APPROVAL_DENIED", "executions": 0} + }, + { + "id": "destructive_opt_out", + "input": {"approval_source": "destructive", "client": "default", "execution_policy": {"gate_destructive": false}}, + "expected": {"requires_approval": false, "error_code": null, "executions": 1} + }, + { + "id": "explicit_warn_and_continue", + "input": {"approval_source": "annotation", "client": "default", "execution_policy": {"strict": false}}, + "expected": {"requires_approval": true, "error_code": null, "executions": 1} + }, + { + "id": "injected_executor_uses_default_gate", + "input": {"approval_source": "annotation", "client": "injected_executor"}, + "expected": {"requires_approval": true, "error_code": "APPROVAL_DENIED", "executions": 0} + } + ] +} diff --git a/conformance/fixtures/event_delivery_semantics.json b/conformance/fixtures/event_delivery_semantics.json index 314aa312..8b730650 100644 --- a/conformance/fixtures/event_delivery_semantics.json +++ b/conformance/fixtures/event_delivery_semantics.json @@ -1,4 +1,5 @@ { + "profile": "events", "description": "Event delivery semantics — retry policy, dead-letter event, and on_failure callback (Issue #61). Verifies that all subscriber types honor the unified retry config, that permanent failure emits apcore.event.delivery_failed with the normative payload schema, and that the DLQ event itself is not retried.", "test_cases": [ { @@ -44,10 +45,8 @@ "description": "A subscriber that fails on every attempt MUST trigger emission of apcore.event.delivery_failed after max_attempts is reached. The DLQ event payload MUST conform to the normative schema.", "setup": { "subscriber": { - "type": "a2a", + "type": "test_remote", "id": "remote-monitor-1", - "platform_url": "https://platform.example.invalid", - "skill_id": "myapp.event_receiver", "retry": { "max_attempts": 3, "initial_backoff_ms": 10 @@ -71,7 +70,7 @@ "dlq_event": { "event_type": "apcore.event.delivery_failed", "data_contains": { - "subscriber_type": "a2a", + "subscriber_type": "test_remote", "subscriber_id": "remote-monitor-1", "attempt_count": 3, "original_event": { @@ -94,9 +93,8 @@ "description": "If a subscriber registered for apcore.event.delivery_failed itself raises, the SDK MUST log at ERROR and discard. The DLQ event MUST NOT be retried (no infinite loop).", "setup": { "primary_subscriber": { - "type": "a2a", + "type": "test_remote", "id": "broken-primary", - "platform_url": "https://platform.example.invalid", "retry": { "max_attempts": 2, "initial_backoff_ms": 10 @@ -178,16 +176,6 @@ "backoff_multiplier": 3.0 } }, - { - "type": "a2a", - "platform_url": "https://platform.example.invalid", - "retry": { - "max_attempts": 7, - "initial_backoff_ms": 250, - "max_backoff_ms": 10000, - "backoff_multiplier": 3.0 - } - }, { "type": "file", "path": "/tmp/apcore-conformance-retry-policy.jsonl", @@ -227,12 +215,6 @@ "max_backoff_ms": 10000, "backoff_multiplier": 3.0 }, - "a2a": { - "max_attempts": 7, - "initial_backoff_ms": 250, - "max_backoff_ms": 10000, - "backoff_multiplier": 3.0 - }, "file": { "max_attempts": 7, "initial_backoff_ms": 250, diff --git a/conformance/fixtures/export_profiles.json b/conformance/fixtures/export_profiles.json deleted file mode 100644 index 49be45f8..00000000 --- a/conformance/fixtures/export_profiles.json +++ /dev/null @@ -1,187 +0,0 @@ -{ - "description": "Export profiles follow PROTOCOL_SPEC 4.17 and Appendix D.1 (decision D-140). The `anthropic` profile strips every `x-*` keyword at any depth of the input schema — apcore-rust passed them through. The `mcp` profile maps readonly / destructive / idempotent / open_world to MCP ToolAnnotations hints, and carries `requires_approval` and `streaming` — which MCP ToolAnnotations do not define — in the tool's `_meta` as `requiresApproval` and `streaming`, each present only when true, never in `annotations`. All three SDKs put `streaming` in `annotations` and emitted no `requiresApproval` at all.", - "spec_sections": [ - "PROTOCOL_SPEC 4.17", - "PROTOCOL_SPEC Appendix D.1" - ], - "module_contract": { - "module_id": "demo.send", - "description": "Send a message", - "input_schema": { - "type": "object", - "x-owner": "billing", - "properties": { - "to": { - "type": "string", - "description": "Recipient address", - "x-sensitive": true, - "x-examples": [ - "a@example.com" - ] - }, - "items": { - "type": "array", - "items": { - "type": "object", - "properties": { - "sku": { - "type": "string", - "x-constraints": { - "pattern_hint": "upper" - } - } - } - } - }, - "x-trace": { - "type": "string", - "description": "Caller-supplied trace tag", - "x-sensitive": false - } - }, - "required": [ - "to" - ] - }, - "output_schema": { - "type": "object", - "properties": { - "sent": { - "type": "boolean" - } - } - } - }, - "driver_contract": { - "path": "Export through the SDK's public profile exporter (SchemaExporter.export with the profile, or the Registry export that delegates to it) for a module registered from `module_contract` with the case's `annotations`.", - "paths": "`expected.paths` maps a JSON Pointer into the exported object to the value it MUST hold.", - "absent_paths": "`expected.absent_paths` lists JSON Pointers that MUST NOT resolve.", - "no_x_keywords_under": "`expected.no_x_keywords_under` is a JSON Pointer: no object key beginning with `x-` may appear anywhere beneath it, EXCEPT a key of a `properties` object, which is a property name rather than a keyword." - }, - "test_cases": [ - { - "id": "anthropic_strips_every_x_keyword", - "input": { - "profile": "anthropic", - "annotations": { - "readonly": false, - "destructive": true, - "idempotent": false, - "open_world": true, - "requires_approval": true, - "streaming": true - } - }, - "expected": { - "no_x_keywords_under": "/input_schema", - "paths": { - "/name": "demo_send", - "/input_schema/type": "object", - "/input_schema/properties/to/type": "string", - "/input_schema/required": [ - "to" - ], - "/input_schema/properties/items/items/properties/sku/type": "string" - } - } - }, - { - "id": "anthropic_keeps_a_property_named_like_an_extension", - "description": "D-140: only x- KEYWORDS are stripped. A property whose NAME begins with `x-` is data; stripping it removes an input the module accepts. apcore-python and apcore-typescript deleted every dict key beginning with `x-`, property names included.", - "input": { - "profile": "anthropic", - "annotations": { - "readonly": false, - "destructive": true, - "idempotent": false, - "open_world": true, - "requires_approval": true, - "streaming": true - } - }, - "expected": { - "paths": { - "/input_schema/properties/x-trace/type": "string" - }, - "absent_paths": [ - "/input_schema/properties/x-trace/x-sensitive" - ] - } - }, - { - "id": "mcp_carries_requires_approval_and_streaming_in_meta", - "input": { - "profile": "mcp", - "annotations": { - "readonly": false, - "destructive": true, - "idempotent": false, - "open_world": true, - "requires_approval": true, - "streaming": true - } - }, - "expected": { - "paths": { - "/_meta/requiresApproval": true, - "/_meta/streaming": true, - "/annotations/destructiveHint": true, - "/annotations/readOnlyHint": false - }, - "absent_paths": [ - "/annotations/streaming", - "/annotations/requiresApproval", - "/annotations/requires_approval" - ] - } - }, - { - "id": "mcp_omits_false_hints_from_meta", - "description": "Each `_meta` hint is present only when its annotation is true, and neither appears in `annotations` when false either. Fails an implementation that always writes both keys.", - "input": { - "profile": "mcp", - "annotations": { - "readonly": true, - "destructive": false, - "idempotent": true, - "open_world": false, - "requires_approval": false, - "streaming": false - } - }, - "expected": { - "paths": { - "/annotations/readOnlyHint": true, - "/annotations/idempotentHint": true - }, - "absent_paths": [ - "/_meta/requiresApproval", - "/_meta/streaming", - "/annotations/streaming", - "/annotations/requiresApproval" - ] - } - }, - { - "id": "mcp_preserves_x_keywords", - "description": "The over-correction guard: the `mcp` profile keeps the schema as-is, `x-*` included (4.17).", - "input": { - "profile": "mcp", - "annotations": { - "readonly": false, - "destructive": true, - "idempotent": false, - "open_world": true, - "requires_approval": true, - "streaming": true - } - }, - "expected": { - "paths": { - "/inputSchema/properties/to/x-sensitive": true, - "/inputSchema/x-owner": "billing" - } - } - } - ] -} diff --git a/conformance/fixtures/reload_path_filter.json b/conformance/fixtures/reload_path_filter.json index caf4f027..ba00ce8e 100644 --- a/conformance/fixtures/reload_path_filter.json +++ b/conformance/fixtures/reload_path_filter.json @@ -1,4 +1,5 @@ { + "profile": "system-modules", "description": "Granular reload via the path_filter input on system.control.reload_module. path_filter and module_id are mutually exclusive (MODULE_RELOAD_CONFLICT). A path_filter matching zero modules is a no-op. Reload order MUST follow dependency topological order. PROTOCOL_SPEC 6.7 clause 4 fixes the matcher: path_filter is a GLOB-DIALECT pattern matched with algorithm A25 (9.2.3) against each registered module ID — `*` and `?` only, every other character literal, and NO pattern is ever rejected. Until v1.37.0 this clause said only 'glob' and the three SDKs used three matchers (fnmatch, A08, the glob crate), so one control-plane request reloaded two modules, reloaded none, or was refused as malformed depending on which SDK served it. Every case below except the first uses a value from outside the trailing-star family, which is the only family the three agreed on. See docs/features/system-modules.md#14-granular-reload-via-path-filtering.", "test_cases": [ { @@ -156,8 +157,8 @@ } }, { - "id": "reload_dependents_is_accepted_and_inert", - "description": "D-121: `reload_dependents` is DEPRECATED and ignored. Declared in all three SDKs' input schemas and read by none — a spec MUST that no implementation satisfied, which is the §9.1.3 'declared surface reaches no mechanism' shape applied to a module input field. Three independent implementations skipping it is the evidence the maintainer decision rests on: deprecate now, remove at 2.0, do NOT implement.\n\nThe reloaded set is asserted IDENTICAL to `glob_filter_restricts_rediscovery`, which runs the same filter without the field. Asserting only that the call succeeds would pass for an SDK that started honouring it and pulled the dependents in.\n\nThe once-per-instance deprecation WARNING is pinned by per-SDK tests instead: it is instance state, and a fixture case cannot observe it without depending on which case ran first in the process.\n\nAT 2.0 THIS CASE FLIPS rather than being deleted: the field is removed, the input schema sets `additionalProperties: false`, and the same input becomes a validation error.", + "id": "removed_reload_dependents_is_rejected", + "description": "The closed reload input rejects the removed reload_dependents field.", "registered_modules": [ "executor.email.send", "executor.email.verify", @@ -170,13 +171,7 @@ "reload_dependents": true, "reason": "deploy email service" }, - "expected": { - "success": true, - "reloaded_modules_set": [ - "executor.email.send", - "executor.email.verify" - ] - } + "expected": {"error_code": "SCHEMA_VALIDATION_ERROR"} }, { "id": "bulk_reload_audits_per_module_with_one_correlation_id", diff --git a/conformance/skip_asymmetry_baseline.json b/conformance/skip_asymmetry_baseline.json index 11e3deee..445e2a8c 100644 --- a/conformance/skip_asymmetry_baseline.json +++ b/conformance/skip_asymmetry_baseline.json @@ -1,5 +1,5 @@ { - "ratchet": 26, + "ratchet": 25, "_ratchet_note": "Each accepted entry records a clause that runs in one SDK and is skipped in another, with the reason recorded beside it. The limit tracks the current accepted entries.", "accepted": { "acl_system.add_rule.error.value_error_kwargs_path": { @@ -50,12 +50,6 @@ "rust": "skipped", "note": "verified 2026-09-21: apcore-rust has no decorator and no runtime type-hint inference; a module declares its schemas explicitly." }, - "event_system.deliver.error.ImportError_a2a": { - "python": "live", - "typescript": "skipped", - "rust": "skipped", - "note": "verified 2026-09-21: Python raises ImportError when aiohttp is absent. apcore-typescript uses global fetch and apcore-rust gates the HTTP path behind the `events` cargo feature at compile time, so neither has an import to fail." - }, "event_system.emit.input.event_type.not_empty": { "python": "live", "typescript": "skipped", diff --git a/docs/features/acl-system.md b/docs/features/acl-system.md index 7af110fe..1827e42f 100644 --- a/docs/features/acl-system.md +++ b/docs/features/acl-system.md @@ -428,7 +428,7 @@ acl: ``` === "TypeScript" ```typescript - import { ACL, APCore, Config } from "apcore-js"; + import { ACL, APCore, Config } from "apcore-js/full"; // APCore calls ACL.discover(config) and attaches the result. const app = new APCore({ config: Config.load("apcore.yaml") }); @@ -813,7 +813,7 @@ Condition handlers are registered at runtime into a process-wide registry, and a ``` === "TypeScript" ```typescript - import { ACL, APCore, Context, createIdentity } from "apcore-js"; + import { ACL, APCore, Context, createIdentity } from "apcore-js/full"; // Load ACL from YAML (synchronous) const acl = ACL.load("acl.yaml"); diff --git a/docs/features/apcore-client.md b/docs/features/apcore-client.md index d8ede92a..3ebb853b 100644 --- a/docs/features/apcore-client.md +++ b/docs/features/apcore-client.md @@ -88,7 +88,7 @@ A supplied Registry or Executor can retain modules and middleware installed befo === "TypeScript" ```typescript - import { APCore, Config } from 'apcore-js'; + import { APCore, Config } from 'apcore-js/full'; const config = new Config({ sys_modules: { enabled: true } }); const client = new APCore({ config, failOnError: true }); @@ -417,7 +417,7 @@ Assumes an `apcore.yaml` with `sys_modules.enabled: true` and `sys_modules.event ``` === "TypeScript" ```typescript - import { APCore, Config } from "apcore-js"; + import { APCore, Config } from "apcore-js/full"; const client = new APCore({ config: Config.load("apcore.yaml") }); diff --git a/docs/features/approval-system.md b/docs/features/approval-system.md index c4a1a582..fc9b273c 100644 --- a/docs/features/approval-system.md +++ b/docs/features/approval-system.md @@ -248,15 +248,15 @@ These handlers are provided by the respective bridge packages, not by apcore cor An `ExecutionPolicy` is an execution-time governance layer attached to the Executor (§7.9). It lets an operator change the governance of already-registered modules without editing them: - **`rules`** — `PolicyRule`s, each with a module-ID `pattern` (ACL wildcard semantics) and optional overrides for `requires_approval` and `destructive` (unset = keep the module's value), plus a `reason` for the audit trail. The most specific matching rule wins (ACL specificity scoring); on a tie the more restrictive rule wins. A matched override beats the module's own declaration. -- **`gate_destructive`** — when true, a module whose effective `destructive` is true needs approval even if `requires_approval` is false. -- **`strict`** — when true, a call that needs approval but has no `ApprovalHandler` fails closed with `ApprovalDeniedError` instead of being skipped with a warning. +- **`gate_destructive`** defaults to true and requires approval for a module whose effective `destructive` is true. +- **`strict`** defaults to true and denies calls requiring approval when no `ApprovalHandler` is configured. The gate applies these sources in order. 1. Combine the live module's `requires_approval` and `destructive` flags with the corresponding declared metadata flags. A true value from either source counts. The registry can receive those declarations from `*.binding.yaml`, `*_meta.yaml`, `metadata=`, or a Rust `ModuleDescriptor` (D-96, D-125). 2. Resolve the module-scoped requirement using the winning policy rule, if any, then add the requirement from `gate_destructive` when it applies. A policy rule can override a module annotation. 3. Combine that result with the ACL's `approval: required` decision for this invocation. If either requires approval, the gate requires approval. A policy override cannot clear the ACL's requirement. -4. Enforce the resulting requirement using the `ApprovalHandler`, or deny it under strict policy if the handler is absent. With neither configured, the gate warns and continues. +4. Ask the `ApprovalHandler` when approval is required. The default strict gate denies the call if the handler is absent. An explicit `strict: false` policy warns and continues in that case. Built-in policy rules match on the module ID. The invocation arguments reach policy resolution for the audit trail after `_approval_token` is stripped (§7.9.6). @@ -488,7 +488,7 @@ The emitter is the one given to the Executor: `Executor(registry, event_emitter= ## Testing Strategy - **Union tests** verify that the gate fires when any single governance source requires approval (annotation, declared metadata, ACL `approval: required`, policy rule, `gate_destructive`) and that a `false` in one source never cancels a `true` in another. -- **Skip tests** confirm the gate is skipped (with a warning) when no handler is set, and fails closed when `strict` is set. +- **Default and opt-out tests** cover zero executions for a denied call and the warning from an explicit non-strict policy. - **Handler tests** confirm each built-in handler returns the expected `ApprovalResult` status. - **Error mapping tests** verify that `rejected` → `ApprovalDeniedError`, `timeout` → `ApprovalTimeoutError`, `pending` → `ApprovalPendingError`, and that a handler exception propagates unchanged. - **Token tests** verify that `_approval_token` is removed from the inputs on every path and routed to `check_approval`. diff --git a/docs/features/async-tasks.md b/docs/features/async-tasks.md index 9632e454..634871d8 100644 --- a/docs/features/async-tasks.md +++ b/docs/features/async-tasks.md @@ -67,7 +67,7 @@ A task waiting for its next retry attempt is `pending` with `retry_count > 0`; t ``` === "TypeScript" ```typescript - import type { TaskStatus } from "apcore-js"; + import type { TaskStatus } from "apcore-js/full"; interface TaskInfo { readonly taskId: string; @@ -160,7 +160,7 @@ A task waiting for its next retry attempt is `pending` with `retry_count > 0`; t === "TypeScript" ```typescript import { Type } from "@sinclair/typebox"; - import { APCore, AsyncTaskManager, TaskStatus } from "apcore-js"; + import { APCore, AsyncTaskManager, TaskStatus } from "apcore-js/full"; const client = new APCore(); client.module({ @@ -323,7 +323,7 @@ Task records live in a `TaskStore`. Every method is asynchronous in every SDK so ``` === "TypeScript" ```typescript - import type { TaskInfo, TaskStatus } from "apcore-js"; + import type { TaskInfo, TaskStatus } from "apcore-js/full"; interface TaskStore { save(task: TaskInfo): Promise; @@ -368,7 +368,7 @@ Injecting a store: ``` === "TypeScript" ```typescript - import { APCore, AsyncTaskManager, InMemoryTaskStore } from "apcore-js"; + import { APCore, AsyncTaskManager, InMemoryTaskStore } from "apcore-js/full"; const client = new APCore(); @@ -423,7 +423,7 @@ The class is exported at the package root as `AsyncRetryConfig` in all three SDK ``` === "TypeScript" ```typescript - import { APCore, AsyncRetryConfig, AsyncTaskManager } from "apcore-js"; + import { APCore, AsyncRetryConfig, AsyncTaskManager } from "apcore-js/full"; const client = new APCore(); const manager = new AsyncTaskManager({ executor: client.executor }); @@ -496,7 +496,7 @@ The reaper is an opt-in background task that periodically deletes terminal tasks ``` === "TypeScript" ```typescript - import { APCore, AsyncTaskManager } from "apcore-js"; + import { APCore, AsyncTaskManager } from "apcore-js/full"; const client = new APCore(); const manager = new AsyncTaskManager({ executor: client.executor }); diff --git a/docs/features/call-chain-guard.md b/docs/features/call-chain-guard.md index 2ddaafae..fe9b70fd 100644 --- a/docs/features/call-chain-guard.md +++ b/docs/features/call-chain-guard.md @@ -176,7 +176,7 @@ The same keys can be set programmatically before the client is built: ``` === "TypeScript" ```typescript - import { APCore, Config } from "apcore-js"; + import { APCore, Config } from "apcore-js/full"; const config = Config.fromDefaults(); config.set("executor.max_call_depth", 16); diff --git a/docs/features/config-bus.md b/docs/features/config-bus.md index 14e0b51d..0416e759 100644 --- a/docs/features/config-bus.md +++ b/docs/features/config-bus.md @@ -123,7 +123,7 @@ There are three ways environment variables can feed into config: === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; Config.envMap({ PORT: 'port', DATABASE_URL: 'db_url' }); @@ -163,7 +163,7 @@ Global env_map maps to the **config root level**, not inside any namespace. This === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; Config.registerNamespace({ name: 'myapp', @@ -211,7 +211,7 @@ Namespace env_map maps into the specified namespace. Use for env vars with well- === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; Config.registerNamespace({ name: 'myapp' }); // envPrefix auto-derived as "MYAPP" @@ -268,7 +268,7 @@ The same bare env var name cannot appear in more than one env_map (global or nam === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; Config.envMap({ PORT: 'port' }); Config.registerNamespace({ @@ -324,7 +324,7 @@ Matches the env var suffix against the `defaults` tree structure. Flat keys matc === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; Config.registerNamespace({ name: 'myapp', @@ -441,7 +441,7 @@ env_map / env_prefix overrides > YAML file > namespace defaults === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; const config = Config.load('apcore.yaml'); @@ -494,7 +494,7 @@ Attach data from a file or in-memory dict to a namespace. Mounted data is merged === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; const config = Config.load('apcore.yaml'); config.mount('my-plugin', { fromDict: { timeout: 10000 } }); @@ -542,7 +542,7 @@ Re-read the source YAML, re-detect mode, re-apply namespace defaults, env overri === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; const config = Config.load('apcore.yaml'); config.reload(); @@ -602,7 +602,7 @@ The discovery entry point differs by SDK: Python exposes the search as the modul ```typescript import process from 'node:process'; - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; Config.load('my-custom-config.yaml'); // explicit path process.env.APCORE_CONFIG_FILE = 'custom.yaml'; // via env var @@ -719,14 +719,11 @@ Every key in `schemas/apcore-config.schema.json` is accepted, but 16 of them are | `logging.level` | deprecated, warns | construct a `ContextLogger` and pass it to `ObsLoggingMiddleware(logger=...)`; log from modules through the host application's logger (D-67) | | `logging.format` | deprecated, warns | as for `logging.level` | | `observability.metrics.enabled` | deprecated, warns | pass a `MetricsCollector` to the client (`APCore(metrics_collector=...)`) | -| `observability.metrics.exporter` | deprecated, warns | construct the exporter (e.g. `PrometheusExporter`) in code | +| `observability.metrics.exporter` | deprecated, warns | pass the Core text renderer to a host-owned listener | | `extensions.lazy_load` | inert | — (discovery runs on an explicit `discover()` call) | | `extensions.namespace` | inert | — | | `id_map.auto_detect` | inert | — (a configured ID map is always applied) | | `middleware.disabled` | inert | remove middleware in code, or remove steps with `pipeline.remove` | -| `project.version` | inert | — | -| `sys_modules.usage.bucketing_strategy` | inert | — | -| `sys_modules.usage.retention_hours` | inert | — | | `$schema` | inert by design | an editor hint; never read at runtime | `extensions.auto_discover` is **partial**: only `validate()` reads it (for a semantic warning). Setting it to `false` does not stop discovery. @@ -830,7 +827,7 @@ An SDK **MUST NOT** return a boolean or a "list of problems" in place of raising === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; const namespaces = Config.registeredNamespaces(); // [{ name: 'observability', envPrefix: 'APCORE_OBSERVABILITY', hasSchema: false }, ...] @@ -862,7 +859,7 @@ An SDK **MUST NOT** return a boolean or a "list of problems" in place of raising === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; Config.registerNamespace({ name: 'myapp' }); const cfg = Config.load('apcore.yaml'); @@ -908,7 +905,7 @@ An SDK **MUST NOT** return a boolean or a "list of problems" in place of raising === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; Config.envMap({ PORT: 'port' }); Config.registerNamespace({ @@ -979,7 +976,7 @@ An SDK **MUST NOT** return a boolean or a "list of problems" in place of raising === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; Config.envMap({ PORT: 'port', DATABASE_URL: 'db_url' }); Config.registerNamespace({ diff --git a/docs/features/core-executor.md b/docs/features/core-executor.md index 743d7c2a..5c37acbe 100644 --- a/docs/features/core-executor.md +++ b/docs/features/core-executor.md @@ -36,7 +36,7 @@ The standard strategy runs eleven steps, in this order in all three SDKs: 4. **`acl_check`** — Evaluates the attached ACL for (`caller_id`, or `@external` when it is null; target module ID; Context). A denial raises `ACL_DENIED`. With no ACL attached the step allows the call. A rule carrying `approval: required` is recorded for Step 5. -5. **`approval_gate`** — Engages when **any** of these requires approval: the module's `requires_approval` annotation, the registry descriptor/metadata (D-96, D-125), an ACL rule with `approval: required` ([§6.9](../spec/protocol-spec.md)), or an `ExecutionPolicy` with `gate_destructive` ([§7.9.2](../spec/protocol-spec.md)). The configured `ApprovalHandler` decides; rejected, timed-out and pending decisions raise `APPROVAL_DENIED`, `APPROVAL_TIMEOUT` and `APPROVAL_PENDING`. With no handler the gate is skipped with a warning, unless `ExecutionPolicy(strict=true)` makes it fail closed. See [Approval System](./approval-system.md). +5. **`approval_gate`** — Evaluates the module annotation, registry metadata, policy rules, and the call's ACL approval requirement. Destructive modules require approval by default. When approval is required, a configured `ApprovalHandler` decides. Rejected, timed-out and pending decisions raise `APPROVAL_DENIED`, `APPROVAL_TIMEOUT`, and `APPROVAL_PENDING`. Without a handler, the default gate raises `APPROVAL_DENIED` before running the module. See [Approval System](./approval-system.md). 6. **`middleware_before`** — Runs every middleware's `before()` in priority order; each may replace the inputs. A failure here runs the `on_error` chain. See [Middleware System](./middleware-system.md). diff --git a/docs/features/decorator-bindings.md b/docs/features/decorator-bindings.md index c5b023fc..ea58fb33 100644 --- a/docs/features/decorator-bindings.md +++ b/docs/features/decorator-bindings.md @@ -300,7 +300,7 @@ The pattern is matched against each file name (not recursively) with Algorithm A ``` === "TypeScript" ```typescript - import { BindingLoader, Config, Registry } from "apcore-js"; + import { BindingLoader, Config, Registry } from "apcore-js/full"; const config = Config.load("apcore.yaml"); // may set bindings.dir / bindings.pattern const registry = new Registry(); diff --git a/docs/features/error-history.md b/docs/features/error-history.md index 9c96411c..c7463268 100644 --- a/docs/features/error-history.md +++ b/docs/features/error-history.md @@ -92,7 +92,7 @@ TypeScript uses camelCase field names (`moduleId`, `aiGuidance`, `firstOccurred` === "TypeScript" ```typescript - import { ErrorHistory, ErrorHistoryMiddleware, ModuleError } from "apcore-js"; + import { ErrorHistory, ErrorHistoryMiddleware, ModuleError } from "apcore-js/full"; const history = new ErrorHistory({ maxEntriesPerModule: 50, maxTotalEntries: 1000 }); @@ -177,7 +177,7 @@ Every SDK exports the two functions, so you can compute a fingerprint without re === "TypeScript" ```typescript - import { computeFingerprint, normalizeMessage } from "apcore-js"; + import { computeFingerprint, normalizeMessage } from "apcore-js/full"; const message = "Order 48213 failed at 2026-09-16T10:30:00Z (request a1b2c3d4-e5f6-7890-abcd-ef1234567890)"; diff --git a/docs/features/event-system.md b/docs/features/event-system.md index fe60ac24..236448c6 100644 --- a/docs/features/event-system.md +++ b/docs/features/event-system.md @@ -21,7 +21,7 @@ With `sys_modules.enabled` and `sys_modules.events.enabled`, `APCore` creates th - Define the `EventSubscriber` protocol: an async `on_event()` plus optional `event_pattern`, `subscriber_id`, `subscriber_type`, `retry` and `on_failure` members. - Errors in one subscriber **MUST NOT** propagate to other subscribers or to the emitter's caller. - Retry failed deliveries per subscriber and emit `apcore.event.delivery_failed` when retries are exhausted. -- Provide built-in `webhook`, `a2a`, `file`, `stdout` and `filter` subscribers, and a registry of subscriber factories for config-driven instantiation. +- Provide built-in `webhook`, `file`, `stdout`, and `filter` subscribers, and a host-owned registry of factories for configured subscribers. ## Technical Design @@ -103,7 +103,7 @@ Events are immutable once emitted (Python `frozen=True`, TypeScript `readonly`, === "TypeScript" ```typescript - import type { ApCoreEvent, EventRetryConfig } from "apcore-js"; + import type { ApCoreEvent, EventRetryConfig } from "apcore-js/full"; export interface EventSubscriber { onEvent(event: ApCoreEvent): void | Promise; @@ -156,7 +156,7 @@ Python's `EventEmitter.subscribe()` raises `TypeError` when `on_event` is not a === "TypeScript" ```typescript - import type { ApCoreEvent, EventSubscriber } from "apcore-js"; + import type { ApCoreEvent, EventSubscriber } from "apcore-js/full"; export declare class EventEmitter { constructor(maxPending?: number); // default 1000 @@ -214,7 +214,7 @@ Python's `EventEmitter.subscribe()` raises `TypeError` when `on_event` is not a ``` === "TypeScript" ```typescript - import { APCore, Config, type ApCoreEvent } from "apcore-js"; + import { APCore, Config, type ApCoreEvent } from "apcore-js/full"; const client = new APCore({ config: Config.load("apcore.yaml") }); // sys_modules.events.enabled: true @@ -266,7 +266,7 @@ Python's `EventEmitter.subscribe()` raises `TypeError` when `on_event` is not a ``` === "TypeScript" ```typescript - import { APCore, Config, type EventSubscriber } from "apcore-js"; + import { APCore, Config, type EventSubscriber } from "apcore-js/full"; const client = new APCore({ config: Config.load("apcore.yaml") }); @@ -317,161 +317,65 @@ A subscriber whose pattern is `"*"` receives every event **except** `apcore.even | Type | Delivers to | Config fields (besides `id`, `retry`) | |------|-------------|---------------------------------------| | `webhook` | HTTP POST of the event JSON | `url`, `headers`, `timeout_ms` (default 5000); `retry_count` (retries after the first attempt, i.e. `max_attempts = retry_count + 1`; ignored when `retry` is present) | -| `a2a` | HTTP POST of `{"skillId": …, "event": {…}}` | `platform_url`, `auth` (string → `Authorization: Bearer `, map → merged into headers), `skill_id` (default `"apevo.event_receiver"`), `timeout_ms` | | `file` | Appends to a local file | `path`, `append` (default `true`), `format` (`json` default / `text`), `rotate_bytes` | | `stdout` | Standard output | `format` (`text` default / `json`), `level_filter` | | `filter` | Another subscriber, for matching events only | `delegate_type`, `delegate_config`, `include_events`, `exclude_events` | -- **HTTP delivery (`webhook`, `a2a`).** Sends `Content-Type: application/json`. 2xx is success. 5xx, connection errors and timeouts raise inside the subscriber, so the emitter's retry policy applies. 4xx is logged as a permanent failure and is not retried. Python needs the `events` extra (`pip install apcore[events]`, which provides `aiohttp`) — without it every delivery fails with `ImportError` and takes the retry/dead-letter path; Rust needs the `events` cargo feature. +- **Webhook delivery.** Sends `Content-Type: application/json`. A successful 2xx response completes delivery. The emitter applies retry policy to 5xx, connection failures, and timeouts. Install Python's `events` extra or enable Rust's `events` feature to use the built-in HTTP transport. - **`filter`.** When `include_events` is present it is decisive: an event is forwarded if it matches any entry and discarded otherwise, and `exclude_events` is not consulted. Otherwise an event matching any `exclude_events` entry is discarded. Both lists use A25. Because a pattern that fails to match means the event is *delivered*, `exclude_events` fails open — keep its patterns simple and test them. - **`id`.** Every subscriber has a stable `subscriber_id`; when the config omits `id`, the SDK generates `"-"`. It appears in dead-letter and circuit events. -Constructors of the two HTTP subscribers: - -=== "Python" - - ```python - from apcore.events import A2ASubscriber, EventRetryConfig, WebhookSubscriber - - webhook = WebhookSubscriber( - "https://example.com/hook", - headers={"X-Source": "apcore"}, - timeout_ms=5000, - id="audit-hook", - retry=EventRetryConfig(max_attempts=5), - event_pattern="apcore.*", - ) - - a2a = A2ASubscriber( - "https://agent.example.com", - auth="bearer-token-123", - timeout_ms=5000, - skill_id="myapp.event_receiver", - id="agent-bridge", - ) - ``` - -=== "TypeScript" - - ```typescript - import { A2ASubscriber, WebhookSubscriber } from "apcore-js"; - - const webhook = new WebhookSubscriber( - "https://example.com/hook", - { "X-Source": "apcore" }, - { timeoutMs: 5000, id: "audit-hook", retry: { maxAttempts: 5 } }, - ); - - const a2a = new A2ASubscriber( - "https://agent.example.com", - "bearer-token-123", - { timeoutMs: 5000, id: "agent-bridge", skillId: "myapp.event_receiver" }, - ); - ``` - -=== "Rust" - - ```rust - use apcore::events::subscribers::{A2AAuth, A2ASubscriber}; - use apcore::events::{EventRetryConfig, WebhookSubscriber}; - - fn main() { - let mut webhook = WebhookSubscriber::new("audit-hook", "https://example.com/hook", "apcore.*") - .with_retry(EventRetryConfig { max_attempts: 5, ..Default::default() }); - webhook.headers.insert("X-Source".to_string(), "apcore".to_string()); - - let mut a2a = A2ASubscriber::new("agent-bridge", "https://agent.example.com", "*") - .with_skill_id("myapp.event_receiver"); - a2a.auth = Some(A2AAuth::Bearer("bearer-token-123".to_string())); - } - ``` - ### Subscriber Factories -Config-driven subscribers are built by factories keyed by `type`. The five built-in types are registered automatically; add your own with `register_subscriber_type` — the factory is called once per configured entry and receives that entry's config object: +The host's factory registry builds subscribers keyed by `type`, including +filter delegates. The factory receives the configuration for one subscriber. +Use the [A2A adapter](https://github.com/aiperceivable/apcore-surfaces/tree/main/a2a) +to add delivery to an A2A receiver. === "Python" ```python - from apcore.events import ApCoreEvent - from apcore.sys_modules.registration import register_subscriber_type - - - class SlackSubscriber: - subscriber_type = "slack" + from apcore.events import SubscriberRegistry, StdoutSubscriber + from apcore.full import APCore, Config - def __init__(self, webhook_url: str, channel: str = "#general") -> None: - self.webhook_url = webhook_url - self.channel = channel - - async def on_event(self, event: ApCoreEvent) -> None: - print(f"post {event.event_type} to {self.channel}") - - - register_subscriber_type( - "slack", - lambda config: SlackSubscriber(config["webhook_url"], config.get("channel", "#general")), - ) + subscribers = SubscriberRegistry() + subscribers.register("console", lambda config: StdoutSubscriber(output_format=config.get("format", "text"))) + client = APCore(config=Config.load("apcore.yaml"), subscriber_registry=subscribers) ``` + === "TypeScript" ```typescript - import { registerSubscriberType, type ApCoreEvent, type EventSubscriber } from "apcore-js"; - - class SlackSubscriber implements EventSubscriber { - readonly subscriberType = "slack"; - - constructor( - private readonly webhookUrl: string, - private readonly channel: string, - ) {} - - async onEvent(event: ApCoreEvent): Promise { - console.log(`post ${event.eventType} to ${this.channel} via ${this.webhookUrl}`); - } - } - - registerSubscriberType("slack", (config) => - new SlackSubscriber(String(config.webhook_url), String(config.channel ?? "#general")), - ); + import { Config } from "apcore-js/config"; + import { StdoutSubscriber } from "apcore-js/events"; + import { APCore } from "apcore-js/full"; + import { createSysModulesPlugin } from "apcore-js/sys-modules"; + + const client = new APCore({ + config: Config.load("apcore.yaml"), + plugins: [createSysModulesPlugin({ + subscriberFactories: { console: () => new StdoutSubscriber() }, + })], + }); ``` + === "Rust" ```rust - use apcore::errors::ModuleError; - use apcore::events::{register_subscriber_type, ApCoreEvent, EventSubscriber}; - use async_trait::async_trait; - use serde_json::Value; - - #[derive(Debug)] - struct SlackSubscriber { - webhook_url: String, - channel: String, - } - - #[async_trait] - impl EventSubscriber for SlackSubscriber { - fn subscriber_type(&self) -> &str { "slack" } - - async fn on_event(&self, event: &ApCoreEvent) -> Result<(), ModuleError> { - println!("post {} to {} via {}", event.event_type, self.channel, self.webhook_url); - Ok(()) - } - } - - fn main() { - register_subscriber_type( - "slack", - Box::new(|config: &Value| { - let subscriber = SlackSubscriber { - webhook_url: config["webhook_url"].as_str().unwrap_or_default().to_string(), - channel: config["channel"].as_str().unwrap_or("#general").to_string(), - }; - Ok(Box::new(subscriber) as Box) - }), - ); + use std::path::Path; + + use apcore::events::{StdoutSubscriber, SubscriberRegistry}; + use apcore::{APCore, APCoreOptions, Config}; + + fn main() -> Result<(), Box> { + let mut subscribers = SubscriberRegistry::new(); + subscribers.register("console", |_| Ok(Box::new(StdoutSubscriber::default()))); + let options = APCoreOptions { + config: Some(Config::load(Path::new("apcore.yaml"))?), + ..Default::default() + }; + let _client = APCore::try_start_with_subscribers(options, &subscribers)?; + Ok(()) } ``` -The registry also offers `unregister_subscriber_type(type_name)`, `reset_subscriber_registry()` (back to the built-ins) and a function that builds one subscriber from a config object (`create_subscriber_from_config` / `createSubscriberFromConfig` / `create_subscriber`). Python additionally re-exports the registration function as `apcore.events.register_subscriber_factory`. - ### Configuration ```yaml @@ -500,17 +404,14 @@ sys_modules: - type: "filter" id: "health-pager" - delegate_type: "a2a" + delegate_type: "webhook" delegate_config: - platform_url: "https://agent.example.com" - auth: "bearer-token-123" - skill_id: "myapp.event_receiver" + url: "https://events.example.com/health" include_events: - "apcore.health.*" - - type: "slack" # a type added with register_subscriber_type - webhook_url: "https://hooks.slack.com/services/..." - channel: "#alerts" + - type: "console" # supplied by this host's factory registry + format: "text" ``` ## Event Naming Convention @@ -658,7 +559,7 @@ A subscriber may also define `on_failure(event, error, attempt_count)`. It is in ``` === "TypeScript" ```typescript - import { EventEmitter, type ApCoreEvent, type EventSubscriber } from "apcore-js"; + import { EventEmitter, type ApCoreEvent, type EventSubscriber } from "apcore-js/full"; class HealthAlertSubscriber implements EventSubscriber { readonly eventPattern = "apcore.health.*"; @@ -738,7 +639,7 @@ Python wraps every subscriber created from `sys_modules.events.subscribers` in a | File | Purpose | |------|---------| | `src/apcore/events/emitter.py` | `EventEmitter`, `ApCoreEvent`, `EventSubscriber`, retry and dead-letter delivery | - | `src/apcore/events/subscribers.py` | `WebhookSubscriber`, `A2ASubscriber`, `FileSubscriber`, `StdoutSubscriber`, `FilterSubscriber` | + | `src/apcore/events/subscribers.py` | Webhook, file, stdout, and filter delivery | | `src/apcore/events/circuit_breaker.py` | `CircuitBreakerWrapper` | | `src/apcore/events/retry.py` | `EventRetryConfig` | | `src/apcore/sys_modules/registration.py` | Subscriber factory registry, config-driven subscribers | @@ -845,22 +746,6 @@ Python wraps every subscriber created from `sys_modules.events.subscribers` in a - thread_safe: true - pure: false (outbound HTTP) -## Contract: A2ASubscriber.on_event - -### Inputs -- `event` (`ApCoreEvent`, required) — sent as `{"skillId": , "event": {}}` to `platform_url`. A string `auth` becomes `Authorization: Bearer `; a map is merged into the headers. - -### Errors -- As for `WebhookSubscriber.on_event`: 5xx, connection errors and timeouts go through the retry policy and the dead-letter path; 4xx is logged and not retried. - -### Returns -- Nothing on 2xx. - -### Properties -- async: true -- thread_safe: true -- pure: false (outbound HTTP) - ## Contract: CircuitBreakerWrapper._on_failure Internal in every SDK (Python `_on_failure`, TypeScript `_onFailure`, Rust private `on_failure`); specified because all three must behave the same. diff --git a/docs/features/execution-pipeline.md b/docs/features/execution-pipeline.md index 82c81547..696b15d3 100644 --- a/docs/features/execution-pipeline.md +++ b/docs/features/execution-pipeline.md @@ -567,7 +567,7 @@ A `type` names a factory registered in code before the executor is built. `handl === "TypeScript" ```typescript - import { APCore, Config, registerStepType } from 'apcore-js'; + import { APCore, Config, registerStepType } from 'apcore-js/full'; import type { PipelineContext, Step, StepResult } from 'apcore-js'; class RateLimitStep implements Step { diff --git a/docs/features/extension-system.md b/docs/features/extension-system.md index edfeaf03..f358ba90 100644 --- a/docs/features/extension-system.md +++ b/docs/features/extension-system.md @@ -105,7 +105,7 @@ The Extension System provides a pluggable architecture for customizing and exten ``` === "TypeScript" ```typescript - import { ExtensionManager } from "apcore-js"; + import { ExtensionManager } from "apcore-js/full"; const manager = new ExtensionManager(); diff --git a/docs/features/metrics-and-usage.md b/docs/features/metrics-and-usage.md index c35e819e..5555837d 100644 --- a/docs/features/metrics-and-usage.md +++ b/docs/features/metrics-and-usage.md @@ -8,8 +8,8 @@ description: "MetricsCollector and MetricsMiddleware, Prometheus export, per-mod apcore has two collectors for call statistics: -- **`MetricsCollector`** — Prometheus-style counters and histograms, fed by `MetricsMiddleware`. Read by the `system.health.*` modules, `PlatformNotifyMiddleware` and `PrometheusExporter`. -- **`UsageCollector`** — per-module call records in hourly buckets, fed by `UsageMiddleware`. Read by the `system.usage.*` modules, `PrometheusExporter` and `PeriodicUsageExporter`. +- **`MetricsCollector`** tracks Prometheus-style counters and histograms fed by `MetricsMiddleware`. The health modules and the Prometheus renderer read these metrics. +- **`UsageCollector`** groups per-module call records in hourly buckets. The usage modules, the Prometheus renderer, and `PeriodicUsageExporter` read these records. Neither is configured from `apcore.yaml`: `observability.metrics.enabled` and `observability.metrics.exporter` are inert, and so are `sys_modules.usage.retention_hours` and `sys_modules.usage.bucketing_strategy` (see [Which config keys work](./observability.md#which-config-keys-work)). You construct the collectors and middlewares yourself, or let [system modules](./system-modules.md) create `UsageCollector`, `ErrorHistory` and their middlewares. `MetricsMiddleware` is never installed for you — add it when you want metrics. @@ -43,27 +43,14 @@ The [Observability quick start](./observability.md#quick-start) and the [Prometh ## Prometheus export -`PrometheusExporter` serves the collectors over HTTP for scraping. It is constructed and started by your application — no configuration key starts it (`observability.prometheus.*` does not exist). +Render the current collectors to Prometheus text and pass the render callback to +the [Toolkit HTTP listener](https://github.com/aiperceivable/apcore-surfaces/tree/main/toolkit). +It serves `GET /metrics`, `GET /healthz`, and `GET /readyz`. Mark the listener +ready after the application finishes startup. -| Endpoint | Response | -|---|---| -| `GET {path}` (default `/metrics`) | Prometheus text: the `MetricsCollector` families, plus the usage families below when a `UsageCollector` is attached | -| `GET /healthz` | `200 OK` — liveness | -| `GET /readyz` | `200 OK` after `mark_ready()` / `markReady()`, `503` before | - -Attaching a `UsageCollector` adds the `apcore_usage_calls_24h` gauge (by `module_id` and `status`), `apcore_usage_error_rate`, and `apcore_usage_p50_latency_ms` / `p95` / `p99`. The rolling call count can decrease as records age out. The deprecated `apcore_usage_calls_total` name is a gauge alias with the same values and labels. Use `apcore_usage_calls_24h` for rolling counts and the cumulative `apcore_module_calls_total` counter for queries such as `rate()` and `increase()`. The Rust exporter always emits the three standard `apcore_module_*` families, even before the first observation. - -| | Construct | Start / stop | -|---|---|---| -| Python | `PrometheusExporter(collector, usage_collector=None)` | `start(port=9090, path="/metrics", host="127.0.0.1")` (background thread), `stop()` | -| TypeScript | `new PrometheusExporter({ collector, usageCollector })` | `start({ port, path })`; `await stop()` | -| Rust | `PrometheusExporter::new(collector).with_usage_collector(usage)` | `start(port, path).await?` (spawns a task, returns `io::Result`), `shutdown()`, `local_addr()` | - -The Python listener binds to IPv4 loopback by default. Set `host` explicitly when metrics need to be reachable from a remote scraper. The Rust listener binds to all IPv4 interfaces. Both listeners limit concurrent connections and set timeouts for request headers and response writes. Python `stop()` closes the listener. Rust `shutdown()` signals it to close, and `local_addr()` reports `None` once the listening socket is released. - -`export()` returns the same text the endpoint serves. It reads live collector state. - -Applications that own the HTTP listener can render the same response without opening a socket. Pass one of these render callbacks to the [Toolkit Prometheus listener](https://github.com/aiperceivable/apcore-surfaces/tree/main/toolkit) or to the application's existing HTTP server. +The usage collector adds the rolling `apcore_usage_calls_24h` gauge, error +rate, and latency percentiles. Use the cumulative `apcore_module_calls_total` +counter for `rate()` or `increase()`. === "Python" ```python @@ -76,12 +63,11 @@ Applications that own the HTTP listener can render the same response without ope === "TypeScript" ```typescript - import { MetricsCollector, PrometheusExporter, UsageCollector } from "apcore-js"; + import { MetricsCollector, UsageCollector, renderPrometheusMetrics } from "apcore-js/observability"; - const collector = new MetricsCollector(); - const usageCollector = new UsageCollector(); - const renderer = new PrometheusExporter({ collector, usageCollector }); - console.log(renderer.export()); + const metrics = new MetricsCollector(); + const usage = new UsageCollector(); + console.log(renderPrometheusMetrics(metrics, usage)); ``` === "Rust" @@ -95,89 +81,6 @@ Applications that own the HTTP listener can render the same response without ope } ``` -The following examples use the built-in HTTP exporter. - -=== "Python" - ```python - from apcore import APCore - from apcore.observability import ( - MetricsCollector, - MetricsMiddleware, - PrometheusExporter, - UsageCollector, - UsageMiddleware, - ) - - metrics = MetricsCollector() - usage = UsageCollector() - - client = APCore() - client.use(MetricsMiddleware(metrics)) - client.use(UsageMiddleware(usage)) - - exporter = PrometheusExporter(metrics, usage_collector=usage) - exporter.start(port=9090, path="/metrics") - exporter.mark_ready() # /readyz answers 200 from now on - - # ... serve traffic ... - - exporter.stop() - ``` - -=== "TypeScript" - ```typescript - import { - APCore, - MetricsCollector, - MetricsMiddleware, - PrometheusExporter, - UsageCollector, - UsageMiddleware, - } from "apcore-js"; - - const metrics = new MetricsCollector(); - const usage = new UsageCollector(); - - const client = new APCore(); - client.use(new MetricsMiddleware(metrics)); - client.use(new UsageMiddleware(usage)); - - const exporter = new PrometheusExporter({ collector: metrics, usageCollector: usage }); - exporter.start({ port: 9090, path: "/metrics" }); - exporter.markReady(); // /readyz answers 200 from now on - - // ... serve traffic ... - - await exporter.stop(); - ``` - -=== "Rust" - ```rust - use apcore::observability::{ - MetricsCollector, MetricsMiddleware, PrometheusExporter, UsageCollector, UsageMiddleware, - }; - use apcore::APCore; - - #[tokio::main] - async fn main() -> Result<(), Box> { - let metrics = MetricsCollector::new(); - let usage = UsageCollector::new(); - - let client = APCore::new(); - client.use_middleware(Box::new(MetricsMiddleware::new(metrics.clone())))?; - client.use_middleware(Box::new(UsageMiddleware::new(usage.clone())))?; - - let exporter = PrometheusExporter::new(metrics).with_usage_collector(usage); - exporter.start(9090, "/metrics").await?; - exporter.mark_ready(); // /readyz answers 200 from now on - - // ... serve traffic ... - - exporter.shutdown(); - Ok(()) - } - ``` - For Prometheus Operator auto-discovery, bind to an address the scraper can reach and add these pod annotations. ```yaml @@ -212,7 +115,7 @@ A module with no recorded calls is not an error: it reports zero counts, a zero- ## UsageExporter (push-style) -`PrometheusExporter` is scraped; a `UsageExporter` pushes. `PeriodicUsageExporter` polls a `UsageCollector` on an interval and hands the summary to your exporter — an HTTP poster, a Kafka producer, a file writer. apcore ships only `NoopUsageExporter` (drops everything) and the periodic driver; transport-specific exporters are yours to write. +A Prometheus listener answers scrape requests. `PeriodicUsageExporter` polls a `UsageCollector` and passes each summary to a host-supplied `UsageExporter`. The built-in `NoopUsageExporter` discards summaries. | | Exporter interface | Driver | |---|---|---| @@ -254,8 +157,8 @@ A module with no recorded calls is not an error: it reports zero counts, a zero- === "TypeScript" ```typescript - import { PeriodicUsageExporter, UsageCollector } from "apcore-js"; - import type { UsageExporter } from "apcore-js"; + import { PeriodicUsageExporter, UsageCollector } from "apcore-js/full"; + import type { UsageExporter } from "apcore-js/full"; class PrintUsageExporter implements UsageExporter { async export(summary: Record): Promise { @@ -395,8 +298,8 @@ An alert fires once per module and does not fire again until the module has reco === "TypeScript" ```typescript - import { ErrorHistory, InMemoryStorageBackend, MetricsCollector, UsageCollector } from "apcore-js"; - import type { StorageBackend } from "apcore-js"; + import { ErrorHistory, InMemoryStorageBackend, MetricsCollector, UsageCollector } from "apcore-js/full"; + import type { StorageBackend } from "apcore-js/full"; // One backend shared by all three collectors; namespaces keep them apart. const backend = new InMemoryStorageBackend(); diff --git a/docs/features/observability.md b/docs/features/observability.md index eeccda34..22c3769c 100644 --- a/docs/features/observability.md +++ b/docs/features/observability.md @@ -12,7 +12,7 @@ apcore instruments module calls through ordinary middleware, so observability pl |---|---|---| | Tracing — spans, sampling, exporters, processors, W3C propagation | `TracingMiddleware`, `BatchSpanProcessor`, `TraceContext` | this page | | Structured logging | `ContextLogger`, `ObsLoggingMiddleware` | this page | -| Metrics, usage analytics, Prometheus, storage backends | `MetricsCollector`, `UsageCollector`, `PrometheusExporter`, `StorageBackend` | [Metrics and Usage](./metrics-and-usage.md) | +| Metrics, usage analytics, Prometheus text, storage backends | `MetricsCollector`, `UsageCollector`, Prometheus renderer, `StorageBackend` | [Metrics and Usage](./metrics-and-usage.md) | | Recent-error tracking and fingerprints | `ErrorHistory`, `ErrorHistoryMiddleware` | [Error History](./error-history.md) | | Secret redaction in logs and captured I/O | `x-sensitive`, `obs.redaction.*`, `RedactionConfig` | [Redaction](./redaction.md) | @@ -99,7 +99,7 @@ Or build the stack yourself. Register the middlewares outermost first — tracin MetricsMiddleware, ObsLoggingMiddleware, TracingMiddleware, - } from "apcore-js"; + } from "apcore-js/full"; const exporter = new InMemoryExporter(); const metrics = new MetricsCollector(); @@ -306,7 +306,7 @@ Python passes a processor straight to `TracingMiddleware(processor=…)`. In Rus === "TypeScript" ```typescript - import { BatchSpanProcessor, OTLPExporter, TracingMiddleware } from "apcore-js"; + import { BatchSpanProcessor, OTLPExporter, TracingMiddleware } from "apcore-js/full"; const processor = new BatchSpanProcessor({ exporter: new OTLPExporter({ endpoint: "http://otel-collector:4318/v1/traces" }), diff --git a/docs/features/redaction.md b/docs/features/redaction.md index 77d18271..46ede65a 100644 --- a/docs/features/redaction.md +++ b/docs/features/redaction.md @@ -170,7 +170,7 @@ Things to know: === "TypeScript" ```typescript - import { APCore, Config, ObsLoggingMiddleware, RedactionConfig } from "apcore-js"; + import { APCore, Config, ObsLoggingMiddleware, RedactionConfig } from "apcore-js/full"; const config = Config.load("apcore.yaml"); // the file shown above const client = new APCore({ config }); // the executor's capture point uses obs.redaction.* diff --git a/docs/features/schema-system.md b/docs/features/schema-system.md index 3d6d97fe..2cc07a36 100644 --- a/docs/features/schema-system.md +++ b/docs/features/schema-system.md @@ -1,5 +1,5 @@ --- -description: "Schema loading, validation, $ref resolution bridging YAML to runtime schema objects; strategies yaml_first/native_first/yaml_only, x-* extensions, strict-mode export, export to MCP/OpenAI/Anthropic formats." +description: "Schema loading, validation, reference resolution, schema extensions, generic export and strict schema conversion." --- # Schema System @@ -256,8 +256,9 @@ Resolved schemas are cached in two levels: module ID → content hash, and conte === "Python" ```python - from apcore import Config - from apcore.schema import ExportProfile, SchemaExporter, SchemaLoader, SchemaValidator + from apcore.config import Config + from apcore.schema import SchemaLoader, SchemaValidator + from apcore.schema.strict import to_strict_schema # The loader reads schema.root / schema.strategy from the Config; # load() takes a MODULE ID, not a file path. @@ -272,13 +273,13 @@ Resolved schemas are cached in two levels: module ID → content hash, and conte if not result.valid: print(f"Validation failed ({result.error_code}): {result.errors}") - exporter = SchemaExporter() - mcp_tool = exporter.export(schema_def, ExportProfile.MCP) - print(mcp_tool) # {"name": "...", "description": "...", "inputSchema": {...}, ...} + print(to_strict_schema(schema_def.input_schema)) ``` === "TypeScript" ```typescript - import { Config, ExportProfile, SchemaExporter, SchemaLoader, SchemaValidator } from "apcore-js"; + import { SchemaValidator, toStrictSchema } from "apcore-js"; + import { Config } from "apcore-js/config"; + import { SchemaLoader } from "apcore-js/full"; // The loader reads schema.root / schema.strategy from the Config; // load() takes a MODULE ID and is synchronous. @@ -294,14 +295,12 @@ Resolved schemas are cached in two levels: module ID → content hash, and conte console.error(`Validation failed (${result.errorCode}):`, result.errors); } - const exporter = new SchemaExporter(); - const openaiTool = exporter.export(schemaDef, ExportProfile.OPENAI); - console.log(openaiTool); + console.log(toStrictSchema(schemaDef.inputSchema)); ``` === "Rust" ```rust use apcore::errors::ModuleError; - use apcore::schema::{ExportProfile, SchemaExporter, SchemaLoader, SchemaValidator}; + use apcore::schema::{to_strict_schema, SchemaLoader, SchemaValidator}; use apcore::Config; use serde_json::json; @@ -321,14 +320,15 @@ Resolved schemas are cached in two levels: module ID → content hash, and conte eprintln!("Validation failed: {:?}", result.errors); } - // export() takes the schema Value, a profile, and optional ExportOptions. - let exporter = SchemaExporter::new(); - let anthropic_tool = exporter.export(&schema_def.input_schema, ExportProfile::Anthropic, None)?; - println!("{anthropic_tool}"); + println!("{}", to_strict_schema(&schema_def.input_schema)); Ok(()) } ``` +The Registry exports schema and description data independently of the +publication protocol. Use [Surfaces MCP converters](https://github.com/aiperceivable/apcore-surfaces/tree/main/mcp) +for MCP, OpenAI, and Anthropic tool definitions. + ## Dependencies - The **Executor** validates inputs at pipeline step 7 (`input_validation`) and outputs at step 9 (`output_validation`) using the Schema System. @@ -343,7 +343,7 @@ Resolved schemas are cached in two levels: module ID → content hash, and conte | `schema/ref_resolver.py` | `RefResolver`: `$ref` resolution, self-reference vs. circular classification | | `schema/validator.py` | `SchemaValidator`: result-object validation and the raising `validate_input` / `validate_output` | | `schema/hardening.py` | `content_hash`, exhaustive union validation, `format` warnings | - | `schema/exporter.py` | `SchemaExporter`: MCP / OpenAI / Anthropic / generic export | + | `schema/exporter.py` | Generic schema export | | `schema/strict.py` | `to_strict_schema` (Algorithm A23) | | `schema/openai_strict.py` | OpenAI strict-mode compatibility detection | | `schema/annotations.py` | Merging YAML and code annotations, examples and metadata | diff --git a/docs/features/streaming.md b/docs/features/streaming.md index b4122e1b..44fed924 100644 --- a/docs/features/streaming.md +++ b/docs/features/streaming.md @@ -416,7 +416,7 @@ rules: Config, STREAMING_MARKER, createApprovalResult, - } from "apcore-js"; + } from "apcore-js/full"; import type { StreamingModule } from "apcore-js"; class EchoModule implements StreamingModule { diff --git a/docs/features/system-modules.md b/docs/features/system-modules.md index 6eed319a..fc70736c 100644 --- a/docs/features/system-modules.md +++ b/docs/features/system-modules.md @@ -542,7 +542,7 @@ Hot-reload one module from disk — or every module matching a pattern — witho | `reason` | string | *(required)* | Audit reason | | `lifecycle` | object | omitted | Opt into [managed reload](#managed-reload) with a configurable drain policy and a structured result | -`module_id` and `path_filter` are mutually exclusive (`MODULE_RELOAD_CONFLICT`). Supply one for a module reload. A `path_filter` matching nothing is a no-op with an empty `reloaded_modules`. Bulk reloads run in dependency order, leaves first. `reload_dependents` is deprecated and ignored (it warns once). To reload dependents, use a `path_filter` that covers them (D-121). +`module_id` and `path_filter` are mutually exclusive (`MODULE_RELOAD_CONFLICT`). Supply one for a module reload. A `path_filter` matching nothing returns an empty `reloaded_modules`. Bulk reloads run in dependency order, leaves first. To reload dependents, choose a `path_filter` that covers them (D-121). A selector that includes the reload controller itself returns `RELOAD_FAILED` before the operation changes any registration. Choose a module ID or glob that excludes `system.control.reload_module`. @@ -735,7 +735,7 @@ For an accepted operation, `success: false` indicates a failed reload and is del === "TypeScript" ```typescript - import { APCore, Config } from 'apcore-js'; + import { APCore, Config } from 'apcore-js/full'; const config = Config.load('apcore.yaml'); // sys_modules.enabled: true, events.enabled: true const client = new APCore({ config }); @@ -811,7 +811,7 @@ For an accepted operation, `success: false` indicates a failed reload and is del InMemoryAuditStore, Registry, registerSysModules, - } from 'apcore-js'; + } from 'apcore-js/full'; const config = Config.load('apcore.yaml'); // sys_modules.enabled: true, events.enabled: true const registry = new Registry({ config }); @@ -897,7 +897,7 @@ sys_modules: overrides_path: "/var/lib/apcore/overrides.yaml" ``` -`sys_modules.usage.retention_hours` and `sys_modules.usage.bucketing_strategy` are accepted but read by no SDK (see [Config Bus § Deprecated and inert keys](./config-bus.md#deprecated-and-inert-keys)). +`sys_modules.usage.retention_hours` sets how long the collector retains usage records. The supported `sys_modules.usage.bucketing_strategy` is `hourly`. ## Persistent overrides — pluggable `OverridesStore` @@ -1024,67 +1024,10 @@ The event bus is the minimum auditing surface: events are emitted whether or not ## Usage metrics in Prometheus -`PrometheusExporter` serves the usage collector's data alongside the call metrics when you attach it: - -- `apcore_usage_calls_total{module_id, status}` — counter -- `apcore_usage_error_rate{module_id}` — gauge (0.0–1.0) -- `apcore_usage_p50_latency_ms`, `apcore_usage_p95_latency_ms`, `apcore_usage_p99_latency_ms` `{module_id}` — gauges - -The exporter is constructed and started in code — there is no configuration key for it. The usage collector to attach is the one `register_sys_modules` created (it is in the returned context), and the metrics collector should be the one registration used: - -=== "Python" - - ```python - from apcore import Config, Executor, Registry, register_sys_modules - from apcore.observability import MetricsCollector, PrometheusExporter - - config = Config.load("apcore.yaml") # sys_modules.enabled: true - registry = Registry(config=config) - executor = Executor(registry, config=config) - collector = MetricsCollector() - - ctx = register_sys_modules(registry, executor, config, metrics_collector=collector) - exporter = PrometheusExporter(collector, usage_collector=ctx["usage_collector"]) - exporter.start(port=9090, path="/metrics") - ``` - -=== "TypeScript" - - ```typescript - import { Config, Executor, MetricsCollector, PrometheusExporter, Registry, registerSysModules } from 'apcore-js'; - - const config = Config.load('apcore.yaml'); // sys_modules.enabled: true - const registry = new Registry({ config }); - const executor = new Executor({ registry, config }); - const collector = new MetricsCollector(); - - const ctx = registerSysModules(registry, executor, config, collector); - const exporter = new PrometheusExporter({ collector, usageCollector: ctx.usageCollector }); - exporter.start({ port: 9090, path: '/metrics' }); - ``` - -=== "Rust" - - ```rust - use std::path::Path; - use std::sync::Arc; - - use apcore::{register_sys_modules, Config, Executor, MetricsCollector, PrometheusExporter, Registry}; - - #[tokio::main] - async fn main() -> Result<(), Box> { - let config = Config::load(Path::new("apcore.yaml"))?; // sys_modules.enabled: true - let registry = Arc::new(Registry::new()); - let executor = Executor::new(Arc::clone(®istry), config.clone()); - let collector = MetricsCollector::new(); - - // The collectors are cheap clones over shared state. - let ctx = register_sys_modules(Arc::clone(®istry), &executor, &config, Some(collector.clone()))?; - let exporter = PrometheusExporter::new(collector).with_usage_collector(ctx.usage_collector.clone()); - exporter.start(9090, "/metrics").await?; - Ok(()) - } - ``` +Pass the metrics collector supplied at assembly and the usage collector +returned by system-module registration to the pure Prometheus renderer. +See [Prometheus export](./metrics-and-usage.md#prometheus-export) for the +three SDK calls and the Toolkit listener. ## Contract: register_sys_modules diff --git a/docs/getting-started.md b/docs/getting-started.md index 093a07b2..9336b2b4 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -308,7 +308,7 @@ Middleware can intercept calls for logging, tracing, or security. === "TypeScript" ```typescript - import { ObsLoggingMiddleware } from 'apcore-js'; + import { ObsLoggingMiddleware } from 'apcore-js/full'; client.use(new ObsLoggingMiddleware()); ``` @@ -487,7 +487,7 @@ When configured with `sys_modules.enabled: true`, APCore auto-registers built-in === "TypeScript" ```typescript - import { APCore, Config } from 'apcore-js'; + import { APCore, Config } from 'apcore-js/full'; const config = Config.load('apcore.yaml'); const client = new APCore({ config }); diff --git a/docs/guides/acl-configuration.md b/docs/guides/acl-configuration.md index 08d1facb..de4e2ad4 100644 --- a/docs/guides/acl-configuration.md +++ b/docs/guides/acl-configuration.md @@ -85,7 +85,7 @@ acl: === "TypeScript" ```typescript - import { APCore, Config } from 'apcore-js'; + import { APCore, Config } from 'apcore-js/full'; const client = new APCore({ config: Config.load('apcore.yaml') }); ``` @@ -131,7 +131,7 @@ Load the file yourself when you need a custom audit destination or build the `Ex === "TypeScript" ```typescript - import { ACL, APCore } from 'apcore-js'; + import { ACL, APCore } from 'apcore-js/full'; import type { AuditEntry } from 'apcore-js'; const logDecision = (entry: AuditEntry): void => { @@ -570,7 +570,7 @@ Python and TypeScript ACLs have a `debug` flag that logs each rule evaluation in === "TypeScript" ```typescript - import { ACL } from 'apcore-js'; + import { ACL } from 'apcore-js/full'; const acl = ACL.load('./acl/global_acl.yaml'); acl.debug = true; @@ -609,7 +609,7 @@ For a record of decisions rather than evaluation steps, use the audit block or a === "TypeScript" ```typescript - import { ACL } from 'apcore-js'; + import { ACL } from 'apcore-js/full'; const acl = ACL.load('./acl/global_acl.yaml'); @@ -1044,7 +1044,7 @@ Test the file you ship, with the decisions you expect. This checks the §9.1 fil ```typescript import { describe, expect, it } from 'vitest'; - import { ACL } from 'apcore-js'; + import { ACL } from 'apcore-js/full'; const acl = ACL.load('./acl/global_acl.yaml'); diff --git a/docs/guides/cookbook-approval-flow.md b/docs/guides/cookbook-approval-flow.md index 615510b6..ac7e2b28 100644 --- a/docs/guides/cookbook-approval-flow.md +++ b/docs/guides/cookbook-approval-flow.md @@ -475,36 +475,11 @@ The Rust tab replaces the Phase A `main` and `build_client`; the Python and Type ## 4. What happens when no handler is attached -With no `ApprovalHandler`, the gate is **skipped** with a warning and the module runs unapproved. To fail closed instead, attach an `ExecutionPolicy` with `strict` enabled — gated calls are then denied with `APPROVAL_DENIED` until a handler is attached: - -=== "Python" - ```python - from apcore import APCore, ExecutionPolicy - - client = APCore(policy=ExecutionPolicy(strict=True)) - ``` - -=== "TypeScript" - ```typescript - import { APCore, ExecutionPolicy } from 'apcore-js'; - - // ExecutionPolicy(rules, options) -const client = new APCore({ policy: new ExecutionPolicy(null, { strict: true }) }); - ``` - -=== "Rust" - ```rust - use apcore::{Config, Executor, ExecutionPolicy, Registry}; - use std::sync::Arc; - - fn strict_executor() -> Executor { - let mut executor = Executor::new(Arc::new(Registry::new()), Arc::new(Config::default())); - executor.set_policy(Some(ExecutionPolicy::default().with_strict(true))); - executor // hand to APCore::with_options(None, Some(executor), None, None) - } - ``` - -The approval handler is always attached in code; there is no `apcore.yaml` key for it. +The default approval gate returns `APPROVAL_DENIED` before running a module +that requires approval when the host has no `ApprovalHandler`. Destructive +modules also require approval by default. Attach the handler in code to +process those requests. Review the running gate and the modules it covers +with the Executor's governance report. ### Deploying a scoped approval handler diff --git a/docs/guides/cookbook-observability.md b/docs/guides/cookbook-observability.md index a14b1234..2c1dc46f 100644 --- a/docs/guides/cookbook-observability.md +++ b/docs/guides/cookbook-observability.md @@ -15,7 +15,7 @@ End-to-end recipe: turn on tracing from `apcore.yaml`, log every module call as ## When NOT to use this pattern -- Metrics (call counts, latency histograms) use `MetricsCollector` + `MetricsMiddleware`, with `PrometheusExporter` to serve them — see [Metrics and Usage](../features/metrics-and-usage.md). The `observability.metrics.*` config keys do nothing; wire metrics in code. +- Collect call counts and latency histograms with `MetricsCollector` and `MetricsMiddleware`. Pass the text renderer to the Toolkit listener for scraping. See [Metrics and Usage](../features/metrics-and-usage.md). - Per-module usage statistics come from `UsageCollector` and the `system.usage.*` modules ([Metrics and Usage § Usage collector](../features/metrics-and-usage.md#usage-collector)). --- @@ -122,7 +122,7 @@ Full key reference: [PROTOCOL_SPEC §10.1.1](../spec/protocol-spec.md#1011-traci === "TypeScript" ```typescript import { Type } from '@sinclair/typebox'; - import { APCore, Config, ContextLogger, ObsLoggingMiddleware, RedactionConfig } from 'apcore-js'; + import { APCore, Config, ContextLogger, ObsLoggingMiddleware, RedactionConfig } from 'apcore-js/full'; const config = Config.load('apcore.yaml'); const client = new APCore({ config }); // installs TracingMiddleware from observability.tracing.* diff --git a/docs/guides/creating-modules.md b/docs/guides/creating-modules.md index 314d1968..671cbbf3 100644 --- a/docs/guides/creating-modules.md +++ b/docs/guides/creating-modules.md @@ -44,7 +44,7 @@ A module's metadata should guide an AI agent through each stage of using it: - `x-common-mistakes`: pitfalls callers run into - `x-workflow-hints`: steps that usually come before or after -**3. Governance — declare the risk.** Set `destructive: true` for irreversible operations and `requires_approval: true` for operations a human must confirm (spending money, deleting data). The executor's approval gate then asks your `ApprovalHandler` before the module runs; with no handler configured the gate is skipped with a warning. See the [Approval Flow cookbook](./cookbook-approval-flow.md). +**3. Governance.** Set `destructive: true` for irreversible operations and `requires_approval: true` for operations that need confirmation. The default gate requires an `ApprovalHandler` for either annotation and denies the call before running the module when the handler is absent. See the [Approval Flow cookbook](./cookbook-approval-flow.md). **4. Recovery — say what to do next.** When a module fails, `message` says what happened and `ai_guidance` says what the agent should do about it: @@ -1877,7 +1877,7 @@ my-project/ === "TypeScript" ```typescript - import { APCore, BindingLoader, Config } from 'apcore-js'; + import { APCore, BindingLoader, Config } from 'apcore-js/full'; const config = Config.load('apcore.yaml'); const client = new APCore({ config }); diff --git a/docs/guides/index.md b/docs/guides/index.md index 4c1f0155..e192239c 100644 --- a/docs/guides/index.md +++ b/docs/guides/index.md @@ -21,6 +21,8 @@ The guides are arranged as a learning path. Read the Foundations in order, then ## Integration +- [Runtime Profiles](./runtime-profiles.md) — Assemble the in-memory or full runtime and migrate host integrations + - [Python Golden Path](https://github.com/aiperceivable/apcore/tree/main/examples/python/golden-path) — Register an existing function and verify the same governance from Python and MCP - [Multi-Language](./multi-language.md) — Sharing schemas and module IDs across the Python, TypeScript, and Rust SDKs - [Adapter Development](./adapter-development.md) — Exposing modules through a web framework diff --git a/docs/guides/multi-language.md b/docs/guides/multi-language.md index f8168ee8..1253990f 100644 --- a/docs/guides/multi-language.md +++ b/docs/guides/multi-language.md @@ -206,7 +206,7 @@ All three SDKs read schema files at runtime with `SchemaLoader` — there is no === "TypeScript" ```typescript - import { APCore, Config, FunctionModule, SchemaLoader } from 'apcore-js'; + import { APCore, Config, FunctionModule, SchemaLoader } from 'apcore-js/full'; const loader = new SchemaLoader(Config.fromDefaults()); const schemaDef = loader.load('executor.email.send_email'); diff --git a/docs/guides/runtime-profiles.md b/docs/guides/runtime-profiles.md new file mode 100644 index 00000000..a2462c98 --- /dev/null +++ b/docs/guides/runtime-profiles.md @@ -0,0 +1,113 @@ +--- +description: "Choose the in-memory or full APCore runtime and migrate approval, metrics, event subscribers, and tool exports." +--- + +# Runtime Profiles + +The default Core Profile registers and runs modules in memory. It includes +preflight, approval, cancellation, managed lifecycle, and streaming completion. +Choose explicit extensions when an application reads configuration or discovers +modules from files. The full assembly provides those capabilities together. + +## Assemble the application + +=== "Python" + Install the base distribution for the in-memory client. Install + `apcore[all]` for the full assembly or select `config`, `discovery`, + `observability`, and `events` separately. + + ```python + from apcore import APCore + + client = APCore() + ``` + + ```python + from apcore.full import APCore, Config + + client = APCore(config=Config.load("apcore.yaml")) + client.discover() + ``` + +=== "TypeScript" + Import the in-memory assembly from `apcore-js`. On Node, import the full + assembly or compose the `config`, `discovery`, `sys-modules`, and + `events` subpaths. + + ```typescript + import { APCore } from "apcore-js"; + + const client = new APCore(); + ``` + + ```typescript + import { Config } from "apcore-js/config"; + import { APCore } from "apcore-js/full"; + + const client = new APCore({ config: Config.load("apcore.yaml") }); + await client.discover(); + ``` + +=== "Rust" + Use the crate with its default features for in-memory execution. + Enable the `full` feature for the configured assembly. + + ```rust + use apcore::APCore; + + fn main() { + let _client = APCore::in_memory(); + } + ``` + + ```rust + use std::path::Path; + use apcore::{APCore, APCoreOptions, Config}; + + fn main() -> Result<(), Box> { + let _client = APCore::try_start(APCoreOptions { + config: Some(Config::load(Path::new("apcore.yaml"))?), + fail_on_error: true, + ..Default::default() + })?; + Ok(()) + } + ``` + +## Check approval at startup + +The default gate rejects an approval-required call with `APPROVAL_DENIED` when +the host has no handler. An effective `destructive` annotation also requires +approval. Use the Executor's governance report on the running default or +injected Executor to identify missing gates and approval coverage. When +selecting a custom strategy for production, confirm that it includes the +built-in approval step. + +The configuration file declares its own supported document version. Keep the +document version for the configuration dialect your application uses. + +For Node hosts whose lifecycle hooks call back into the client after an +`await`, the TypeScript full assembly provides per-instance async lifecycle +context. Hosts that compose a custom Node assembly can supply +`createNodeLifecyclePlugin()`. + +To retain the earlier behavior during migration, set both `strict` and +`gate_destructive` to false in the policy supplied to the Executor. Set +`gate_destructive` alone to false to preserve strict enforcement of approval +requirements from annotations, ACL decisions, and policy rules. See the +[approval system](../features/approval-system.md#execution-policy). + +## Move host integrations + +| Existing use | Assembly | +| --- | --- | +| Prometheus HTTP server | Pass the Core text renderer to the Toolkit listener or the application's listener. See [Metrics and Usage](../features/metrics-and-usage.md#prometheus-export). | +| A2A event delivery | Supply the A2A adapter's subscriber factory to each host. Keep its existing `type: a2a` or filter delegate declaration. See [Subscriber Factories](../features/event-system.md#subscriber-factories). | +| Provider tool exports | Use the MCP adapter for MCP tools and the provider converters shipped with it for OpenAI Chat, Responses, and Anthropic. OpenAI and Anthropic use hyphens in place of module ID dots. OpenAI uses strict schemas by default. | +| Generic schema export | Use the Registry schema export. Pass the strict option to apply the shared strict conversion. See [Schema System](../features/schema-system.md). | +| Reload dependent modules | Choose a `path_filter` that includes their module IDs. The reload input reports a schema error for the removed `reload_dependents` option. | + +Run preflight and a harmless invocation through each adapter with the same +Core distribution used by the application. The +[Golden Path](https://github.com/aiperceivable/apcore/tree/main/examples/python/golden-path) +checks direct and MCP calls on the same governance pipeline. diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md index 84dc21d4..091c77c3 100644 --- a/docs/guides/troubleshooting.md +++ b/docs/guides/troubleshooting.md @@ -101,7 +101,7 @@ Common codes. For the full list see [features/error-system.md](../features/error | `BINDING_SCHEMA_INFERENCE_FAILED` | A binding with `auto_schema` targets a callable without enough type information | Add type hints to the callable, or give `input_schema` / `output_schema` / `schema_ref` explicitly | | `ACL_DENIED` | No `allow` rule matched and the ACL file's `default_effect` is `deny`, or a `deny` rule matched | Add an `allow` rule — see §1.2 | | `ACL_RULE_ERROR` | The ACL file is invalid: missing `callers`/`targets`/`effect`, unknown rule key, bad `effect` value or pattern array | Compare with [ACL Configuration Guide § Configuration Format](./acl-configuration.md#3-configuration-format) | -| `APPROVAL_DENIED` | The handler returned `rejected`, or no handler is attached under `ExecutionPolicy(strict=True)` | Inspect the handler; attach one if strict mode is on | +| `APPROVAL_DENIED` | The handler rejected the call, or the call requires approval and the strict gate has no handler | Inspect the decision or attach an approval handler | | `APPROVAL_TIMEOUT` | The handler returned `timeout` | Back off before retrying; the same handler answers again | | `APPROVAL_PENDING` | Phase B: the handler returned `pending` | Keep `approval_id`; call again later with `_approval_token` in the inputs ([Cookbook — Approval-Gated Modules](./cookbook-approval-flow.md)) | | `CALL_DEPTH_EXCEEDED` | The call chain is deeper than `executor.max_call_depth` (default 32) | Flatten the call graph, or raise the limit if the depth is intended | @@ -137,7 +137,7 @@ Enumerate registered modules: === "TypeScript" ```typescript - import { APCore, Config } from 'apcore-js'; + import { APCore, Config } from 'apcore-js/full'; const client = new APCore({ config: Config.load('apcore.yaml') }); console.log(await client.discover(), 'modules discovered'); @@ -176,7 +176,7 @@ Load `apcore.yaml` and print the effective configuration (loading validates it a === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; const config = Config.load('apcore.yaml'); console.log(config.data); diff --git a/docs/index.md b/docs/index.md index db0e312e..87ac2a3b 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.1.0` (draft) | -| Python SDK | `apcore` | `0.33.0` | `1.0.0a1` | -| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.1` | -| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.1` | +| Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `3.0.0` (draft) | +| Python SDK | `apcore` | `0.33.0` | `1.0.0a2` | +| TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.2` | +| Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.2` | The three core SDKs share a 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/api-surface-conventions.md b/docs/spec/api-surface-conventions.md index f02c3832..07273eb4 100644 --- a/docs/spec/api-surface-conventions.md +++ b/docs/spec/api-surface-conventions.md @@ -262,7 +262,7 @@ The following differences are by-design consequences of each language's idioms. | Axis | Python / TypeScript | Rust | Why it is not a gap | |---|---|---|---| | **Error taxonomy shape** | one distinct public exception class per failure (`ModuleNotFoundError`, `ApprovalDeniedError`, …) | variants of a single `pub enum ErrorCode` carried by one `pub struct ModuleError` | Equivalence is at the level of *the error identity being representable*, not *one exported type per error*. The per-type classes have **no** standalone Rust equivalent, and that is correct. | -| **Namespace depth** | a cohesive area MAY sit behind a public sub-package (`apcore.observability.PrometheusExporter`) | the same symbol is often flattened to the crate root (`PrometheusExporter`) | Both are public. The depth of the documented path is a style choice, not a surface gap. | +| **Namespace depth** | a cohesive area MAY sit behind a public sub-package (`apcore.observability.MetricsCollector`) | the same symbol is often flattened to the crate root (`MetricsCollector`) | Both are public. Document the import path for each SDK. | The error-taxonomy difference is concrete: @@ -299,7 +299,7 @@ The error-taxonomy difference is concrete: This is the line between §8.1's namespace-depth divergence (fine) and a genuine break: -- `apcore.observability.PrometheusExporter` — **fine**: `observability` is a public sub-package with its own `__all__`; the import path is one a caller is meant to use. +- `apcore.observability.MetricsCollector` is public through the `observability` subpackage. - `apcore.registry.registry.MAX_MODULE_ID_LENGTH` — **would be a break** if it were the only path: `registry.registry` is the *implementation module* inside the `registry` package. The constant is therefore exported from both `apcore` and `apcore.registry` and named in each `__all__`, matching its root-public status in TypeScript and Rust. Quick test: *if the only import path that works names a module callers were never meant to import from, the symbol is private by accident — re-export it through a public path.* diff --git a/docs/spec/conformance.md b/docs/spec/conformance.md index 09ac072f..e2144d70 100644 --- a/docs/spec/conformance.md +++ b/docs/spec/conformance.md @@ -20,6 +20,11 @@ apcore is implemented in several languages, and every implementation has to beha | **Level 1** | Standard | Production-ready implementation | Most production environments | | **Level 2** | Full | Full-featured implementation | Enterprise-grade, large-scale distributed scenarios | +The levels below enumerate capabilities available from a complete SDK +installation. The active runtime profiles determine which capabilities an +application installs and composes. The default Core Profile is governed by +[protocol-spec §1.8](./protocol-spec.md#18-runtime-profiles). + ### 1.3 Terminology and Keywords The keywords used in this document follow [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119), consistent with [protocol-spec §1.5](./protocol-spec.md#15-specification-keywords). @@ -36,6 +41,9 @@ Level 0 defines the minimal viable implementation of apcore. SDKs reaching this ### 2.2 Must Implement (MUST) +Configuration and Discovery requirements in this table apply when the +corresponding extension profile is selected. + | Component | Responsibility | Reference Section | |------|------|---------| | **Module interface** | Module base class/interface, includes `execute()`, `input_schema`, `output_schema`, `description` | protocol-spec §5.6 | @@ -102,7 +110,7 @@ Level 1 adds the governance pipeline steps (call-chain guard, ACL, approval), mi | **ACL engine** | Permission rule loading, pattern matching (`match_pattern()`), rule evaluation (`evaluate_acl()`) | protocol-spec §6.2, §6.3 | | **ACL default policy** | `default_effect: deny \| allow` in the ACL file; a missing ACL file attaches no ACL | protocol-spec §6.1, §6.6.3.1 | | **ACL edge cases** | When caller_id is null, treat as `@external`, empty rules use default policy | protocol-spec §6.5 | -| **Approval gate (Phase A)** | `ApprovalHandler` protocol; the gate fires on the union of every governance source and is skipped with a warning when no handler is configured | protocol-spec §7.2, §7.4, §7.8 | +| **Approval gate (Phase A)** | `ApprovalHandler` protocol. The default gate denies approval-required calls that lack a handler and requires approval for destructive modules. | protocol-spec §7.2, §7.4, §7.8, §7.9 | | **Middleware framework** | `middleware_before` (6) and `middleware_after` (10) run an onion-model chain with `before`, `after` and `on_error` hooks | protocol-spec §11.1, §11.5 | | **Middleware priority** | Higher numbers execute first | protocol-spec §11.2 | | **Trace ID** | `trace_id` generation (32-char lowercase hex, W3C Trace Context), propagation (child calls inherit) | protocol-spec §10.5 | @@ -386,7 +394,6 @@ The repository ships **98 cross-language fixture files** under `conformance/fixt | [`overrides_store`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/overrides_store.json) | 5 | OverridesStore pluggable persistence | | [`pattern_matching`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/pattern_matching.json) | 12 | ACL / `match_modules` module-ID pattern matching (Algorithm A08) | | [`extension_point_lookup`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/extension_point_lookup.json) | 12 | An unknown extension point is an error, an empty one is not (D-108) | -| [`export_profiles`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/export_profiles.json) | 5 | Export profiles: `anthropic` strips every `x-*` keyword and keeps properties named `x-…`; `mcp` carries `requiresApproval` / `streaming` in `_meta`, never in `annotations` (spec §4.17, Appendix D.1, D-140) | | [`glob_matching`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/glob_matching.json) | 32 | Portable glob matching for pattern-valued values (Algorithm A25, §9.2.3) | | [`pipeline_failfast_config`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/pipeline_failfast_config.json) | 7 | Pipeline configuration fail-fast (spec §5.16) | | [`pipeline_hardening`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/pipeline_hardening.json) | 7 | Pipeline execution hardening: fail-fast, replace-step, run_until, a step timeout raises `MODULE_TIMEOUT` (spec §5.16, D-142) | diff --git a/docs/spec/design-durability-boundary.md b/docs/spec/design-durability-boundary.md index a67cf158..92001988 100644 --- a/docs/spec/design-durability-boundary.md +++ b/docs/spec/design-durability-boundary.md @@ -47,7 +47,7 @@ This is what lets a Context cross a queue, a job board, or a persistent task sto The approval gate (pipeline Step 5, [protocol-spec §7](./protocol-spec.md#7-approval-system)) is the **only** suspension point in apcore's pipeline. Its Phase B contract: -1. The gate fires when any governance source requires approval — the module's annotations, annotations the registry holds for it (binding file, `*_meta.yaml`, `metadata`), an ACL rule with `approval: required`, or `ExecutionPolicy.gate_destructive` for a destructive module ([protocol-spec §7.4, §6.9](./protocol-spec.md#74-executor-integration-step-5)). It calls the configured `ApprovalHandler`; with no handler the gate is skipped with a warning, unless `ExecutionPolicy(strict = true)` makes it fail closed. +1. The gate evaluates the module and registry annotations, the ACL approval decision, and the execution policy. The default policy also requires approval for destructive modules and rejects approval-required calls when the host lacks an `ApprovalHandler`. [Protocol specification §7.4](./protocol-spec.md#74-executor-integration-step-5). 2. If the handler returns `pending`, the executor raises `ApprovalPendingError` carrying an `approval_id`. 3. The caller persists `approval_id` and the original inputs (apcore does not), waits for an out-of-band approval signal, and re-invokes the same module with `_approval_token = approval_id` in the arguments. 4. On resume the executor re-enters the pipeline **from Step 1**. The gate removes `_approval_token` from the arguments and calls `handler.check_approval_for_call(token, request)` with the current invocation. diff --git a/docs/spec/protocol-spec.md b/docs/spec/protocol-spec.md index f6149666..df4c0fa3 100644 --- a/docs/spec/protocol-spec.md +++ b/docs/spec/protocol-spec.md @@ -6,9 +6,9 @@ description: "The canonical apcore protocol specification (RFC 2119): module, sc > **Canonical specification.** This document is the single normative source for the apcore protocol. Where any other document disagrees with it, this document wins. -> Version: 2.1.0 +> Version: 3.0.0 > Status: Draft -> Last Updated: 2026-11-26 +> Last Updated: 2026-11-27 --- @@ -137,6 +137,30 @@ Implementations **MUST** follow these naming rules: - In languages without namespace mechanisms, **MUST** use `apcore_` prefix - Error types **SHOULD** be prefixed with their domain (e.g., `ModuleError`, `SchemaValidationError`) +### 1.8 Runtime Profiles + +A conformant SDK declares the profiles it implements. A requirement applies when its +profile is active. Shared module IDs, schemas, errors and execution semantics have the +same meaning across profile combinations. + +| Profile | Scope | +|---------|-------| +| Core | In-memory registration and metadata, schema validation, call and preflight, ACL and approval governance, middleware, lifecycle, cancellation, and streaming completion | +| Configuration | File-backed configuration, ACL rules, external schemas and overrides | +| Discovery | Filesystem scanning, file bindings, watchers, and reload driven by an external source | +| System Modules | Health, usage, manifest, control, and event composition driven by host configuration | +| Events | Host-owned subscriber factories, optional sinks, retry, and dead-letter delivery | +| Observability | Optional exporters and host-specific telemetry sinks. Core execution may deliver data to a sink supplied by the host. | + +The default SDK assembly **MUST** provide the Core Profile and **MUST** allow +in-memory registration and execution independently of a filesystem, YAML parser, +file watcher, HTTP listener, or external service. Extension profiles **MUST** be +explicitly installed or composed by the host. An SDK may provide a full assembly +that selects its extension profiles together. When selected, each extension +profile **MUST** implement the requirements in its corresponding protocol +sections. Outside the SDK, adapter profiles (§4.17) own protocol-specific tool +shapes and network delivery. + --- ## 2. Naming Specification @@ -1929,8 +1953,8 @@ apcore defines standard export Profiles for adapter developers to follow. Profil | Profile | Characteristics | Typical Users | |---------|------|-----------| -| `mcp` | Preserve `x-*` fields; map annotations → hints; contains `inputSchema` (no `outputSchema`) | MCP Server adapters | -| `openai` | Strip `x-*`; `strict: true`; replace `.` with `_` in id; parameters only | OpenAI Function Calling adapters | +| `mcp` | Preserve schema extensions and project input and output schemas and annotation hints | MCP Server adapters | +| `openai` | Chat Completions and Responses envelopes, with the same tool names and strict schemas by default | OpenAI adapters | | `anthropic` | Strip `x-*`; map examples → input_examples; contains input_schema | Anthropic Claude Tool adapters | | `generic` | Full JSON Schema + all extensions (default) | Generic scenarios, debugging | @@ -1941,19 +1965,19 @@ apcore defines standard export Profiles for adapter developers to follow. Profil - ID: Use as-is (`executor.email.send_email`) - Annotations: `readonly` → `readOnlyHint`, `destructive` → `destructiveHint`, `idempotent` → `idempotentHint`, `open_world` → `openWorldHint` - `requires_approval` and `streaming` have no MCP `ToolAnnotations` equivalent. They travel in the tool's `_meta` as `requiresApproval` and `streaming`, each present only when the annotation is `true`, and never in `annotations` (D-140) -- Output schema: not carried. An MCP adapter that advertises a tool `outputSchema` takes it from the module's `output_schema` (Appendix D.1) +- MCP clients negotiating `2025-06-18` or later can receive a tool `outputSchema` derived from the module's `output_schema` and the matching result `structuredContent` (Appendix D.1). - See Appendix D.1 MCP Mapping **`openai` Profile:** -- Schema: Apply `to_strict_schema()` conversion (§4.16) -- ID: Replace `.` with `_` (e.g., `executor_email_send_email`) -- Replace `description` with `x-llm-description` then strip +- Apply `to_strict_schema()` by default (§4.16), promoting schema-node `x-llm-description` strings before stripping extension keywords. +- Replace `.` with `-` in the module ID (for example, `executor-email-send_email`). +- Wrap the function in `function` for Chat Completions, or place its fields beside `type: function` for Responses. The Responses representation includes explicit `strict: false` when the caller opts out. - See Appendix D.3 OpenAI Mapping **`anthropic` Profile:** - Schema: Strip every `x-*` keyword, at any depth of `input_schema`. Only keywords are stripped: a property *name* beginning with `x-` (a key of `properties`) is data, and the property is kept (D-140) -- ID: Replace `.` with `_` -- Replace `description` with `x-llm-description` then strip +- Replace `.` with `-` in the module ID. +- Promote schema-node `x-llm-description` strings to `description` before stripping extension keywords. - Examples: `module.examples[*].inputs` → `input_examples` - See Appendix D.4 Anthropic Mapping @@ -4671,7 +4695,9 @@ Adapters **SHOULD NOT** invent their own classification mechanisms (such as rese #### 6.6.3 Defense-in-Depth Model -System module access is governed by three independent layers. Each layer operates regardless of the others — and each is **inactive by absence**: a layer that was never configured does not fail closed, it does not run. Nothing in this section is a default-deny. That is deliberate, and stating it is the point of §6.6.3.1. +System module access uses three independent layers. Configuration activates the +modules, an attached ACL defines authorization, and the approval gate evaluates +each call's effective requirements (§6.6.3.1). ```text Layer 1: Activation (Config) — two stages, not one @@ -4704,11 +4730,11 @@ The 0 / 6 / 9 distinction matters to anything that reasons about exposure: a reg Adapters and UI layers **SHOULD NOT** introduce additional independent permission switches. The three layers above are sufficient — adding adapter-level switches creates shadow permission systems that can diverge from the actual ACL state. -##### 6.6.3.1 Layers 2 and 3 are inactive by absence +##### 6.6.3.1 Effects of an absent ACL or approval handler {#6631-layers-2-and-3-are-inactive-by-absence} **Layer 2 — a missing `acl/` path attaches nothing.** When `acl.root` resolves to a path that does not exist, implementations **MUST** attach no ACL and **MUST NOT** synthesize an empty `default_effect: deny` ACL in its place. An empty default-deny ACL denies every inter-module call, so synthesizing one would break every project that has no `acl/` directory — which is every project that has not opted in. `default_effect: deny` is the default *within a ruleset that exists*; it is not a default *for the absence of one*. Pinned by `../../conformance/fixtures/acl_root_discovery.json`. -**Layer 3 — a missing `ApprovalHandler` skips the gate.** With no handler configured, Step 5 is skipped and a module declaring `requires_approval` executes anyway, with a warning (§7.4, §7.9.4). Failing closed is opt-in through `ExecutionPolicy(strict = true)` (§7.9), which converts the skip into `ApprovalDeniedError`. Implementations **MUST NOT** change this default. +**Layer 3 — a missing `ApprovalHandler` denies a call that requires approval.** The default approval gate **MUST** reject such a call before module execution. An explicit `ExecutionPolicy(strict = false)` selects the compatible warn-and-continue behavior (§7.4, §7.9.4). ##### 6.6.3.2 A configured layer is not necessarily an enforced one @@ -5167,7 +5193,7 @@ Executor Pipeline: **Step 5 Algorithm:** ```text -Algorithm: approval_gate(module, arguments, resume_credential, context, approval_handler) +Algorithm: approval_gate(module, arguments, resume_credential, context, approval_handler, policy) Input: module — Resolved module instance @@ -5175,14 +5201,14 @@ Input: resume_credential — Optional private invocation credential from _approval_token context — Execution context (with identity) approval_handler — Configured ApprovalHandler or null + policy — Attached ExecutionPolicy or the built-in defaults Behavior: - 1. IF approval_handler is null → SKIP (no enforcement) - 2. LET annotations = module.annotations - 3. IF annotations is null OR annotations.requires_approval is false → SKIP - (the requirement is the UNION of every governance source — see - "The gate fires on the union of its governance sources" below — - not this one alone) + 1. LET annotations = resolve_effective_annotations(module, policy, ACL decision, context) + 2. IF annotations.requires_approval is false → SKIP + 3. IF approval_handler is null: + a. IF policy.strict → EMIT rejected decision and THROW ApprovalDeniedError + b. WARN once per module, then CONTINUE to Step 6 4. LET request = ApprovalRequest(module_id, snapshot of arguments, context, annotations, ...) IF resume_credential is present: a. IF approval_handler has no check_approval_for_call → THROW ApprovalDeniedError @@ -5196,7 +5222,7 @@ Behavior: "pending" → THROW ApprovalPendingError(result) ``` -**The gate fires on the union of its governance sources (D-96, D-125).** Step 2 of the algorithm binds `module.annotations`, and an implementation **MUST** consult it. An implementation whose registry also holds **declared** annotations for the module — a `ModuleDescriptor` supplied by the caller at registration, or a descriptor into which a metadata document (`*_meta.yaml`, `*.binding.yaml`, a `metadata` argument) is merged (§4.13) — **MUST** fire the gate when *either* the live module instance or the declared annotations declare the requirement. The union is `OR` on `requires_approval` and `destructive` only; every other annotation describes behaviour rather than governance and stays instance-sourced. +**The gate fires on the union of its governance sources (D-96, D-125).** Step 1 of the algorithm **MUST** consult `module.annotations`. When the registry also holds declared annotations for the module, the gate **MUST** include the registry declaration in its evaluation (§4.13). The effective metadata starts with the logical OR of the live and declared `requires_approval` and `destructive` values. Other annotations come from the live instance. The gate then evaluates the attached policy and the call's ACL approval requirement. The union binds **every** reader of `requires_approval` / `destructive` for a registered module, not the gate alone: @@ -5220,7 +5246,7 @@ Rationale: reading only the declared annotations ignores what the module declare An implementation that read only the annotation would silently ignore every rule carrying `approval` — the rule would load, match, and do nothing. **Key behaviors:** -- When no `ApprovalHandler` is configured, Step 5 is **skipped** (inactive by absence, §6.6.3.1) — but per the fail-loud principle (§7.9.4) a module that needs approval **MUST** produce a warning on skip, and an `ExecutionPolicy` with `strict` (§7.9) turns this skip into a fail-closed `ApprovalDeniedError` instead. +- When an invocation requires approval and has no `ApprovalHandler`, the default gate **MUST** raise `ApprovalDeniedError` before running the module. An explicit `ExecutionPolicy(strict = false)` permits the invocation with the warning in §7.9.4. - When an `ExecutionPolicy` (§7.9) is attached, the gate consults it first: the policy may force approval on a module that does not declare `requires_approval`, or (with `gate_destructive`) gate a `destructive` module. - The `_approval_token` mechanism (Phase B) allows clients to retry after external approval without re-triggering the approval flow. - The `_approval_token` key **MUST** be removed from business arguments before they reach subsequent steps. This applies to an invocation whose strategy omits the approval gate as well. The executor can carry the credential separately for the approval handler. A preflight has no approval decision to resume. @@ -5319,10 +5345,10 @@ An **Execution Policy** is a declarative, execution-time governance layer that o #### 7.9.2 `destructive` → approval resolution -The approval gate keys on the **effective** `requires_approval`. Because HTTP-method inference and scanners can set `destructive = true` without setting `requires_approval` (a governance footgun — e.g. an inferred `DELETE`), a policy **MAY** enable `gate_destructive`: +The approval gate keys on the **effective** `requires_approval`. HTTP-method inference and scanners can set `destructive = true` independently of `requires_approval`. - When `gate_destructive` is true, a module whose **effective** `destructive` is true **MUST** be treated as needing approval even when `requires_approval` is false. -- `gate_destructive` is **opt-in**; with no policy, `destructive` and `requires_approval` remain orthogonal (no behavior change). Independently, an implementation **SHOULD** warn when a `destructive` module is exposed with no approval/ACL covering it (see §7.9.4). +- The built-in policy **MUST** default `gate_destructive` to true, including when the host supplies no policy. An explicit `gate_destructive = false` disables this source of approval while preserving requirements from module annotations, ACL rules, and policy rules. An implementation **SHOULD** warn when a destructive module is exposed without approval or ACL coverage (see §7.9.4). #### 7.9.3 Effective annotations to the handler @@ -5332,10 +5358,17 @@ When the gate invokes the handler because a policy forced approval, the `Approva A misconfigured or unreachable governance control **MUST NOT** silently allow. Concretely: -1. When a module needs approval but **no** `ApprovalHandler` is configured, the implementation **MUST** either (default) keep the §7.4 skip behavior **and** emit a warning (at least once per module), or — when the policy sets `strict` — **fail closed** by raising `ApprovalDeniedError` (`APPROVAL_DENIED`). +1. The built-in policy **MUST** default `strict` to true. When a call needs approval and has no handler, the gate **MUST** raise `ApprovalDeniedError` (`APPROVAL_DENIED`). Given explicit `strict = false`, it **MUST** emit a warning at least once per module and continue. 2. A `destructive` module that no approval gate covers **SHOULD** produce a warning (at least once per module). 3. A strict-fail-closed rejection **MUST** emit `apcore.approval.decision` (status `rejected`) like any other adjudication. -4. Strict parsing: an implementation that loads a policy from a document (YAML/JSON) **MUST** reject unknown keys and a missing rule `pattern`, so a typo cannot silently disable a control. +4. An implementation that loads a policy from YAML or JSON **MUST** reject unknown keys and rules missing `pattern`. Omitted policy booleans **MUST** take the built-in defaults, and explicit boolean values **MUST** be preserved. + +The implicit warn-and-continue behavior from earlier protocol versions is +deprecated. During migration an application can select +`strict = false, gate_destructive = false` explicitly to retain that behavior. +An application that requires approval can provide an `ApprovalHandler`. Explicit +strategies that omit the built-in approval gate remain visible in the governance +posture report (§6.6.5). #### 7.9.5 Preflight @@ -5366,7 +5399,7 @@ The tiers below grade the approval subsystem alone. They are not the SDK conform | Tier | Requirement | |-------|-------------| -| **Tier 1 (Basic)** | `ApprovalHandler` protocol defined; Executor skips gate when handler is null | +| **Tier 1 (Basic)** | `ApprovalHandler` protocol defined. The default gate raises `APPROVAL_DENIED` when a call needs approval and lacks a handler. | | **Tier 2 (Standard)** | Step 5 implemented in `call()`, `call_async()`, and `stream()` paths; `AlwaysDenyHandler` and `AutoApproveHandler` provided | | **Tier 3 (Full)** | Phase B support (`check_approval_for_call`, `_approval_token`); `CallbackApprovalHandler` provided; approval audit events emitted | | **Tier 4 (Governance)** | Execution Policy (§7.9): external override + specificity precedence, `gate_destructive`, `strict` fail-closed, effective-annotations contract, and the `apcore.approval.decision` / `apcore.policy.override` / `apcore.acl.denied` events | @@ -6097,7 +6130,7 @@ version: "1.0.0" # REQUIRED — no default exists # Project information project: name: "my-ai-project" # REQUIRED — no default exists (pattern: ^[a-z][a-z0-9_-]*$) - version: "0.1.0" # SHOULD, project version (semver). No effect — read by no implementation + version: "0.1.0" # SHOULD use semver. Reported by system.health.summary. # Extension configuration extensions: @@ -6786,7 +6819,7 @@ Config.register_namespace( **TypeScript:** ```typescript -import { Config } from 'apcore-js'; +import { Config } from 'apcore-js/config'; // Nested style (default) Config.registerNamespace({ @@ -7599,7 +7632,7 @@ Config.reserved_namespaces() === "TypeScript" ```typescript - import { Config } from 'apcore-js'; + import { Config } from 'apcore-js/config'; // Static getter — no Config instance needed const reserved: ReadonlySet = Config.reservedNamespaces; @@ -7959,7 +7992,7 @@ Config.register_namespace( ```typescript // nestjs-apcore/src/index.ts -import { Config } from 'apcore-js'; +import { Config } from 'apcore-js/config'; Config.registerNamespace({ name: 'nestjs-apcore', @@ -8095,8 +8128,8 @@ Config.register_namespace( "manifest": {"enabled": True}, "usage": { "enabled": True, - "retention_hours": 168, # No effect — read by no implementation - "bucketing_strategy": "hourly", # No effect — read by no implementation + "retention_hours": 168, # Retention for usage records in hourly buckets + "bucketing_strategy": "hourly", # Supported granularity }, "control": {"enabled": True}, "error_history": { @@ -8937,8 +8970,8 @@ Implementations **MUST** handle middleware edge cases according to the following | Component | Responsibility | Phase | |------|------|------| | `IDConverter` | Canonical ID ↔ Local ID conversion (class or utility function) | Phase 1 | -| `SchemaLoader` | Load YAML Schema | Phase 1 | -| `Registry` | Module discovery, registration, loading | Phase 1 | +| `SchemaLoader` | Load file-backed schemas (Configuration Profile) | Phase 1 | +| `Registry` | In-memory registration and lookup (Core Profile), external module discovery (Discovery Profile) | Phase 1 | | `Executor` | Module invocation, Schema validation | Phase 1 | | `ACLChecker` | Permission checking | Phase 2 | | `MiddlewareManager` | Middleware management | Phase 2 | @@ -8947,7 +8980,7 @@ Implementations **MUST** handle middleware edge cases according to the following ### 12.2 Core Component Interface Contracts -Following are formalized interface definitions for each core component (language-agnostic pseudocode). All SDK implementations **MUST** provide equivalent implementations of these interfaces. +The following interface definitions use language-agnostic pseudocode. An SDK **MUST** provide equivalent implementations for the requirements of each profile it declares (§1.8). ```text Interface: IDConverter @@ -10192,10 +10225,18 @@ An A2A `AgentSkill` has no schema member, so `input_schema` and `output_schema` ```yaml # Module → OpenAI Function mapping openai_mapping: - function: - name: "{module.id.replace('.', '_')}" # OpenAI doesn't support dots + chat_completions: + type: function + function: + name: "{module.id.replace('.', '-')}" + description: "{module.description}" + parameters: "{module.input_schema}" # after to_strict_schema() (§4.16) + strict: true + responses: + type: function + name: "{module.id.replace('.', '-')}" description: "{module.description}" - parameters: "{module.input_schema}" # after to_strict_schema() (§4.16), per the openai profile (§4.17) + parameters: "{module.input_schema}" # after to_strict_schema() (§4.16) strict: true # annotations mapping (OpenAI Agents SDK) @@ -10209,7 +10250,7 @@ openai_mapping: # Module → Anthropic Tool mapping anthropic_mapping: tool: - name: "{module.id.replace('.', '_')}" + name: "{module.id.replace('.', '-')}" description: "{module.description}" input_schema: "{module.input_schema}" input_examples: "{module.examples[*].inputs}" @@ -10261,10 +10302,11 @@ Each language SDK **SHOULD** provide idiomatic module definition syntax. The fol ## Revision History -The specification is versioned independently of the SDK release line (`0.x`); `CHANGELOG.md` records which SDK release shipped each specification version. The reasoning behind each change is recorded in `CHANGELOG.md` and in the decision records indexed by [`decision-register.md`](./decision-register.md). +The specification and the SDK have independent version numbers. `CHANGELOG.md` records which SDK release ships each specification version. The change rationale appears in `CHANGELOG.md` and the [decision register](./decision-register.md). | Version | Date | Summary | Records | |---|---|---|---| +| 3.0.0 | Unreleased | Define the in-memory Core Profile and opt-in extension profiles (§1.8, §12). Require the default approval gate to reject calls that need a missing handler and require approval for destructive modules by default (§6.6.3.1, §7.4, §7.9). Move provider projections to Surfaces (§4.17 and Appendix D). | [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | | 2.1.0 | Unreleased | Add managed drain and recovery hooks, scoped forced removal, opt-in governed reload reports, and lifecycle events (§6.7, §9.16.2, §12.7.9). | D-153 | | 2.0.0 | Unreleased | Resolve every path-typed configuration value against one project root (§9.2.2). Clarify configured redaction for schema-less calls (§6.1.8, §10.6.1). Require invocation-scoped approval resumption and use a non-secret correlation ID in approval telemetry (§7, §9.16.2). Clarify pipeline configuration, preflight, and approval argument scope (§5.16.1, §7.3–7.4, §12.8). Align schema examples with Draft 2020-12 and the unified validation error format (§4.2, §4.14, §8.1). Clarify the APCore trace ID reservation (§10.5). | [#113](https://github.com/aiperceivable/apcore/issues/113) | | 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/docs/spec/security-considerations.md b/docs/spec/security-considerations.md index cace8f85..e06ca990 100644 --- a/docs/spec/security-considerations.md +++ b/docs/spec/security-considerations.md @@ -333,7 +333,7 @@ The approval handler and `ExecutionPolicy` are code, not configuration. Wire the Config, ExecutionPolicy, createApprovalResult, - } from "apcore-js"; + } from "apcore-js/full"; import type { ApprovalRequest, ApprovalResult } from "apcore-js"; async function askHuman(request: ApprovalRequest): Promise { diff --git a/mkdocs.yml b/mkdocs.yml index fc50da32..4494436f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -87,6 +87,7 @@ nav: - ACL Configuration: guides/acl-configuration.md - Writing Middleware: guides/middleware.md - Integration: + - Runtime Profiles: guides/runtime-profiles.md - Multi-Language Development: guides/multi-language.md - Adapter Development: guides/adapter-development.md - Integrating Existing Projects: guides/integrating-existing-projects.md diff --git a/planning/microkernel-delivery/alpha-2.md b/planning/microkernel-delivery/alpha-2.md new file mode 100644 index 00000000..c9c5677b --- /dev/null +++ b/planning/microkernel-delivery/alpha-2.md @@ -0,0 +1,101 @@ +# APCore alpha.2 delivery + +The starting points are Core `301c90131712f1a42a31c2efed6c19b9744b936c` and Surfaces `7aea980b6f4de3876d5edbbc247235f450fc25c8`. Both revisions passed their post-merge workflows. Both candidate source trees match their merged trees. Verify local artifacts throughout the refactor and obtain separate approval before publishing packages. + +## Implementation order + +1. Expose additive assembly APIs and package entry points. The in-memory profile provides registration, schema validation, governance, lifecycle and streaming completion. Make discovery, YAML configuration, system modules, observability integrations and event sinks explicit. Provide a full assembly for applications using these capabilities. TypeScript exposes a pure Prometheus renderer. Python updates the synchronous bridge while retaining the same asynchronous pipeline for every call. +2. Move Toolkit HTTP listener and A2A subscriber callers and tests to their Surfaces-owned interfaces. Connect the A2A subscriber through an instance-owned factory so multiple hosts can configure their subscriptions independently. Move MCP, OpenAI Chat and Responses, and Anthropic projections into Surfaces. Migrate consumers to the split SDK entry points and record the supported Core range for each resulting package. +3. Verify the migrated consumers against the replacement paths. Then change the default SDK entry points, remove the superseded Core integrations and SDK aliases, and apply the new approval defaults. Retain the deprecation window for configuration keys protected by protocol 1.x. Review the normative profile and default changes against the protocol's governance and versioning requirements. + +## Workstreams + +| Workstream | Acceptance evidence | +| --- | --- | +| Python packaging and assembly | A wheel installed into an empty environment can register and execute a module without YAML or a watcher. Explicit discovery, configuration and the full profile load their declared extras. The full suite passes. | +| Python synchronous bridge | Concurrent caller threads reuse independent loops. Nested calls are bounded and honor deadlines. Shutdown retires loop and worker resources while preserving lifecycle and stream cleanup. Calls share the asynchronous pipeline. | +| TypeScript packaging and assembly | The installed root works in Node and a browser bundle without Node or YAML in its reachable graph. Mixed minimal and full imports leave capabilities scoped to the instance. Full Node assembly preserves async lifecycle reentrancy protection. | +| Rust packaging and assembly | An external crate built with default features exercises registration, governance, cancellation, streaming completion and shutdown. The normal dependency graph excludes filesystem watching, YAML, socket listening and HTTP. Full assembly enables the extensions explicitly and passes complete conformance. Retain the runtime capabilities needed for native lifecycle and stream cleanup. | +| Surfaces | MCP, A2A, CLI and Toolkit pass their supported Core matrix using built SDK distributions. Test HTTP text and readiness, one subscriber delivery and two-host isolation, protocol tool schemas, and cancellation and final results through public entry points. | +| Governance | Exercise module, ACL and policy approval requirements with no handler and record zero module executions. Cover default clients, injected executors and configured strategies. Test explicit policy overrides and preflight alongside ordinary and streaming calls. | +| Shared fixtures and documentation | Keep protocol anchors, align the profile, schema and fixture metadata with the actual dependency boundary, and provide runnable migration examples. Record cold start, package size, execution latency and Python synchronous concurrency with reproducible commands. | + +The approved alpha.1 build hashes remain the comparison baseline. Validate alpha.2 from its own built wheel, npm package and crate, with the Golden Path covering direct calls and MCP on the same distributions. + +## Local acceptance + +| Gate | Evidence | +| --- | --- | +| Python Core | 6,653 tests passed, with 40 skips and 5 expected failures. Clean base and `[all]` wheel installations passed dependency and execution checks. File discovery and native FSEvents passed with the full installation. The nested timeout regression completed without leaving an unretrieved Future. | +| TypeScript Core | 5,862 tests passed, with 36 skips. The installed root worked under Node and browser conditions and in a browser bundle. The minimal import graph excluded Node modules and YAML. Full Node assembly passed instance isolation and async lifecycle tests. | +| Rust Core | The default-feature archive passed 495 unit tests and four Core Profile tests on Rust 1.86. The full profile passed 602 unit tests, 2,439 consolidated integration tests and the standalone suites. Default features exclude YAML, file watchers, reqwest and Tokio file and socket features. Tokio runtime and macros support lifecycle cleanup and streaming. | +| Surfaces Python | Toolkit 1,289, MCP 1,275, A2A 522 and CLI 1,098 tests passed. The final installed Core and MCP wheels passed the direct and MCP Golden Path with the same approval and ACL rules. | +| Surfaces TypeScript | Toolkit 1,079, MCP 993, A2A 491 and CLI 950 tests passed. A separate npm consumer installed all four candidate packages with one Core version. Toolkit also passed installation with Core 0.33.0. | +| Surfaces Rust | Toolkit 714, MCP 1,152, A2A 242 and CLI 1,052 tests passed with the locked Core and Toolkit crates. Toolkit, MCP and A2A used Rust 1.86. CLI used stable Rust to meet its dependency floor. | +| Shared contract | All three SDKs drive all 98 Core fixture files. Every top-level expected field has a reader. The Core Profile fixture covers annotation, ACL, policy and destructive approval requirements with zero module execution on rejection. Surfaces use one shared fixture for provider projections, including recursive references. | +| Migration | The [runtime profile guide](../../docs/guides/runtime-profiles.md), schema and protocol draft reflect the capabilities of the installed packages. MkDocs strict build passed. | + +The local review identified an Anthropic recursive-schema regression, a missing +TypeScript public export, and an inconsistent custom-strategy diagnostic. The +revised converters, packaged imports and governance tests cover these cases. +Candidate branches are local. GitHub review and hosted CI are pending. Tags +and package publication remain paused. + +### Core candidate artifacts + +| Distribution | SDK version | SHA-256 | +| --- | --- | --- | +| Python wheel | `1.0.0a2` | `ed01a45192ce3fff2bc02f76d80b86c38d8a98f60701dce87d8d6952e18239bc` | +| npm archive | `1.0.0-alpha.2` | `fbfc83403234056023d843c424de58d42d6056cb9cbd94d92c0642d2ea0832d9` | +| Rust crate | `1.0.0-alpha.2` | `54e630a6f3c82ee9e01aec1f58ad14a06e21d8082414a1f4d398bce2f45b4de3` | + +Surfaces CI builds its Python wheel from Core commit `dc61dd575a3d76a113f55a84175b6f36ba35e894`. The TypeScript and Rust jobs use Core commit `0384a3d4e7688c47eaa1feea6032fb4739813f20`. The Rust lock records the archive built from that commit, including its Cargo VCS metadata. + +## Benchmark + +Measured on arm64 macOS 15.8.3 with Python 3.11.18, Node 22.23.5, and Rust +1.86.0. The same benchmark registers an in-memory echo module and executes +1,000 validated calls after a 100-call warmup. Pipeline figures are medians +of three runs. Startup is the median of 15 fresh processes. Python and +TypeScript startup include SDK import. Rust startup includes client assembly +in a release-optimized binary. + +| Measurement | Python alpha.1 | Python alpha.2 | TS alpha.1 | TS alpha.2 | Rust alpha.1 | Rust alpha.2 | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Compressed Core package, bytes | 465,997 | 461,991 | 657,377 | 646,218 | 1,545,995 | 1,530,159 | +| Fresh-process startup, ms | 121.48 | 110.71 | 88.42 | 62.89 | 3.41 | 2.90 | +| Warm pipeline p50, μs | 319.54 | 321.04 | 30.67 | 30.29 | 31.75 | 17.08 | +| Warm pipeline p95, μs | 375.63 | 366.25 | 50.54 | 51.58 | 36.08 | 17.42 | +| Python four-thread sync calls per second | 2,033 | 2,693 | | | | | + +These figures describe one workload on the same host. Python synchronous +throughput includes a four-thread caller pool and 1,000 successful calls. + +Install each wheel into an isolated environment, and install each npm archive +into its own project. For Rust, unpack each crate into a separate `library` +directory. Place [bench-alpha2.rs](bench-alpha2.rs) in `runner/src/main.rs` +beside `library` and use the following manifest in `runner/Cargo.toml`. + +```toml +[package] +name = "apcore-benchmark" +version = "0.0.0" +edition = "2021" +rust-version = "1.86" + +[dependencies] +apcore = { path = "../library" } +serde_json = "1" +tokio = { version = "1", features = ["rt", "macros"] } +``` + +Build each Rust runner with `cargo +1.86.0 build --release`. Run the harness +once per installed release with that release's paths. + +```sh +python3 planning/microkernel-delivery/bench-alpha2.py \ + --python /path/to/venv/bin/python \ + --node /path/to/node \ + --npm-directory /path/to/consumer \ + --rust-binary /path/to/runner/target/release/apcore-benchmark +``` diff --git a/planning/microkernel-delivery/bench-alpha2.py b/planning/microkernel-delivery/bench-alpha2.py new file mode 100644 index 00000000..6043959b --- /dev/null +++ b/planning/microkernel-delivery/bench-alpha2.py @@ -0,0 +1,120 @@ +"""Measure a fixed installed-package workload on one machine.""" + +import argparse +import json +import os +import statistics +import subprocess +import time +from pathlib import Path + +PYTHON = """ +import asyncio +import json +import time +from concurrent.futures import ThreadPoolExecutor + +from apcore import APCore + +client = APCore() + + +@client.module("bench.echo", description="Echo an integer") +def echo(value: int) -> dict[str, int]: + return {"value": value} + + +async def main(): + for _ in range(100): + await client.call_async("bench.echo", {"value": 1}) + samples = [] + for i in range(1000): + start = time.perf_counter_ns() + assert (await client.call_async("bench.echo", {"value": i}))["value"] == i + samples.append(time.perf_counter_ns() - start) + result = {} + result["pipeline_p50_us"] = sorted(samples)[499] / 1000 + result["pipeline_p95_us"] = sorted(samples)[949] / 1000 + return result + + +def sync_call(value): + assert client.call("bench.echo", {"value": value})["value"] == value + + +result = asyncio.run(main()) +start = time.perf_counter() +with ThreadPoolExecutor(4) as workers: + list(workers.map(sync_call, range(1000))) +result["sync_four_threads_calls_per_second"] = 1000 / (time.perf_counter() - start) +print(json.dumps(result)) +""" + +JAVASCRIPT = """ +import { APCore } from 'apcore-js'; +const client = new APCore(); +client.module({ + id: 'bench.echo', + description: 'Echo an integer', + inputSchema: { type: 'object', properties: { value: { type: 'integer' } }, required: ['value'] }, + outputSchema: { type: 'object', properties: { value: { type: 'integer' } }, required: ['value'] }, + execute: ({ value }) => ({ value }), +}); +for (let i = 0; i < 100; ++i) await client.call('bench.echo', { value: i }); +const samples = []; +for (let i = 0; i < 1000; ++i) { + const start = process.hrtime.bigint(); + const result = await client.call('bench.echo', { value: i }); + if (result.value !== i) throw new Error('unexpected result'); + samples.push(Number(process.hrtime.bigint() - start)); +} +samples.sort((a, b) => a - b); +console.log(JSON.stringify({ pipeline_p50_us: samples[499] / 1000, pipeline_p95_us: samples[949] / 1000 })); +""" + + +def measure(label, command, cold, program, cwd): + env = dict(os.environ) + env.pop("PYTHONPATH", None) + starts = [] + for _ in range(15): + start = time.perf_counter_ns() + subprocess.run([*command, cold], cwd=cwd, env=env, check=True, capture_output=True) + starts.append(time.perf_counter_ns() - start) + samples = [ + json.loads(subprocess.check_output([*command, program], cwd=cwd, env=env, text=True)) + for _ in range(3) + ] + result = {key: statistics.median(sample[key] for sample in samples) for key in samples[0]} + result["cold_process_and_import_median_ms"] = statistics.median(starts) / 1_000_000 + return label, result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--python", type=Path) + parser.add_argument("--node", type=Path) + parser.add_argument("--npm-directory", type=Path) + parser.add_argument("--rust-binary", type=Path) + args = parser.parse_args() + results = {} + if args.python is not None: + label, result = measure("python", [args.python, "-I", "-c"], "import apcore", PYTHON, None) + results[label] = result + if args.node is not None and args.npm_directory is not None: + label, result = measure( + "typescript", [args.node, "--input-type=module", "-e"], + "await import('apcore-js')", JAVASCRIPT, args.npm_directory, + ) + results[label] = result + if args.rust_binary is not None: + label, result = measure("rust", [args.rust_binary], "--startup", "--pipeline", None) + result["cold_process_and_assembly_median_ms"] = result.pop("cold_process_and_import_median_ms") + results[label] = result + if not results: + parser.error("pass --python, --rust-binary, or both --node and --npm-directory") + print(json.dumps(results, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/planning/microkernel-delivery/bench-alpha2.rs b/planning/microkernel-delivery/bench-alpha2.rs new file mode 100644 index 00000000..30650c12 --- /dev/null +++ b/planning/microkernel-delivery/bench-alpha2.rs @@ -0,0 +1,49 @@ +use apcore::APCore; +use serde_json::json; +use std::time::Instant; + +#[tokio::main(flavor = "current_thread")] +async fn main() -> Result<(), Box> { + let mut client = APCore::new(); + if std::env::args().any(|argument| argument == "--startup") { + return Ok(()); + } + let schema = json!({ + "type": "object", + "properties": {"value": {"type": "integer"}}, + "required": ["value"] + }); + client.module( + "bench.echo", + "Echo an integer", + schema.clone(), + schema, + None, + Vec::new(), + None, + None, + Vec::new(), + None, + |inputs, _context| Box::pin(async move { Ok(inputs) }), + )?; + for index in 0..100 { + client + .call("bench.echo", json!({"value": index}), None, None) + .await?; + } + let mut samples = Vec::with_capacity(1000); + for index in 0..1000 { + let input = json!({"value": index}); + let start = Instant::now(); + let result = client.call("bench.echo", input, None, None).await?; + samples.push(start.elapsed().as_nanos()); + assert_eq!(result["value"], index); + } + samples.sort_unstable(); + println!( + "{{\"pipeline_p50_us\": {}, \"pipeline_p95_us\": {}}}", + samples[499] as f64 / 1000.0, + samples[949] as f64 / 1000.0, + ); + Ok(()) +} diff --git a/schemas/sys-modules.schema.json b/schemas/sys-modules.schema.json index db6397d4..68a89026 100644 --- a/schemas/sys-modules.schema.json +++ b/schemas/sys-modules.schema.json @@ -108,7 +108,7 @@ }, "subscribers": { "type": "array", - "description": "Declarative subscriber definitions instantiated at registration time. Each entry needs a `type` naming a registered subscriber factory (webhook, a2a, file, stdout, filter).", + "description": "Declarative subscriber definitions instantiated at registration time. The host's factory registry resolves `type`. Built-in types are webhook, file, stdout, and filter. Adapters can supply additional factories.", "items": { "type": "object", "required": ["type"], From 50e316a91a005bcf640005cb9e49d781ac28d387 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 19:37:43 +0800 Subject: [PATCH 08/10] docs(protocol): consolidate the SDK 1.0 draft Signed-off-by: tercel --- CHANGELOG.md | 4 ++-- docs/index.md | 4 ++-- docs/spec/protocol-spec.md | 6 ++---- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 354a8801..f37c5af1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- **Protocol 3.0.0 draft.** The default Core Profile supports in-memory execution, with file-backed capabilities and host integrations supplied by explicit extension profiles. The built-in approval gate rejects calls that require approval when no handler is configured and requires approval for destructive modules by default. An explicit policy with `strict = false` and `gate_destructive = false` retains the earlier behavior during migration. +- **Protocol 2.0.0 draft for SDK 1.0.0.** The default Core Profile supports in-memory execution, with file-backed capabilities and host integrations supplied by explicit extension profiles. The built-in approval gate rejects calls that require approval when no handler is configured and requires approval for destructive modules by default. An explicit policy with `strict = false` and `gate_destructive = false` retains the earlier behavior during migration. - Report the configured project version in the health summary and use the configured usage retention period. ### Fixed @@ -34,7 +34,7 @@ This prerelease delivers the cross-repository governance and streaming fixes ahe ### Added -- **Protocol 2.1.0 draft, §6.7, §9.16.2, and §12.7.9.** Add managed drain and recovery hooks, async lifecycle adapters, host-directed cancellation before forced removal, opt-in reload reports, and lifecycle events across the three SDKs. +- **Managed lifecycle, §6.7, §9.16.2, and §12.7.9.** Add managed drain and recovery hooks, async lifecycle adapters, host-directed cancellation before forced removal, opt-in reload reports, and lifecycle events across the three SDKs. - Add owned shutdown and ordered removal handles with independent wait budgets and lifecycle reports in Python, TypeScript, and Rust. - Expose Prometheus text rendering without starting an HTTP listener in Python and Rust. TypeScript uses the existing exporter render method. - Expose a single-invocation stream completion handle in Python, TypeScript, and Rust. The handle reports the output-validation snapshot, post-processing outcomes, and a distinct terminal reason. diff --git a/docs/index.md b/docs/index.md index 87ac2a3b..f6e0bffd 100644 --- a/docs/index.md +++ b/docs/index.md @@ -24,12 +24,12 @@ 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` | `3.0.0` (draft) | +| Protocol specification | [protocol-spec.md](spec/protocol-spec.md) | `1.66.0` | `2.0.0` (draft) | | Python SDK | `apcore` | `0.33.0` | `1.0.0a2` | | TypeScript SDK | `apcore-js` | `0.33.0` | `1.0.0-alpha.2` | | Rust SDK | `apcore` | `0.33.0` | `1.0.0-alpha.2` | -The three core SDKs share a 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. +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. ## Documentation diff --git a/docs/spec/protocol-spec.md b/docs/spec/protocol-spec.md index df4c0fa3..48626fc8 100644 --- a/docs/spec/protocol-spec.md +++ b/docs/spec/protocol-spec.md @@ -6,7 +6,7 @@ description: "The canonical apcore protocol specification (RFC 2119): module, sc > **Canonical specification.** This document is the single normative source for the apcore protocol. Where any other document disagrees with it, this document wins. -> Version: 3.0.0 +> Version: 2.0.0 > Status: Draft > Last Updated: 2026-11-27 @@ -10306,9 +10306,7 @@ The specification and the SDK have independent version numbers. `CHANGELOG.md` r | Version | Date | Summary | Records | |---|---|---|---| -| 3.0.0 | Unreleased | Define the in-memory Core Profile and opt-in extension profiles (§1.8, §12). Require the default approval gate to reject calls that need a missing handler and require approval for destructive modules by default (§6.6.3.1, §7.4, §7.9). Move provider projections to Surfaces (§4.17 and Appendix D). | [Changelog](https://github.com/aiperceivable/apcore/blob/main/CHANGELOG.md) | -| 2.1.0 | Unreleased | Add managed drain and recovery hooks, scoped forced removal, opt-in governed reload reports, and lifecycle events (§6.7, §9.16.2, §12.7.9). | D-153 | -| 2.0.0 | Unreleased | Resolve every path-typed configuration value against one project root (§9.2.2). Clarify configured redaction for schema-less calls (§6.1.8, §10.6.1). Require invocation-scoped approval resumption and use a non-secret correlation ID in approval telemetry (§7, §9.16.2). Clarify pipeline configuration, preflight, and approval argument scope (§5.16.1, §7.3–7.4, §12.8). Align schema examples with Draft 2020-12 and the unified validation error format (§4.2, §4.14, §8.1). Clarify the APCore trace ID reservation (§10.5). | [#113](https://github.com/aiperceivable/apcore/issues/113) | +| 2.0.0 | 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) | | 1.65.0 | 2026-10-08 | Add public bare-name canonicalization with structured, non-throwing results in all SDKs; preserve A02, ASCII-only case conversion and existing underscores, and reject non-ASCII, invalid starts and overlong output (§2.2.1). | [Rust #40](https://github.com/aiperceivable/apcore-rust/issues/40) | | 1.64.0 | 2026-10-08 | Algorithm A02 is exhaustive and ASCII-scoped: it preserves existing underscores and non-ASCII characters through case conversion, then rejects a result outside the Canonical ID grammar; it never repairs arbitrary identifiers (§2.2). The repairing class-name conversion is named `snake_case_name` and is distinct from A02's `snake_case_identifier` (§2.1.1). | #122 | From 2a0a8b1b2c04acb58c5dbe9f2b45c4923450e409 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 20:00:58 +0800 Subject: [PATCH 09/10] fix(core): resolve alpha.2 review and conformance findings Signed-off-by: tercel --- conformance/check_doc_examples.py | 29 ++++++++-- docs/features/apcore-client.md | 2 +- docs/features/event-system.md | 3 +- docs/features/schema-system.md | 56 ++++++++++++------- docs/spec/conformance.md | 7 ++- planning/microkernel-delivery/alpha-2.md | 7 ++- python/src/apcore/_sync_bridge.py | 14 ++--- python/src/apcore/executor.py | 2 +- .../conformance/test_issue123_contracts.py | 38 +++++++++++++ typescript/src/client.ts | 3 +- typescript/src/discovery.ts | 6 +- .../tests/test-assembly-extensions.test.ts | 14 +++++ 12 files changed, 133 insertions(+), 48 deletions(-) diff --git a/conformance/check_doc_examples.py b/conformance/check_doc_examples.py index 219fcf71..0e7210e9 100644 --- a/conformance/check_doc_examples.py +++ b/conformance/check_doc_examples.py @@ -91,6 +91,16 @@ def python_surface(sdk: Path) -> dict[str, set[str]]: if all_m: names |= set(re.findall(r'"(\w+)"', all_m.group(1))) surface[dotted] = names + + # The root's __getattr__ preserves explicit imports of extension symbols. + # Resolve those routes against their destinations as well as the root. + root = pkg / "__init__.py" + if root.is_file(): + extensions = re.search(r"^_EXTENSION_EXPORTS\s*=\s*\{(.*?)^\}", root.read_text(), re.M | re.S) + if extensions: + for name, module in re.findall(r'"(\w+)":\s*"([\w.]+)"', extensions.group(1)): + if name in surface.get(module, ()): + surface["apcore"].add(name) return surface @@ -119,8 +129,15 @@ def sources(target): } -def _typescript_file_exports(source: Path) -> set[str]: - """Collect top-level declarations and explicit re-exports from source.""" +def _typescript_file_exports(source: Path, visited: set[Path] | None = None) -> set[str]: + """Collect top-level declarations and follow relative barrel re-exports.""" + source = source.resolve() + if visited is None: + visited = set() + if source in visited: + return set() + visited.add(source) + src = source.read_text() declaration = (r"export\s+(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?" r"(?:class|function|const|let|var|interface|type|enum)\s+([\w$]+)") @@ -135,10 +152,10 @@ def _typescript_file_exports(source: Path) -> set[str]: ) if m: names.add(m.group(1)) - for star in re.findall(r"export\s+\*\s+from\s+['\"]\./([^'\"]+)['\"]", src): - p = source.parent / star.replace(".js", ".ts") - if p.is_file(): - names.update(re.findall(declaration, p.read_text())) + for target in re.findall(r"export\s+\*\s+from\s+['\"](\.{1,2}/[^'\"]+)['\"]", src): + reexport = source.parent / (target.removesuffix(".js") + ".ts") + if reexport.is_file(): + names.update(_typescript_file_exports(reexport, visited)) return names diff --git a/docs/features/apcore-client.md b/docs/features/apcore-client.md index 3ebb853b..c8fa6426 100644 --- a/docs/features/apcore-client.md +++ b/docs/features/apcore-client.md @@ -780,7 +780,7 @@ Clients sharing a Registry get the same shutdown operation ID and the same modul The report status is `pending`, `completed`, or `failed`. A batch has one row per input. If its dispatch deadline leaves entries unstarted, its final status is `failed` with `stop_reason: operation_deadline`. A forced removal records any leases still active at unload and whether they are still settling. The coordinator waits for an active drain hook before unloading. -Use `snapshot()` inside a lifecycle callback to inspect its operation, and await the handle from the host outside that callback. In the TypeScript browser entry, the reentry guard covers the synchronous part of a callback. After the callback yields, awaiting its own operation can leave both the callback and the operation waiting indefinitely. +Use `snapshot()` inside a lifecycle callback to inspect its operation, and await the handle from the host outside that callback. In the default TypeScript entry, the reentry guard covers the synchronous part of a callback. After the callback yields, awaiting its own operation can leave both the callback and the operation waiting indefinitely. In Node, the full assembly or `createNodeLifecyclePlugin()` extends the guard across async callbacks. === "Python" diff --git a/docs/features/event-system.md b/docs/features/event-system.md index 236448c6..dbb1154b 100644 --- a/docs/features/event-system.md +++ b/docs/features/event-system.md @@ -361,8 +361,7 @@ to add delivery to an A2A receiver. ```rust use std::path::Path; - use apcore::events::{StdoutSubscriber, SubscriberRegistry}; - use apcore::{APCore, APCoreOptions, Config}; + use apcore::{APCore, APCoreOptions, Config, StdoutSubscriber, SubscriberRegistry}; fn main() -> Result<(), Box> { let mut subscribers = SubscriberRegistry::new(); diff --git a/docs/features/schema-system.md b/docs/features/schema-system.md index 2cc07a36..5947f708 100644 --- a/docs/features/schema-system.md +++ b/docs/features/schema-system.md @@ -81,37 +81,53 @@ At the module-invocation boundary validation is strict: no type coercion is appl ### SchemaExporter and ExportProfile -`SchemaExporter.export(schema_def, profile, ...)` converts a schema definition into a target format selected by `ExportProfile` (§4.17): - -- **`mcp`** — MCP tool definition; keeps `x-*` fields and maps annotations to hints. -- **`openai`** — OpenAI function-calling definition; strips `x-*`, applies strict mode. -- **`anthropic`** — Anthropic tool-use definition. -- **`generic`** — provider-neutral representation. +Core exports a provider-neutral representation of a module's schema and keeps +the JSON Schema extension fields. TypeScript also accepts `ExportProfile.GENERIC` +in `SchemaExporter.export()`. The MCP, OpenAI, and Anthropic profiles belong to +the adapter layer ([§4.17](../spec/protocol-spec.md#417-export-profiles)). === "Python" ```python - from apcore.schema import ExportProfile - - profile = ExportProfile.MCP - # ExportProfile.OPENAI, ExportProfile.ANTHROPIC, ExportProfile.GENERIC - print(profile.value) # "mcp" + from apcore.schema import SchemaDefinition, SchemaExporter + + definition = SchemaDefinition( + module_id="common.echo", + description="Echo a message.", + input_schema={"type": "object"}, + output_schema={"type": "object"}, + ) + print(SchemaExporter().export_generic(definition)["module_id"]) ``` === "TypeScript" ```typescript - import { ExportProfile } from "apcore-js"; - - const profile: ExportProfile = ExportProfile.MCP; - // ExportProfile.OPENAI, ExportProfile.ANTHROPIC, ExportProfile.GENERIC - console.log(profile); // "mcp" + import { SchemaExporter } from "apcore-js"; + + const definition = { + moduleId: "common.echo", + description: "Echo a message.", + inputSchema: { type: "object" }, + outputSchema: { type: "object" }, + definitions: {}, + version: "1.0.0", + }; + console.log(new SchemaExporter().exportGeneric(definition).module_id); ``` === "Rust" ```rust - use apcore::schema::ExportProfile; + use apcore::schema::{export_generic, SchemaDefinition}; + use serde_json::json; fn main() { - let profile = ExportProfile::Mcp; - // ExportProfile::OpenAi, ExportProfile::Anthropic, ExportProfile::Generic - println!("{profile:?}"); + let definition = SchemaDefinition { + module_id: "common.echo".into(), + description: "Echo a message.".into(), + input_schema: json!({"type": "object"}), + output_schema: json!({"type": "object"}), + error_schema: None, + definitions: None, + version: None, + }; + println!("{}", export_generic(&definition)["module_id"]); } ``` diff --git a/docs/spec/conformance.md b/docs/spec/conformance.md index e2144d70..09ed7c8e 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 **98 cross-language fixture files** under `conformance/fixtures/` covering **1225 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 **98 cross-language fixture files** under `conformance/fixtures/` covering **1229 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 @@ -346,7 +346,7 @@ The repository ships **98 cross-language fixture files** under `conformance/fixt | [`annotations_extra_round_trip`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/annotations_extra_round_trip.json) | 12 | `ModuleAnnotations.extra` wire-format round-trip (spec §4.4.1) | | [`approval_gate`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/approval_gate.json) | 11 | Approval gate enforcement at Executor Step 5 (spec §7.4) | | [`approval_request_fields`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/approval_request_fields.json) | 2 | `ApprovalRequest` carries `caller_id` (read straight off `Context.caller_id` — null on a top-level call, never the `@external` ACL sentinel) and `action` (= `module_id`), populated by the approval gate at Executor Step 5 (spec §7.3.1, D-03) | -| [`approval_startup_report`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/approval_startup_report.json) | 5 | Startup reporting for modules that declare approval requirements | +| [`approval_startup_report`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/approval_startup_report.json) | 6 | Startup reporting for modules that declare approval requirements | | [`async_task_cancellation`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/async_task_cancellation.json) | 2 | `AsyncTaskManager.cancel()` real abort via CancelToken (D-18) | | [`async_task_evolution`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/async_task_evolution.json) | 10 | Pluggable `TaskStore`, retry with backoff | | [`bindings_dir_resolution`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/bindings_dir_resolution.json) | 13 | Binding-directory resolution: a loader invoked without an explicit directory resolves `bindings.dir` / `bindings.pattern` under §9.2 precedence, an explicit argument wins, and no scan happens at client initialisation (spec §5.12.6) | @@ -368,6 +368,7 @@ The repository ships **98 cross-language fixture files** under `conformance/fixt | [`document_version_negotiation`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/document_version_negotiation.json) | 9 | Configuration and module-schema file compatibility (A14, spec §13.3) | | [`error_codes`](https://github.com/aiperceivable/apcore/blob/main/conformance/fixtures/error_codes.json) | 19 | Error code collision detection (Algorithm A17, spec §8.4) | | [`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) | | [`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) | @@ -429,7 +430,7 @@ The repository ships **98 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** | **1225** | **98 fixtures** | +| **Total** | **1229** | **98 fixtures** | ### 8.2 Loading Fixtures from a Test Runner diff --git a/planning/microkernel-delivery/alpha-2.md b/planning/microkernel-delivery/alpha-2.md index c9c5677b..8972ff32 100644 --- a/planning/microkernel-delivery/alpha-2.md +++ b/planning/microkernel-delivery/alpha-2.md @@ -38,10 +38,11 @@ The approved alpha.1 build hashes remain the comparison baseline. Validate alpha The local review identified an Anthropic recursive-schema regression, a missing TypeScript public export, and an inconsistent custom-strategy diagnostic. The revised converters, packaged imports and governance tests cover these cases. -Candidate branches are local. GitHub review and hosted CI are pending. Tags -and package publication remain paused. +Follow hosted CI and review in [Core PR #236](https://github.com/aiperceivable/apcore/pull/236) +and [Surfaces PR #125](https://github.com/aiperceivable/apcore-surfaces/pull/125). +Tags and package publication remain paused. -### Core candidate artifacts +### Initial local Core candidate artifacts | Distribution | SDK version | SHA-256 | | --- | --- | --- | diff --git a/python/src/apcore/_sync_bridge.py b/python/src/apcore/_sync_bridge.py index f0000d67..13b2d802 100644 --- a/python/src/apcore/_sync_bridge.py +++ b/python/src/apcore/_sync_bridge.py @@ -8,7 +8,7 @@ import time import weakref from collections.abc import Coroutine -from concurrent.futures import Future, ThreadPoolExecutor +from concurrent.futures import Future from typing import Any from apcore.errors import ErrorCodes, ModuleError, ModuleTimeoutError @@ -31,7 +31,6 @@ def __init__(self) -> None: self._lock = threading.Lock() self._local = threading.local() self._loops: weakref.WeakSet[_ThreadLoop] = weakref.WeakSet() - self._pool: ThreadPoolExecutor | None = None self._slots = threading.BoundedSemaphore(_NESTED_WORKERS) def close(self) -> None: @@ -42,9 +41,6 @@ def close(self) -> None: owner.retired = True if not owner.active: owner.close() - pool, self._pool = self._pool, None - if pool is not None: - pool.shutdown(wait=False) def run(self, coro: Coroutine[Any, Any, Any], module_id: str, wait: float | None) -> Any: try: @@ -77,7 +73,7 @@ def run(self, coro: Coroutine[Any, Any, Any], module_id: str, wait: float | None def _run_on_worker(self, coro: Coroutine[Any, Any, Any], module_id: str, wait: float | None) -> Any: deadline = None if wait is None else time.monotonic() + wait reentrant = getattr(_worker_thread, "active", False) - # A worker waiting for another slot could deadlock the pool. It can + # A worker waiting for another slot could deadlock the bridge. It can # make a nested sync call while there is spare capacity. admitted = self._slots.acquire(blocking=False) if reentrant else self._slots.acquire(timeout=wait) if not admitted: @@ -131,10 +127,8 @@ def run() -> None: self._slots.release() try: - with self._lock: - if self._pool is None: - self._pool = ThreadPoolExecutor(max_workers=_NESTED_WORKERS, thread_name_prefix="apcore-sync") - self._pool.submit(run) + # A timed-out caller can exit even when module cleanup is slow. + threading.Thread(target=run, name="apcore-sync", daemon=True).start() except BaseException: self._slots.release() coro.close() diff --git a/python/src/apcore/executor.py b/python/src/apcore/executor.py index a1d72040..767d0580 100644 --- a/python/src/apcore/executor.py +++ b/python/src/apcore/executor.py @@ -646,7 +646,7 @@ def call( Sync wrapper around :meth:`call_async`. Each thread caches its own loop for synchronous calls. A call made inside a running loop uses a - bounded worker pool instead. + background worker, with a bound on concurrent workers. Args: module_id: The module to execute. diff --git a/python/tests/conformance/test_issue123_contracts.py b/python/tests/conformance/test_issue123_contracts.py index a1fd2e92..bd3f9b33 100644 --- a/python/tests/conformance/test_issue123_contracts.py +++ b/python/tests/conformance/test_issue123_contracts.py @@ -10,6 +10,9 @@ import copy import json import os +import subprocess +import sys +import textwrap import time from dataclasses import asdict from datetime import datetime @@ -530,6 +533,41 @@ async def execute(inputs: dict[str, Any], context: Context) -> dict[str, bool]: assert await asyncio.to_thread(completed.wait, 1) +def test_d133_sync_bridge_cleanup_does_not_delay_process_exit() -> None: + program = textwrap.dedent("""\ + import asyncio + from apcore import APCore + from apcore.errors import ModuleTimeoutError + + class SlowModule: + input_schema = {"type": "object"} + output_schema = {"type": "object"} + description = "A module with slow cancellation cleanup" + + async def execute(self, inputs, context): + try: + await asyncio.sleep(30) + finally: + await asyncio.sleep(30) + + async def main(): + client = APCore() + await client.register_async("sample.slow", SlowModule()) + try: + client.executor.call("sample.slow", timeout_ms=300) + except ModuleTimeoutError: + print("caller saw timeout", flush=True) + else: + raise AssertionError("expected the sync bridge deadline to expire") + client.close() + print("client closed", flush=True) + + asyncio.run(main()) + """) + result = subprocess.run([sys.executable, "-c", program], capture_output=True, text=True, timeout=5, check=True) + assert result.stdout.splitlines() == ["caller saw timeout", "client closed"] + + def test_d136_native_python_inputs_remain_supported() -> None: """D-136 preserves already typed Python inputs while rejecting coercion.""" registry = Registry() diff --git a/typescript/src/client.ts b/typescript/src/client.ts index d8a50c47..bffab9d3 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -189,7 +189,8 @@ export class APCore { // Respect ACLs already configured on a supplied Executor. if (this.config && prebuiltExecutor === undefined) { - if (discoverAcl === undefined && this.config.get('acl.root') != null) { + const aclRoot = this.config.getDeclared('acl.root'); + if (discoverAcl === undefined && aclRoot != null && aclRoot !== '') { throw new InvalidInputError('Configured ACL paths require an ACL discovery plugin or a configured executor'); } const discovered = discoverAcl?.(this.config); diff --git a/typescript/src/discovery.ts b/typescript/src/discovery.ts index e3ce7f7e..c765cf87 100644 --- a/typescript/src/discovery.ts +++ b/typescript/src/discovery.ts @@ -17,6 +17,10 @@ export function createDiscoveryRegistry(options?: DiscoveryRegistryOptions): Reg /** Install filesystem discovery on the registry this client constructs. */ export function createFilesystemDiscoveryPlugin(options?: Omit): APCorePlugin { return { - createRegistry: (config, lifecycleCallbacks) => createDiscoveryRegistry({ ...options, config, lifecycleCallbacks }), + createRegistry: (config, lifecycleCallbacks) => createDiscoveryRegistry({ + ...options, + config, + lifecycleCallbacks: lifecycleCallbacks ?? options?.lifecycleCallbacks, + }), }; } diff --git a/typescript/tests/test-assembly-extensions.test.ts b/typescript/tests/test-assembly-extensions.test.ts index 64c7d521..4070a2d0 100644 --- a/typescript/tests/test-assembly-extensions.test.ts +++ b/typescript/tests/test-assembly-extensions.test.ts @@ -54,6 +54,20 @@ describe('instance-scoped assembly extensions', () => { } }); + it('keeps the lifecycle callbacks configured on the discovery registry', () => { + const callbacks = createDiscoveryRegistry().lifecycleCallbacks; + const discovery = createFilesystemDiscoveryPlugin({ lifecycleCallbacks: callbacks }); + const client = new APCore({ plugins: [discovery] }); + + expect(client.registry.lifecycleCallbacks).toBe(callbacks); + }); + + it('requires an ACL discovery plugin only for an explicitly configured ACL path', () => { + const plugins = [createFilesystemDiscoveryPlugin()]; + expect(new APCore({ config: Config.fromDefaults(), plugins }).executor.governanceState().aclConfigured).toBe(false); + expect(() => new APCore({ config: new Config({ acl: { root: 'acl' } }), plugins })).toThrow(/ACL discovery plugin/); + }); + it('loads ACL files explicitly and lets the client assemble only its own executor', async () => { const root = await mkdtemp(join(tmpdir(), 'apcore-acl-plugin-')); try { From 3b5fb5defb7e32900da4e826a848bb23258cd91e Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 20:01:55 +0800 Subject: [PATCH 10/10] test(rust): synchronize shutdown subscriber test setup Signed-off-by: tercel --- planning/microkernel-delivery/alpha-2.md | 2 +- rust/tests/test_client.rs | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/planning/microkernel-delivery/alpha-2.md b/planning/microkernel-delivery/alpha-2.md index 8972ff32..068547f8 100644 --- a/planning/microkernel-delivery/alpha-2.md +++ b/planning/microkernel-delivery/alpha-2.md @@ -50,7 +50,7 @@ Tags and package publication remain paused. | npm archive | `1.0.0-alpha.2` | `fbfc83403234056023d843c424de58d42d6056cb9cbd94d92c0642d2ea0832d9` | | Rust crate | `1.0.0-alpha.2` | `54e630a6f3c82ee9e01aec1f58ad14a06e21d8082414a1f4d398bce2f45b4de3` | -Surfaces CI builds its Python wheel from Core commit `dc61dd575a3d76a113f55a84175b6f36ba35e894`. The TypeScript and Rust jobs use Core commit `0384a3d4e7688c47eaa1feea6032fb4739813f20`. The Rust lock records the archive built from that commit, including its Cargo VCS metadata. +The initial Surfaces checks built the Python wheel from Core commit `dc61dd575a3d76a113f55a84175b6f36ba35e894` and the TypeScript and Rust distributions from `0384a3d4e7688c47eaa1feea6032fb4739813f20`. The Rust lock records the archive built from that commit, including its Cargo VCS metadata. The cross-repository compatibility workflow also tests the exact distributions uploaded by the hosted Core build. ## Benchmark diff --git a/rust/tests/test_client.rs b/rust/tests/test_client.rs index a2dc2b07..3fe49919 100644 --- a/rust/tests/test_client.rs +++ b/rust/tests/test_client.rs @@ -602,10 +602,11 @@ async fn test_managed_shutdown_rejects_wait_from_its_unload_hook() { async fn test_shutdown_flush_budget_is_local_and_subscribers_cannot_wait_on_it() { use apcore::events::subscribers::EventSubscriber; use futures_util::FutureExt; + use tokio::sync::watch; #[derive(Debug)] struct HoldingSubscriber { - operation: Arc>>, + operation: watch::Receiver>, observed: Arc, release: Arc, } @@ -616,7 +617,14 @@ async fn test_shutdown_flush_budget_is_local_and_subscribers_cannot_wait_on_it() if event.module_id.as_deref() != Some("demo.echo") { return Ok(()); } - let operation = self.operation.lock().unwrap().clone().unwrap(); + // Shutdown can emit the event before the caller receives its operation. + let mut operation = self.operation.clone(); + let operation = operation + .wait_for(Option::is_some) + .await + .unwrap() + .clone() + .unwrap(); let result = operation.wait(None).now_or_never().unwrap(); assert_eq!(result.unwrap_err().code, ErrorCode::GeneralInvalidInput); self.observed.notify_one(); @@ -632,14 +640,14 @@ async fn test_shutdown_flush_budget_is_local_and_subscribers_cannot_wait_on_it() None, None, ); - let operation_slot = Arc::new(Mutex::new(None)); + let (operation_sender, operation_receiver) = watch::channel(None); let observed = Arc::new(tokio::sync::Notify::new()); let release = Arc::new(tokio::sync::Notify::new()); client .on_subscriber( "apcore.registry.module_unregistered", Box::new(HoldingSubscriber { - operation: Arc::clone(&operation_slot), + operation: operation_receiver, observed: Arc::clone(&observed), release: Arc::clone(&release), }), @@ -652,7 +660,7 @@ async fn test_shutdown_flush_budget_is_local_and_subscribers_cannot_wait_on_it() ..Default::default() })) .unwrap(); - *operation_slot.lock().unwrap() = Some(operation.clone()); + operation_sender.send(Some(operation.clone())).unwrap(); let peer = peer .start_shutdown(Some(apcore::ShutdownOptions { event_flush_timeout_ms: Some(0),