diff --git a/deploy/observability/init-db.py b/deploy/observability/init-db.py index 08ee09a913..99af86fc88 100644 --- a/deploy/observability/init-db.py +++ b/deploy/observability/init-db.py @@ -20,10 +20,10 @@ from sqlalchemy.engine import make_url +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.runtime.composition import open_builtin_runtime from powercontext.builtin.runtime.config import BuiltinConfig -from powercontext.server.authz import PrincipalRef -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.settings import ServerSettings diff --git a/deploy/observability/run-host.py b/deploy/observability/run-host.py index f975af6989..bfe6c6ac67 100644 --- a/deploy/observability/run-host.py +++ b/deploy/observability/run-host.py @@ -41,7 +41,7 @@ def main() -> int: if args.container: environment = dict(os.environ) else: - from powercontext.cli.env_file import read_environment_file + from powercontext.env_file import read_environment_file environment.update(read_environment_file(local / "server.env")) if not args.container: diff --git a/desktop/tests/real_server.py b/desktop/tests/real_server.py index 76af3cd989..9c1d1d2e31 100644 --- a/desktop/tests/real_server.py +++ b/desktop/tests/real_server.py @@ -66,12 +66,12 @@ def probe_measurement( def fixture_provider(config, admin): + from powercontext.builtin.authz import PrincipalRef from powercontext.server.authentication import ( AuthenticationRejectedError, AuthenticationResult, ProviderReadiness, ) - from powercontext.server.authz import PrincipalRef class FixtureProvider: async def authenticate(self, request): @@ -290,9 +290,9 @@ async def run(): if not config.get("provider"): await server.serve() return + from powercontext.builtin.authz import PrincipalRef + from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.persistence.migrations.server_readiness import prepare_server_storage - from powercontext.server.authz import PrincipalRef - from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.settings import AccessControlConfig admin = PrincipalRef(type="service", id="desktop-fixture-admin") diff --git a/docs/en/development/core-protocol.md b/docs/en/development/core-protocol.md index a0a24c3615..12f931cfae 100644 --- a/docs/en/development/core-protocol.md +++ b/docs/en/development/core-protocol.md @@ -102,8 +102,8 @@ conflicts and persistence; the family service is responsible for its domain beha A `Trigger` is a policy over a signal and prior state. It returns a `PolicyTransition` containing the next state and zero or more actions. A Trigger should not open storage, schedule itself, or perform the action it selects. -APScheduler belongs to the Builtin runtime lifecycle. It decides when to evaluate a policy. The Trigger decides what -the observed signal means. +The Builtin runtime's Artifact Processing Supervisor decides when to evaluate a policy. The Trigger decides what the +observed signal means. ## Ownership boundaries diff --git a/docs/en/development/remote-access-implementation.md b/docs/en/development/remote-access-implementation.md index 21cca85981..e373fb5a7d 100644 --- a/docs/en/development/remote-access-implementation.md +++ b/docs/en/development/remote-access-implementation.md @@ -80,9 +80,9 @@ and OceanBase uses HNSW for `vector` and `hybrid` searches. Inference configuration is documented in [Configure Pydantic AI inference](pydantic-ai-inference.md). -Set `POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS` to process pending Source windows on a persisted interval. Scheduled -jobs use the SQLite sidecar at `POWERCONTEXT_HOME/scheduler.db`. Scheduling works with either application database and -requires a configured generation pipeline. +Set `POWERCONTEXT_SERVER_RUNTIME_MEMORY_SCHEDULE_SECONDS` to admit pending Source windows on an interval. The Artifact +Processing Supervisor keeps its processing state in the application database and creates no separate scheduler +database. Scheduling works with either application database and requires a configured generation pipeline. ## HTTP surface diff --git a/docs/en/docs/develop/interfaces.md b/docs/en/docs/develop/interfaces.md index 6ad163f744..63d3b9485a 100644 --- a/docs/en/docs/develop/interfaces.md +++ b/docs/en/docs/develop/interfaces.md @@ -249,9 +249,9 @@ selector retains that selector, and Experience incubation uses its independent c ## Scheduled Experience incubation An integration can capture a completed task as a Content Source with metadata `"kind": "task-outcome"`. When the -Experience schedule is configured, APScheduler scans bounded Source windows and asks the configured schema-bound -pipeline for reusable situation, action, outcome, and lesson proposals. Each proposal cites exact Sources and enters -the Review Inbox as a pending Experience Candidate. +Experience schedule is configured, the Artifact Processing Supervisor scans bounded Source windows and asks the +configured schema-bound pipeline for reusable situation, action, outcome, and lesson proposals. Each proposal cites +exact Sources and enters the Review Inbox as a pending Experience Candidate. Experience incubation has its own persisted Source cursor, independent from Memory extraction. Candidate writes and cursor advancement commit together; a generation or write failure leaves the window available for retry. Ordinary diff --git a/docs/en/rfcs/0019_local_source_memory_runtime.md b/docs/en/rfcs/0019_local_source_memory_runtime.md index 318d453831..a6295bcbe2 100644 --- a/docs/en/rfcs/0019_local_source_memory_runtime.md +++ b/docs/en/rfcs/0019_local_source_memory_runtime.md @@ -9,6 +9,10 @@ description: A proposal for a SQLite-backed Runtime that captures scoped Sources > **Note:** PowerContext now uses bundled sqlite-vec for SQLite vector search. Statements about Vec1 in this RFC no > longer apply and remain only as a record of the original design. +> +> **Note:** Automatic processing runs under the Artifact Processing Supervisor +> ([RFC 1515](1515_artifact_processing_supervisor.md)). The APScheduler interval job, its SQLite sidecar, and +> `ScheduledSourceProcessor` described in this RFC no longer exist and remain only as a record of the original design. # Summary diff --git a/docs/zh/development/core-protocol.md b/docs/zh/development/core-protocol.md index f4d6938eff..70eb08abe9 100644 --- a/docs/zh/development/core-protocol.md +++ b/docs/zh/development/core-protocol.md @@ -98,7 +98,7 @@ service 负责领域行为。 `Trigger` 是基于 signal 和先前 state 的策略。它返回 `PolicyTransition`,其中包含下一状态和零个或多个 action。 Trigger 不应打开存储、调度自身或执行它选择的 action。 -APScheduler 属于 Builtin runtime 的生命周期,负责决定何时评估策略。Trigger 只解释当前 signal 的含义。 +Builtin runtime 的 Artifact Processing Supervisor 负责决定何时评估策略。Trigger 只解释当前 signal 的含义。 ## 职责边界 diff --git a/docs/zh/development/remote-access-implementation.md b/docs/zh/development/remote-access-implementation.md index 0a64c51448..afc35ada5a 100644 --- a/docs/zh/development/remote-access-implementation.md +++ b/docs/zh/development/remote-access-implementation.md @@ -76,9 +76,9 @@ export POWERCONTEXT_SERVER_DATABASE_URL="mysql+aoceanbase://user:password@host:2 inference 配置见[配置 Pydantic AI 推理](pydantic-ai-inference.md)。 -设置 `POWERCONTEXT_SERVER_RUNTIME_SCHEDULE_SECONDS` 可以按持久化 interval 处理待消费的 Source window。 -定时 job 使用 `POWERCONTEXT_HOME/scheduler.db` 作为 SQLite sidecar。调度可以配合任一 application database -使用,但必须配置 generation pipeline。 +设置 `POWERCONTEXT_SERVER_RUNTIME_MEMORY_SCHEDULE_SECONDS` 可以按 interval 准入待消费的 Source window。 +Artifact Processing Supervisor 把处理状态保存在 application database 中,不会创建独立的 scheduler 数据库。 +调度可以配合任一 application database 使用,但必须配置 generation pipeline。 ## HTTP 接口 diff --git a/docs/zh/docs/develop/interfaces.md b/docs/zh/docs/develop/interfaces.md index ded179ce5a..e1a367803a 100644 --- a/docs/zh/docs/develop/interfaces.md +++ b/docs/zh/docs/develop/interfaces.md @@ -227,9 +227,9 @@ selector;Experience 孵化继续使用独立的游标和定时任务。 ## 后台 Experience 孵化 Integration 可以把已完成任务采集为 metadata 含 `"kind": "task-outcome"` 的 Content Source。启用 -Experience schedule 后,APScheduler 会扫描有上限的 Source window,并让配置好的 schema-bound pipeline -生成可复用的 situation、action、outcome 和 lesson。每条 proposal 都引用精确 Source,并以 pending -Experience Candidate 进入 Review Inbox。 +Experience schedule 后,Artifact Processing Supervisor 会扫描有上限的 Source window,并让配置好的 +schema-bound pipeline 生成可复用的 situation、action、outcome 和 lesson。每条 proposal 都引用精确 Source, +并以 pending Experience Candidate 进入 Review Inbox。 Experience 孵化使用独立于 Memory extraction 的持久化 Source cursor。Candidate 写入和 cursor 推进会在同一 事务提交;generation 或写入失败时,该 window 保留给下次重试。普通 Prompt Source 不是 Task Outcome, diff --git a/docs/zh/rfcs/0019_local_source_memory_runtime.md b/docs/zh/rfcs/0019_local_source_memory_runtime.md index 905656392a..0fb5293506 100644 --- a/docs/zh/rfcs/0019_local_source_memory_runtime.md +++ b/docs/zh/rfcs/0019_local_source_memory_runtime.md @@ -9,6 +9,9 @@ description: 本地 Runtime 的设计提案,以 SQLite 保存 Scope 内的 Sou > **注意:** PowerContext 当前使用随 builtin 依赖捆绑的 sqlite-vec 提供 SQLite 向量检索。本 RFC 中关于 Vec1 的 > 表述已不再适用,仅作为原始设计记录保留。 +> +> **注意:** 自动处理由 Artifact Processing Supervisor 执行([RFC 1515](1515_artifact_processing_supervisor.md))。 +> 本 RFC 描述的 APScheduler interval job、SQLite sidecar 和 `ScheduledSourceProcessor` 已不存在,仅作为原始设计记录保留。 # Summary diff --git a/evaluation/agent_tool_recovery/server.py b/evaluation/agent_tool_recovery/server.py index 676f0b9bdf..89934a2dac 100644 --- a/evaluation/agent_tool_recovery/server.py +++ b/evaluation/agent_tool_recovery/server.py @@ -55,9 +55,9 @@ AuthenticationResult, ProviderReadiness, ) -from powercontext.server.authz import AccessBinding, AccessBindingState, AccessRole, ResourceRef -from powercontext.server.authz.models import PrincipalRef -from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.authz import AccessBinding, AccessBindingState, AccessRole, ResourceRef +from powercontext.builtin.authz.models import PrincipalRef +from powercontext.builtin.authz.repository import ACCESS_TABLES, RelationalAccessRepository from powercontext.server.context import is_internal_bridge from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, ServerSettings diff --git a/evaluation/memory/capture_ownership/src/powercontext_eval_capture_ownership/replay.py b/evaluation/memory/capture_ownership/src/powercontext_eval_capture_ownership/replay.py index ec4186faf4..7e9bcf185c 100644 --- a/evaluation/memory/capture_ownership/src/powercontext_eval_capture_ownership/replay.py +++ b/evaluation/memory/capture_ownership/src/powercontext_eval_capture_ownership/replay.py @@ -302,7 +302,7 @@ async def run_experiment( extraction_instructions=definition.default_instructions, ) # Real ASGI HTTP routes and application lifespan, not a mocked capture handler. - with TestClient(create_server_app(settings=settings, scheduler_path=private_dir / "scheduler.db")) as client: + with TestClient(create_server_app(settings=settings)) as client: response = client.post( "/v1/scopes", json={ diff --git a/evaluation/memory/source_poisoning/README.md b/evaluation/memory/source_poisoning/README.md index 82cfef68ee..78b2ed2cb6 100644 --- a/evaluation/memory/source_poisoning/README.md +++ b/evaluation/memory/source_poisoning/README.md @@ -119,7 +119,7 @@ do not point them at a production catalog. No paid-provider call is part of a no ), inference=configured_inference, ) - app = create_server_app(settings=settings, scheduler_path=temporary_scheduler) + app = create_server_app(settings=settings) ``` 3. For each entry in `cases.json`, create a new Scope using `POST /v1/scopes`. For each `sources` string, call diff --git a/evaluation/performance/input_encoding/runner.py b/evaluation/performance/input_encoding/runner.py index 3098136558..8da461a7a4 100644 --- a/evaluation/performance/input_encoding/runner.py +++ b/evaluation/performance/input_encoding/runner.py @@ -282,18 +282,18 @@ async def _attempt( @asynccontextmanager -async def _open_runtime(config: BuiltinConfig, *, scheduler_path: Path): +async def _open_runtime(config: BuiltinConfig): """Reject absent external databases before each evaluation or readback opening.""" if isinstance(config.database, OceanBaseConfig): async with OceanBaseProfile.open_existing(config.database, tables=()): pass - async with open_builtin_runtime(config, scheduler_path=scheduler_path) as runtime: + async with open_builtin_runtime(config) as runtime: yield runtime async def _reopen(configs, args) -> None: for mode, config in configs.items(): - async with _open_runtime(config, scheduler_path=args.output / f"scheduler-{mode}.db") as runtime: + async with _open_runtime(config) as runtime: for path in sorted((args.output / "attempts").glob("*.json")): result = json.loads(path.read_text()) if result["mode"] != mode or "artifact_ref" not in result: @@ -390,10 +390,7 @@ async def run(args) -> None: with observe_usage(): async with AsyncExitStack() as stack: runtimes = { - mode: await stack.enter_async_context( - _open_runtime(config, scheduler_path=args.output / f"scheduler-{mode}.db") - ) - for mode, config in configs.items() + mode: await stack.enter_async_context(_open_runtime(config)) for mode, config in configs.items() } execution_start = time.perf_counter() segment["startup_seconds"] = execution_start - startup diff --git a/examples/jupyter/13_team_access_control.ipynb b/examples/jupyter/13_team_access_control.ipynb index de334f5938..91ef9a3ef3 100644 --- a/examples/jupyter/13_team_access_control.ipynb +++ b/examples/jupyter/13_team_access_control.ipynb @@ -79,10 +79,10 @@ "import secrets\n", "from secrets import compare_digest\n", "\n", + "from powercontext.builtin.authz import PrincipalRef\n", + "from powercontext.builtin.authz.composition import open_builtin_access_control\n", "from powercontext.client import ForbiddenResponseError, PowerContextClient\n", "from powercontext.server.authentication import AuthenticationRejectedError, AuthenticationResult, ProviderReadiness\n", - "from powercontext.server.authz import PrincipalRef\n", - "from powercontext.server.authz.composition import open_builtin_access_control\n", "from powercontext.server.settings import AccessControlConfig, BearerAuthConfig\n", "\n", "principals = {\n", diff --git a/examples/jupyter/_tutorial.py b/examples/jupyter/_tutorial.py index 039cf9bf43..8c10b1ecf3 100644 --- a/examples/jupyter/_tutorial.py +++ b/examples/jupyter/_tutorial.py @@ -184,7 +184,7 @@ def _start_server(self) -> None: ) if self.settings_overrides: settings = ServerSettings.model_validate({**dict(settings), **self.settings_overrides}) - app = create_server_app(settings=settings, scheduler_path=self.directory / "scheduler.db", **self.app_options) + app = create_server_app(settings=settings, **self.app_options) listener = socket.socket() listener.bind(("127.0.0.1", 0)) self._listener = listener diff --git a/examples/systemone/README.md b/examples/systemone/README.md index 887d35bd46..570a7ae49f 100644 --- a/examples/systemone/README.md +++ b/examples/systemone/README.md @@ -98,7 +98,6 @@ async def main() -> None: async with open_builtin_runtime( config, decision_model=backend, - scheduler_path=directory / "scheduler.db", ) as runtime: model = runtime.decision_model if model is None: diff --git a/examples/systemone/applicability_eval.py b/examples/systemone/applicability_eval.py index 87ee574a2a..0c01f9636b 100644 --- a/examples/systemone/applicability_eval.py +++ b/examples/systemone/applicability_eval.py @@ -40,8 +40,8 @@ from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import DecisionModel, DecisionOutcome, RuntimeConfig from powercontext.builtin.runtime.config import ExternalSkillsConfig -from powercontext.cli.env_file import EnvironmentFileError, read_environment_file from powercontext.client import PowerContextClient +from powercontext.env_file import EnvironmentFileError, read_environment_file from powercontext.http import ArtifactReference from powercontext.server.factory import create_server_app from powercontext.server.settings import McpConfig, MetricsConfig, ServerSettings @@ -221,7 +221,6 @@ async def run(args: argparse.Namespace, config: SystemOneConfig) -> Path: mcp=McpConfig(enabled=False), metrics=MetricsConfig(enabled=False), ), - scheduler_path=directory / "scheduler.db", ) budget = load_laya_budget(args.checkpoint) if config.provider == "laya" else None source_digests = { diff --git a/examples/systemone/decision.py b/examples/systemone/decision.py index 2a20769714..81ddfcdddb 100644 --- a/examples/systemone/decision.py +++ b/examples/systemone/decision.py @@ -56,9 +56,7 @@ async def evaluate( runtime_config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{data_dir / 'runtime.db'}")) async with httpx.AsyncClient(timeout=config.timeout_seconds) as client: backend = SystemOneDecisionModel(config, client, laya_budget=budget) - async with open_builtin_runtime( - runtime_config, decision_model=backend, scheduler_path=data_dir / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(runtime_config, decision_model=backend) as runtime: decision_model = runtime.decision_model if decision_model is None: raise RuntimeError("The Runtime did not expose the injected decision model") # noqa: TRY003 diff --git a/examples/systemone/server.py b/examples/systemone/server.py index 4c1b9289b9..2764085b2e 100644 --- a/examples/systemone/server.py +++ b/examples/systemone/server.py @@ -289,9 +289,7 @@ async def review(self, run: dict[str, Any]) -> None: client, laya_budget=self.laya_budget if provider == "laya" else None, ) - async with open_builtin_runtime( - config, decision_model=backend, scheduler_path=directory / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(config, decision_model=backend) as runtime: if runtime.decision_model is None: raise DemoError("The Runtime did not expose the injected decision model.") # noqa: TRY003 for arm in _ARMS: diff --git a/examples/systemone/worker.py b/examples/systemone/worker.py index 5e1d595d89..79e0b6e11d 100644 --- a/examples/systemone/worker.py +++ b/examples/systemone/worker.py @@ -71,7 +71,7 @@ async def execute(request: dict[str, Any]) -> dict[str, Any]: raise ValueError("The run directory must be an absolute path") # noqa: TRY003 await asyncio.to_thread(directory.mkdir, parents=True, exist_ok=True) config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{directory / 'runtime.db'}")) - async with open_builtin_runtime(config, scheduler_path=directory / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: memory = runtime.atomic_memory if memory is None: raise RuntimeError("Atomic Memory is unavailable") # noqa: TRY003 diff --git a/pyproject.toml b/pyproject.toml index 209bdfdc13..4da809be88 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -121,7 +121,7 @@ powercontext = "powercontext.cli.app:main" powercontext-ops = "powercontext.ops.__main__:main" [project.entry-points."powercontext.cli"] -code = "powercontext.builtin.code.cli:app" +code = "powercontext.cli.code:app" config = "powercontext.cli.config:app" doctor = "powercontext.cli.system:doctor_app" observability = "powercontext.observability.cli:app" diff --git a/release/upgrade-support.json b/release/upgrade-support.json index 39f2e09919..ed3f9baafb 100644 --- a/release/upgrade-support.json +++ b/release/upgrade-support.json @@ -3,8 +3,8 @@ "target_version": "1.5.1", "mode": "upgrade-required", "schema_review": { - "persistence_sha256": "d09de34ffb55e59616feac2a0fdb94cf4ef3a045879d3040ff1c68cbe74e5e43", - "rationale": "Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. Revision v1_5_0_004 adds the optional pc_artifact_source_locators relation keyed by the existing Artifact Revision and Source-edge ordinal for both registered source releases and vector/Code profiles. Explicit maintenance creates the empty relation without rewriting historical lineage, payloads, Source identities, earlier revision resources or checksums. Missing locators remain omitted in legacy encodings; located citations survive persistence, HTTP/MCP and portable export/restore, and Source sequence mismatches are rejected without redirecting identity. Atomic Memory content and vector bindings are unchanged, so locator metadata does not require re-embedding. Local SQLite migration, restart, citation and portable round-trip tests pass; MySQL layout checks do not constitute native seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic matrix and publication restrictions remain unchanged. Projection verification and repair read only the exact authoritative head content and state, avoiding target-only Source locator lineage tables at earlier registered migration checkpoints. Frozen resources and revision checksums remain unchanged. Source locator line-count and heading-path limits are centralized without changing their values, accepted payloads or stored encodings. Gateway authorization adds the Scope-level gateway.user role and gateway.invoke action to the existing binding vocabulary. It does not change stored binding structure or migration resources: existing records retain their role and do not implicitly gain gateway.invoke; new grants use the existing binding persistence and resource validation. Existing upgrade support remains upgrade-required and is not certified by this digest refresh. OceanBase Atomic Memory lexical retrieval uses native MATCH with minimum_should_match and SCORE when a controlled capability probe confirms support, and retains the existing MATCH AGAINST plus complete-word coverage path for unsupported backends. Capability decisions are held only in memory per connection pool. Search, complete related enumeration and recovery preserve Analyzer term deduplication, coverage thresholds, scope and content filters, vector completeness checks, same-statement authority heads and the existing oceanbase_match raw-score contract. This query-only change adds no tables, public interfaces, schema revisions, stored fields or row encodings; existing SPACE index definitions, projection formats, historical migration resources and revision checksums remain unchanged. No schema migration or projection rebuild is required for this query implementation. The upgrade-required policy, registered sources and complete installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. Queries above 256 distinct terms retain whole-word coverage unless the engine is identified as OceanBase 4.6 or newer, because earlier native engines can accept MATCH while ignoring that threshold. This compatibility guard changes query selection only. Native capability caching obtains the pool through run_sync, including pinned historical migration connections, without acquiring another connection or releasing maintenance locks. Queries containing SPACE stopwords retain Analyzer-based whole-word admission in all lexical operations. These corrections change neither stored projections nor registered schema resources. SQLite Topic Memory full-text helper version 2 assigns each Scope's helper rows to a hashed 2^32-rowid range above every rowid that version 1 assigned, so Topic replacement and search bound their FTS5 cursors to one Scope's range. Virtual table definitions, registered schema fingerprints, migration resources and authoritative active Topic rows are unchanged. Unmanaged initialization and the existing s1400 domain step rebuild version-1 helper rows from the active tables with exact identities and revisions; a managed database that still holds version-1 helper rows keeps the previous identity filters until the helper is rebuilt. bm25 statistics remain table-wide, so search hits, ordering and scores are unchanged. The standalone seekdb maintenance identity is derived from @@server_uuid and DATABASE() when ob_compatibility_mode is missing, NULL, or empty and VERSION() contains -OceanBase seekdb-. The db-migrate identity probe and the server-run tenant gate share one compatibility classifier; ORACLE and non-seekdb servers remain rejected. This is an admission-only change and does not alter registered table layouts, migration resources, persisted row encodings, or public interfaces. Source writes and text retrieval reuse parameterized SQL structures with fresh Scope, identity, revision, binding and increment values on every execution. Only the fixed built-in Content manifest construction and exact validated payload bytes reuse cached metadata; database registration and indexed-identity checks remain current, and callers receive deep copies. MySQL/OceanBase journal allocation retains SELECT FOR UPDATE; SQLite retains its write reservation. Concurrent Content captures coalesce already queued requests into bounded transactions, isolate individual failures after batch rollback, replay stable identities on cancellation and drain admitted callers during shutdown. No schema, migration, stored encoding, Source identity, journal ordering, processing counter semantics or upgrade support claims change. A Topic Memory window attempt whose publication loses the Topic head CAS to a concurrent replace or Dream records last_error_code head_conflict on its existing pc_topic_memory_work_budgets row, and the attempt ceiling and the next attempt's counter treat that one attempt as not spent. Provider request and token charges stay committed and are never refunded. No table layout, column, constraint, migration resource, revision checksum or row encoding changes; existing rows never carry head_conflict, so their counters and blocks keep their meaning. A binary without this change counts such an attempt as spent, which can only stop that frontier sooner. The Dashboard processing page reads the existing Source journal and Artifact lineage relation and marks only Sources with an exact Artifact citation. It introduces no new table or public JSON interface and does not reconstruct execution history, delivery or adoption. Source journal envelopes record an optional UTC saved_at timestamp for newly inserted records. This adds write metadata inside the existing powercontext-source-v1 payload, without changing registered tables, schema revisions, frozen migration resources or checksums. Historical envelopes and raw legacy payloads remain readable with unknown save time; replay does not invent a timestamp, and handoff receipt upgrades preserve the original timestamp. Source identity, material digests, journal positions and processing intent identities remain unchanged. This compatibility review does not establish installed-release upgrade acceptance; the upgrade-required policy and complete automatic matrix remain unchanged." + "persistence_sha256": "537eabccaa905b96b566522770409197187e82f3d662795dba8ce7d0d957c46f", + "rationale": "Topic Memory processing failures attach bounded, content-free stage, reason and budget diagnostics to in-flight exceptions. Rejected reservations retain their existing durable charges; readback omits token-specific fields unless committed evidence establishes the limiting dimension, and repeated rejected calls cannot reinterpret prior evidence. Source structure and history-count guards do not imply context overflow. Missing FTS capability is configuration, and incomplete vector projections are business validation. No database schema, migration resource, registered table layout, frozen revision checksum, row encoding, persisted journal format or worker retry behavior is changed by these diagnostic annotations. The reusable Server migration framework registers actual PowerContext 1.3.0 through s1300 -> s1400 -> s1401 -> s1402 and actual 1.4.0 through the separate immutable r1400 -> s1400 -> s1401 -> s1402 source bridge. Original 1.3 resources and checksums remain byte-identical. Real 1.4.0 SQLite, embedded seekDB and OceanBase structures were captured from the official wheel in all twelve vector/Code configurations; provenance and exact source layouts are packaged with the bridge. The 1.4 bridge preserves current Candidate, Artifact and task data, adds the missing Topic budget/block structure, revokes old lease fences and joins the existing archive/portable-storage path. Empty retained tables align the final schema without inventing 1.3 Candidate history. Source histories retain their identity through subsequent upgrades and recovery; shared head names never authorize adopting unknown layouts. Vector profiles remain bound to historical model, profile ID, dimension, unit normalization and L2 distance, with no provider calls during maintenance. Complete schema, domain, projection, profile and retained-history checks precede startup and partial maintenance. Local SQLite and embedded seekDB startup reject an observable active maintenance lock through a read-only probe. SQLite runtime admission validates the default adjacent journal, rejecting unfinished full or partial maintenance, changed recorded revision checksums and missing required retained tables. Absent journals do not invent retention obligations; custom evidence directories require explicit operator verification and remote coordinator locks remain subject to deployment orchestration. Native read-only readiness uses a consistent snapshot and does not acquire Atomic Memory head locks; normal business transaction isolation is unchanged. Offline projection repairs retain the original locked state comparison and write-side CAS protection. Target locks, backup choices, original recovery evidence and explicit remote acknowledgments remain enforced. The installed-artifact catalog retains twelve 1.3.0 source/backend/vector/Code combinations. Embedded seekDB uses pylibseekdb 1.4.0.post2 or newer with the recovered-transaction lock fix. Main and publication require all twelve configurations, including embedded seekDB full-server-code and full-server-vector-code. No configuration is waived; incomplete, failed or skipped evidence rejects acceptance. The seekdb-code diagnostic selection cannot authorize publication. The registered 1.4.0 bridge remains implemented but is outside the CI upgrade acceptance matrix; passing this gate does not certify that path. The gate preserves source-specific Processing counters and isolates OceanBase source databases. Any failed, skipped or missing automatic case rejects publication. The policy remains upgrade-required until the exact target artifact passes the required automatic matrix and the reviewed support declaration is updated. Captured source structure, local tests and checkpoint replay are distinct from installed-release acceptance, native interruption/observer recovery and backup restoration. The Candidate generation prototype observes actual SQLite/seekDB/OceanBase migration checkpoints outside the production bundle; it does not replace frozen registrations or weaken recovery checks. Existing target schema and data formats, including batched persistence interfaces, remain governed by the shared registered path. The synchronized master adds blank-text validation at Source creation and managed worker logging. It changes neither registered table layout nor migration data encodings; existing stored Source values are not rewritten. The source bridges and frozen history remain unchanged. Compatibility commands identify Server-owned storage before opening a writable legacy profile and delegate source admission to the shared framework, including actual 1.4.0 and rejection of unknown layouts. Partial Processing and Atomic Memory projection maintenance verify the original recorded revision checksums; native admission also validates typed journal identity and its completed position against the database revision. Persisted vector profiles reject unsupported partial maintenance before plans, backups or operation evidence, including when the supplied configuration omits embeddings. These are admission-only changes; frozen migration resources, registered layouts, historical checksums and data transformations remain unchanged. PowerContext 1.4.1 assigns release-based presentation names v1_4_1_001 through v1_4_1_003 to the existing shared upgrade steps; the 1.3.0 and 1.4.0 source baselines remain independently registered. Existing revision IDs, bundle and revision checksums, accepted plan identities and journal schemas are unchanged. New Server revisions use software-version-plus-sequence names directly; software releases without storage changes may reuse the same database revision. Naming does not grant acceptance or replace source registration. Full Server status, plan, apply and verify reject unfinished Processing configuration and Atomic Memory projection journals through the same typed admission check used by partial maintenance and SQLite startup. The owning domain runner can still resume its own journal. This only changes admission; frozen revisions, journal formats, database layouts and data transformations remain unchanged. Revision v1_4_1_004 registers the pc_access_owner_recovery outbox on the shared Server chain for both installed-release sources and all registered vector/Code profiles. It creates an empty table through explicit maintenance for existing managed databases and through the registered bootstrap for fresh databases. Earlier revision resources, fingerprints, checksums and existing domain row encodings remain unchanged. External relationship writers use version-1 Artifact and Candidate intents committed with domain data; replay retains the original deployment, principal, resource or target, and idempotency identity. Stable operation and audit event identities prevent lost acknowledgements from duplicating ownership or audit. Conflicting intents are rejected and unknown historical ownership is not inferred. Unregistered outbox layouts are not adopted merely from a table name. This registration does not establish installed-release or external-Provider upgrade acceptance. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Database selection now defaults to powercontext for seekDB and for OceanBase URLs without a database, while explicit database names remain authoritative. An implicit seekDB selection is rejected before initialization when the legacy test database contains pc_ tables; operators can explicitly select database=test to retain those records, and no database is moved or deleted automatically. Bootstrap reuses an accessible selected database without CREATE privilege and creates only a confirmed missing database, with idempotent creation and explicit permission errors. Read-only maintenance on an initialized MySQL-compatible engine requires the selected database and never provisions it; an absent or empty seekDB instance remains a no-engine initial plan. MySQL initialization creates only missing requested tables and indexes, and sorts only those requested tables; existing registered tables are preserved. Code graph connections use the selected database, retain historical graph identities for test, and distinguish other database identities. Server identity initialization avoids redundant MySQL DDL on an existing table. Frozen migration resources, revision identifiers and checksums, registered table definitions, journal formats, and existing row encodings are unchanged. These runtime selection and admission changes do not establish an accepted upgrade path; the policy remains upgrade-required and the installed-release acceptance gate still applies. MySQL recovery rejects different registered table sets before normalization. Backend-default normalization copies only the column and index maps it changes and compares each table without cloning whole inventories. Admitted layouts, registered transitions, recovery checks, schema equality and caller-owned inventories remain preserved. SeekDB status and verify distinguish a missing configured database from an uninitialized engine and denied access. Read-only plan can represent a missing selected database as an uninitialized target without creating it; apply provisions that selected database only after the operator accepts its bound plan, then rechecks the target under the maintenance lock. Installed-release seekDB acceptance explicitly retains the historical test database and separately verifies that omitted selection is refused. Registered schema resources, revision checksums, row encodings and write-side provisioning remain unchanged. Server startup can apply an uninitialized plan to provision a missing selected seekDB database; plan, status and verify still never provision it. OceanBase 4.6 SHOW CREATE TABLE can reflect FTS_INDEX_TYPE=MATCH or PHRASE_MATCH on FULLTEXT indexes. Reflection accepts these known types without changing the logical inventory; unknown values remain rejected and indexed columns, parser identity and token-size properties remain significant. PHRASE_MATCH additionally supports phrase matching; the registered layouts require term matching and do not declare a phrase-only contract. Frozen migration resources, checksums, recovery evidence and persisted layouts remain unchanged. Native 4.6.3.1 DDL was captured from a real installed 1.3.0 database; replay of this fixture does not establish complete native upgrade acceptance. The CI database image and master full automatic upgrade matrix remain unchanged. Revision v1_4_1_005 adds nullable Atomic Memory description projection metadata after the registered owner-recovery revision, through explicit SQLite and MySQL schema transitions for both source chains and all vector/Code profiles. Earlier revision resources, fingerprints and checksums remain unchanged. The additive change neither rewrites authoritative Artifact history nor generates summaries or scans stored bodies. Existing managed databases require explicit migration; existing descriptions remain null until a new write or explicit projection repair copies authoritative metadata. Intermediate projection validation uses only columns available at that revision and still rejects inconsistent existing fields. Unmanaged SDK initialization retains its nullable-column compatibility path. The installed-release acceptance matrix and publication restrictions remain required; local regression checks do not establish native upgrade acceptance. Artifact plugin storage extends the shared Server chain from v1_4_1_006 to v1_5_0_001 with registration columns, family declarations, search state and projections, index coverage and changes, and vector-space/index registrations. SQLite also registers portable vectors and FTS auxiliary structures. Native registration columns are added in one ALTER with a matching recovery checkpoint; final column definitions and constraints are unchanged. Native vector tables are created online from registered spaces and are admitted to later maintenance inventories only after exact layout validation. Historical migration resources, retained objects, and existing data are preserved. This review does not expand the supported upgrade matrix or certify installed-release acceptance. Source write plugin registrations use the additive v1_4_1_006 revision after v1_4_1_005 on both source chains. It creates only pc_source_write_plugins; all earlier master revision scripts, schema resources and checksums remain unchanged. Revision v1_5_0_002 follows v1_5_0_001 and adds retained Source evidence bindings, exact Atomic Memory evidence snapshots and their schema marker on all registered backends. A new versioned domain step verifies retained evidence for lexical and vector profiles; earlier released domain resources and recorded revision checksums remain byte-identical. Existing Sources and Memory revisions without accepted declarations stay neutral, with no trust backfill. Current projection maintenance and rebuild explicitly require evidence validation. This additive registration does not establish installed-release acceptance; the upgrade-required gate and publication restrictions are unchanged. Revision v1_5_0_003 adds the disposable exact-revision pc_atomic_memory_evidence projection through the existing index adapters. Transactional body writes publish it from accepted evidence; scoped portable restore and maintenance rebuild derive it from retained history without current-registry trust backfill or model calls. Domain conformance compares historical and derived values, including neutral legacy declarations, on lexical and vector layouts. Earlier revision resources and fingerprints remain unchanged. Local SQLite recovery and real OceanBase 4.4.2.1 evidence conformance were exercised; these do not certify installed-release upgrades or change publication restrictions. Source evidence maintenance now accepts the deployment's own Source definition registry, reports one bounded neutralization reason through operational logs, batches exact-revision reads and caches retained-schema validation per manifest fingerprint. Indexed repair accepts that registry explicitly; the migration bundle still admits evidence against the builtin registry and says so. These changes alter neither registered table layouts nor retained encodings, and the runtime and Server evidence DDL remain byte-identical. The policy remains upgrade-required with the full automatic matrix and publication restrictions described above. Source definition manifests derive every field whose default is null from the validation schema, so an already accepted Definition keeps its fingerprint and re-registers after upgrade; populating such a field requires the nested model to serialize by alias. Registered layouts and retained encodings are unchanged. The runtime MySQL-family table fast path now runs the registered additive evidence migration before creating other tables, so an unmanaged OceanBase or seekDB database cannot retain evidence tables without their p0005 marker.. Code publication recovery adds an optional per-binding publication.json journal that records a generation identifier before its database commit and final directory rename. Caches created before this journal existed remain readable without synthesizing historical publication records; identifiers for already orphaned rows are not inferred. New seekDB generations retain the existing identifier, graph descriptor, manifest and row encodings, while reclamation validates the recorded identifier and scopes deletion to its binding. Live or reader-retained generation directories and the in-flight publication are protected from journal-window reclamation. SQLite graph rows remain owned by their generation directory. This additive local cache journal changes recovery behavior but does not change registered SQL table layouts, migration resources, revision identifiers, historical checksums or the Server migration journal. The policy remains upgrade-required, and the complete installed-release acceptance matrix remains mandatory; this compatibility review is not evidence of completed native upgrade acceptance. Managed Ops admission validates a private main-file and WAL snapshot through the exact target Server bundle, retaining the original database identity and maintenance evidence. Snapshot admission is read-only and cannot initialize, migrate or recover storage. It adds no schema revision, changes no persisted row or journal format, and does not expand supported upgrade declarations or the installed-release acceptance matrix. PreparedContext Receipt records the actual FTS mode on Experience search outcomes. This adds only an in-memory observation field; it does not change stored Experience rows, SQL selection, schema registrations, migration resources, or data encodings. Unmanaged historical Server databases are admitted by required structure and domain state, then normalized before adopting an existing checkpoint. Historical Memory conversion, Scope preservation, SQLite rollback and native DDL recovery use the shared maintenance flow. Independent extension objects and harmless DDL differences do not require clean-install fingerprints. Existing immutable revision resources and the installed-release acceptance matrix remain unchanged. Local historical tests do not certify arbitrary tenant defaults, every vector/Code configuration or future releases. SQLite compatibility validation includes effective primary-key collations and rejects conflicting identity semantics. Historical normalization and the frozen s1400 rebuild preserve generated extension definitions while copying only writable columns. Both virtual and stored generated values remain computed by SQLite; immutable revision resources and the native backend paths are unchanged. SQLite table rebuilds preserve declared collations on ordinary and generated extension columns, including their inherited index comparison semantics. Expression-local COLLATE clauses remain part of their expressions and do not change the column collation. This changes only SQLite compatibility normalization; frozen revisions and native backend execution remain unchanged. Historical Memory admission recognizes lineage ownership columns and default non-merge references while rejecting unmapped payloads. Native compatibility journals record temporary Processing counter ownership before DDL and clear it after cleanup, including completed-phase recovery. SQLite extension preservation also covers the registered r1400 bridge. Frozen migration resources and the installed-release acceptance matrix remain unchanged. Native historical Atomic conversion creates nullable description metadata with the registered UTF-8 binary collation, allowing the later frozen ADD transition to recognize its completed postcondition without duplicate DDL. SQLite historical normalization and registered source bridges preserve dependent views and their triggers during same-name table replacement. Legacy rename behavior is limited to the exact staging-to-final rename statements and the original connection setting is restored; genuine table renames still update dependent references. Frozen migration resources and native backend behavior remain unchanged. SQLite admission validates required extension defaults using SQLite deterministic-expression restrictions and a non-NULL evaluation on an isolated connection. Connection-state, random and clock-dependent expressions are rejected; direct CURRENT_DATE, CURRENT_TIME and CURRENT_TIMESTAMP defaults remain supported alongside usable constant expressions. Regression coverage verifies consecutive Source writes in distinct scopes within the same transaction. Read-only verification and startup admission share this rule; supported defaults remain usable through Source write and readback. Independent extension tables remain preserved through managed upgrades and initialization recovery; missing recovery evidence and missing vector configuration still block maintenance. Registered native column additions and modifications materialize the charset and collation declared by their immutable postcondition when the SQL would otherwise inherit a historical table default. This preserves GBK-origin upgrade recovery without changing frozen resources, existing table defaults, independent extension encodings or readiness requirements. SQLite Candidate extension columns and their values survive both stages of the registered Dream rebuild, including generated columns and dependent views. Frozen source introspection projects the already-validated managed columns without altering stored extension data. Independent indexes use SQLite-rewritten definitions after genuine table renames. Native CHECK removal resolves the actual constraint name from the registered expression and enforcement semantics, including recovery after committed DDL. Frozen resources, registered revision checksums and the installed-release acceptance matrix remain unchanged. SQLite admission rejects additional NOT NULL generated columns because computed values can reject valid Source writes. Nullable virtual and stored extensions remain preserved across historical upgrades and support Source write/readback. Frozen migrations and native backend behavior are unchanged. Ownership recovery preflight derives candidate-family filters from the exact migration identities, including Prompt Candidates that do not have standalone Artifact owners. Static Scope permission previews now use the same complete internal receipt keys as bootstrap for long Scope IDs. These authorization-only changes add no stored fields, row encoding, schema, or migration registration. Static Scope preset keys retain existing short identities and use SHA-256 for oversized relationship keys. Bootstrap and read-only preview recognize both bounded keys and historical receipts, including revoked bindings. No schema or migration registration changes. Managed observability reads existing Context Bootstrap receipt metadata in authorized Scope batches and aggregates it by integration and receipt state. This adds no schema revision, stored row changes, migration resources, or data encoding changes; receipt identities, historical evidence and the declared upgrade acceptance matrix remain unchanged. SQLite connection failures drain the aiosqlite 0.22.1 worker before propagating the error or cancellation, including failures before pool admission. This connection-lifecycle fix changes no registered schema, historical revision checksum, stored value, or upgrade source policy. Prepared-context reuse proofs revalidate cited code files by reading their current worktree digest through the existing no-follow capture reader and exclusion rules. This adds a read-only lookup; it changes no code index cache layout, manifest, graph rows, publication journal, SQL layout, migration resource or checksum. Revision v1_5_0_004 adds the optional pc_artifact_source_locators relation keyed by the existing Artifact Revision and Source-edge ordinal for both registered source releases and vector/Code profiles. Explicit maintenance creates the empty relation without rewriting historical lineage, payloads, Source identities, earlier revision resources or checksums. Missing locators remain omitted in legacy encodings; located citations survive persistence, HTTP/MCP and portable export/restore, and Source sequence mismatches are rejected without redirecting identity. Atomic Memory content and vector bindings are unchanged, so locator metadata does not require re-embedding. Local SQLite migration, restart, citation and portable round-trip tests pass; MySQL layout checks do not constitute native seekDB/OceanBase or installed-release acceptance. The upgrade-required policy, required automatic matrix and publication restrictions remain unchanged. Projection verification and repair read only the exact authoritative head content and state, avoiding target-only Source locator lineage tables at earlier registered migration checkpoints. Frozen resources and revision checksums remain unchanged. Source locator line-count and heading-path limits are centralized without changing their values, accepted payloads or stored encodings. Gateway authorization adds the Scope-level gateway.user role and gateway.invoke action to the existing binding vocabulary. It does not change stored binding structure or migration resources: existing records retain their role and do not implicitly gain gateway.invoke; new grants use the existing binding persistence and resource validation. Existing upgrade support remains upgrade-required and is not certified by this digest refresh. OceanBase Atomic Memory lexical retrieval uses native MATCH with minimum_should_match and SCORE when a controlled capability probe confirms support, and retains the existing MATCH AGAINST plus complete-word coverage path for unsupported backends. Capability decisions are held only in memory per connection pool. Search, complete related enumeration and recovery preserve Analyzer term deduplication, coverage thresholds, scope and content filters, vector completeness checks, same-statement authority heads and the existing oceanbase_match raw-score contract. This query-only change adds no tables, public interfaces, schema revisions, stored fields or row encodings; existing SPACE index definitions, projection formats, historical migration resources and revision checksums remain unchanged. No schema migration or projection rebuild is required for this query implementation. The upgrade-required policy, registered sources and complete installed-release acceptance matrix remain unchanged; this review does not certify installed-release upgrades. Queries above 256 distinct terms retain whole-word coverage unless the engine is identified as OceanBase 4.6 or newer, because earlier native engines can accept MATCH while ignoring that threshold. This compatibility guard changes query selection only. Native capability caching obtains the pool through run_sync, including pinned historical migration connections, without acquiring another connection or releasing maintenance locks. Queries containing SPACE stopwords retain Analyzer-based whole-word admission in all lexical operations. These corrections change neither stored projections nor registered schema resources. SQLite Topic Memory full-text helper version 2 assigns each Scope's helper rows to a hashed 2^32-rowid range above every rowid that version 1 assigned, so Topic replacement and search bound their FTS5 cursors to one Scope's range. Virtual table definitions, registered schema fingerprints, migration resources and authoritative active Topic rows are unchanged. Unmanaged initialization and the existing s1400 domain step rebuild version-1 helper rows from the active tables with exact identities and revisions; a managed database that still holds version-1 helper rows keeps the previous identity filters until the helper is rebuilt. bm25 statistics remain table-wide, so search hits, ordering and scores are unchanged. The standalone seekdb maintenance identity is derived from @@server_uuid and DATABASE() when ob_compatibility_mode is missing, NULL, or empty and VERSION() contains -OceanBase seekdb-. The db-migrate identity probe and the server-run tenant gate share one compatibility classifier; ORACLE and non-seekdb servers remain rejected. This is an admission-only change and does not alter registered table layouts, migration resources, persisted row encodings, or public interfaces. Source writes and text retrieval reuse parameterized SQL structures with fresh Scope, identity, revision, binding and increment values on every execution. Only the fixed built-in Content manifest construction and exact validated payload bytes reuse cached metadata; database registration and indexed-identity checks remain current, and callers receive deep copies. MySQL/OceanBase journal allocation retains SELECT FOR UPDATE; SQLite retains its write reservation. Concurrent Content captures coalesce already queued requests into bounded transactions, isolate individual failures after batch rollback, replay stable identities on cancellation and drain admitted callers during shutdown. No schema, migration, stored encoding, Source identity, journal ordering, processing counter semantics or upgrade support claims change. A Topic Memory window attempt whose publication loses the Topic head CAS to a concurrent replace or Dream records last_error_code head_conflict on its existing pc_topic_memory_work_budgets row, and the attempt ceiling and the next attempt's counter treat that one attempt as not spent. Provider request and token charges stay committed and are never refunded. No table layout, column, constraint, migration resource, revision checksum or row encoding changes; existing rows never carry head_conflict, so their counters and blocks keep their meaning. A binary without this change counts such an attempt as spent, which can only stop that frontier sooner. The Dashboard processing page reads the existing Source journal and Artifact lineage relation and marks only Sources with an exact Artifact citation. It introduces no new table or public JSON interface and does not reconstruct execution history, delivery or adoption. Source journal envelopes record an optional UTC saved_at timestamp for newly inserted records. This adds write metadata inside the existing powercontext-source-v1 payload, without changing registered tables, schema revisions, frozen migration resources or checksums. Historical envelopes and raw legacy payloads remain readable with unknown save time; replay does not invent a timestamp, and handoff receipt upgrades preserve the original timestamp. Source identity, material digests, journal positions and processing intent identities remain unchanged. This compatibility review does not establish installed-release upgrade acceptance; the upgrade-required policy and complete automatic matrix remain unchanged. Relocating access control from the Server package to the built-in runtime, removing the unused Source-cursor discovery query, and moving the code command out of the built-in Code package are code-organization changes. They change neither registered table layout nor migration data encodings: the generated table and index DDL for every persistence and access table is identical on the SQLite and MySQL dialects." }, "cases": [], "automatic_sources": { diff --git a/scripts/dashboard_multiday.py b/scripts/dashboard_multiday.py index a178dda69b..f9b5f55c4c 100644 --- a/scripts/dashboard_multiday.py +++ b/scripts/dashboard_multiday.py @@ -131,7 +131,7 @@ def replay(arguments: argparse.Namespace) -> None: } # Restart the Server each day to verify persistence across process lifecycles. with time_machine.travel(date, tick=True): - app = create_server_app(settings=settings, scheduler_path=output / "scheduler.db") + app = create_server_app(settings=settings) with TestClient(app, raise_server_exceptions=False) as client: client.headers["Authorization"] = f"Bearer {token}" default = call(client, directory, "server-default", "GET", "/v1/scopes/default") diff --git a/scripts/upgrade_release_gate.py b/scripts/upgrade_release_gate.py index fc72f6792c..c9d91dd8a5 100644 --- a/scripts/upgrade_release_gate.py +++ b/scripts/upgrade_release_gate.py @@ -43,7 +43,7 @@ "src/powercontext/builtin/persistence", "src/powercontext/builtin/code", "src/powercontext/server/identity.py", - "src/powercontext/server/authz", + "src/powercontext/builtin/authz", "src/powercontext/limits.py", ) PHASES = frozenset({ diff --git a/src/powercontext/server/authz/__init__.py b/src/powercontext/builtin/authz/__init__.py similarity index 85% rename from src/powercontext/server/authz/__init__.py rename to src/powercontext/builtin/authz/__init__.py index e4d7784499..16b4044b3d 100644 --- a/src/powercontext/server/authz/__init__.py +++ b/src/powercontext/builtin/authz/__init__.py @@ -12,11 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Server-owned authentication and authorization building blocks.""" +"""Authorization building blocks shared by the built-in Runtime and the Server.""" from typing import TYPE_CHECKING -from powercontext.server.authz.errors import ( +from powercontext.builtin.authz.errors import ( AccessBindingNotFoundError, AccessConflictError, AccessControlError, @@ -25,8 +25,8 @@ AccessInvalidRequestError, AccessUnavailableError, ) -from powercontext.server.authz.keys import IDEMPOTENCY_KEY_LIMIT, bounded_idempotency_key -from powercontext.server.authz.models import ( +from powercontext.builtin.authz.keys import IDEMPOTENCY_KEY_LIMIT, bounded_idempotency_key +from powercontext.builtin.authz.models import ( DEFAULT_DEPLOYMENT_ID, PUBLIC_ACCESS_ACTIONS, ROLE_CARDINALITIES, @@ -48,7 +48,7 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.service import ( +from powercontext.builtin.authz.service import ( AccessAuditContext, AccessAuditPage, AccessAuditStore, @@ -74,18 +74,18 @@ ) if TYPE_CHECKING: - from powercontext.server.authz.authzen import AuthZenAuthorizationProvider - from powercontext.server.authz.casbin import CasbinAuthorizationProvider + from powercontext.builtin.authz.authzen import AuthZenAuthorizationProvider + from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider def __getattr__(name: str) -> object: # Runtime consumers use the shared Access contract without selecting a Server provider. if name == "AuthZenAuthorizationProvider": - from powercontext.server.authz.authzen import AuthZenAuthorizationProvider + from powercontext.builtin.authz.authzen import AuthZenAuthorizationProvider return AuthZenAuthorizationProvider if name == "CasbinAuthorizationProvider": - from powercontext.server.authz.casbin import CasbinAuthorizationProvider + from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider return CasbinAuthorizationProvider message = f"module {__name__!r} has no attribute {name!r}" diff --git a/src/powercontext/server/authz/authzen.py b/src/powercontext/builtin/authz/authzen.py similarity index 96% rename from src/powercontext/server/authz/authzen.py rename to src/powercontext/builtin/authz/authzen.py index 1cdaf1a95e..7c4937f9e3 100644 --- a/src/powercontext/server/authz/authzen.py +++ b/src/powercontext/builtin/authz/authzen.py @@ -22,14 +22,14 @@ import httpx from pydantic import SecretStr -from powercontext.limits import MAX_POLICY_REVISION_LENGTH -from powercontext.server.authz.errors import AccessUnavailableError -from powercontext.server.authz.models import AccessDecision, AccessSubjectRef, MemoryEntrySelector, ResourceRef -from powercontext.server.authz.service import ( +from powercontext.builtin.authz.errors import AccessUnavailableError +from powercontext.builtin.authz.models import AccessDecision, AccessSubjectRef, MemoryEntrySelector, ResourceRef +from powercontext.builtin.authz.service import ( AccessRequest, AuthorizedResourceFilter, ResourceSearchRequest, ) +from powercontext.limits import MAX_POLICY_REVISION_LENGTH from powercontext.transport import is_plaintext_non_loopback _EVALUATION_PATH = "/access/v1/evaluation" diff --git a/src/powercontext/server/authz/casbin.py b/src/powercontext/builtin/authz/casbin.py similarity index 98% rename from src/powercontext/server/authz/casbin.py rename to src/powercontext/builtin/authz/casbin.py index 0afbf53079..7ec4a3a393 100644 --- a/src/powercontext/server/authz/casbin.py +++ b/src/powercontext/builtin/authz/casbin.py @@ -21,8 +21,8 @@ import casbin -from powercontext.server.authz.errors import AccessInvalidRequestError -from powercontext.server.authz.models import ( +from powercontext.builtin.authz.errors import AccessInvalidRequestError +from powercontext.builtin.authz.models import ( DEFAULT_DEPLOYMENT_ID, ROLE_ACTIONS, ROLE_CHILD_ACTIONS, @@ -35,7 +35,7 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.service import ( +from powercontext.builtin.authz.service import ( AccessRepository, AccessRequest, AuthorizedResourceFilter, diff --git a/src/powercontext/server/authz/composition.py b/src/powercontext/builtin/authz/composition.py similarity index 95% rename from src/powercontext/server/authz/composition.py rename to src/powercontext/builtin/authz/composition.py index 8db3da30f5..cba7e18f0f 100644 --- a/src/powercontext/server/authz/composition.py +++ b/src/powercontext/builtin/authz/composition.py @@ -21,13 +21,8 @@ from datetime import UTC, datetime from uuid import uuid4 -from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile -from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile -from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.builtin.runtime.composition import BuiltinConfigurationError -from powercontext.builtin.runtime.config import DatabaseConfig -from powercontext.server.authz.casbin import CasbinAuthorizationProvider -from powercontext.server.authz.models import ( +from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider +from powercontext.builtin.authz.models import ( DEFAULT_DEPLOYMENT_ID, AccessBinding, AccessBindingState, @@ -35,12 +30,17 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository -from powercontext.server.authz.service import ( +from powercontext.builtin.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.authz.service import ( AccessControlService, AccessProviderCapabilities, BuiltinAuthorizationProvider, ) +from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile +from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.runtime.composition import BuiltinConfigurationError +from powercontext.builtin.runtime.config import DatabaseConfig @asynccontextmanager diff --git a/src/powercontext/builtin/authz/dream.py b/src/powercontext/builtin/authz/dream.py new file mode 100644 index 0000000000..6eeba8278d --- /dev/null +++ b/src/powercontext/builtin/authz/dream.py @@ -0,0 +1,137 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Authorize Dream evidence and Candidate ownership against Access Control.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.artifacts import ArtifactRef +from powercontext.builtin.authz.errors import AccessControlError, AccessDeniedError +from powercontext.builtin.authz.models import AccessAction, PrincipalRef, ResourceRef +from powercontext.builtin.authz.service import AccessAuditContext, AccessControlService +from powercontext.builtin.dream.models import DreamError + +if TYPE_CHECKING: + # Annotation-only: importing the Dream service here would load the Runtime package. + from powercontext.builtin.dream.models import DreamRecord + from powercontext.builtin.dream.service import DreamPermission + from powercontext.builtin.evidence.resolver import EvidenceReference + + +def principal_identity(principal: PrincipalRef) -> str: + return json.dumps({"type": principal.type, "id": principal.id}, ensure_ascii=False, separators=(",", ":")) + + +def _principal(identity: str) -> PrincipalRef: + try: + value = json.loads(identity) + except (ValueError, TypeError) as error: + raise DreamError("access_revoked") from error + if not isinstance(value, dict) or set(value) != {"type", "id"}: + raise DreamError("access_revoked") + try: + return PrincipalRef(type=value["type"], id=value["id"]) + except (ValueError, TypeError, AccessControlError) as error: + raise DreamError("access_revoked") from error + + +def evidence_resource(scope_id: str, ref: EvidenceReference | None) -> ResourceRef: + if isinstance(ref, ArtifactRef) and ref.family != "topic-memory": + return ResourceRef.artifact(scope_id, family=ref.family, artifact_id=ref.artifact_id) + # Sources and Topic Memory reads belong to the Scope. + return ResourceRef.scope(scope_id) + + +class DreamAuthorization: + """Check a recorded Dream principal; background work carries no request identity.""" + + def __init__(self, access: AccessControlService) -> None: + self.access = access + + def _request_id(self) -> str | None: + return None + + async def authorize( + self, + scope_id: str, + principal_id: str, + permission: DreamPermission, + ref: EvidenceReference | None, + ) -> None: + principal = _principal(principal_id) + resource = evidence_resource(scope_id, ref) + if permission == "contribute": + action = AccessAction.SCOPE_CONTRIBUTE + elif permission in {"write", "write_tags"}: + if isinstance(ref, ArtifactRef) and ref.family in {"prompt", "topic-memory"}: + action, resource = AccessAction.SCOPE_ADMIN, ResourceRef.scope(scope_id) + else: + action = AccessAction.ARTIFACT_WRITE + else: + action = AccessAction.SCOPE_READ if resource == ResourceRef.scope(scope_id) else AccessAction.ARTIFACT_READ + try: + await self.access.require( + principal, + action, + resource, + context=AccessAuditContext( + request_id=self._request_id(), + transport="background", + operation="artifact_dreaming", + ), + ) + except AccessDeniedError as error: + raise DreamError("access_revoked") from error + except AccessControlError as error: + raise DreamError("access_unavailable") from error + + async def attest_candidate( + self, connection: AsyncConnection, record: DreamRecord, candidate_id: str, family: str + ) -> None: + bound = type(self)(self.access.with_connection(connection)) + await bound.authorize(record.run.scope_id, record.principal_id, "contribute", None) + await bound.access.attest_candidate_owner( + scope_id=record.run.scope_id, + candidate_id=candidate_id, + family=family, + proposed_owner=_principal(record.principal_id), + target=None + if record.run.target is None + else ResourceRef.artifact( + record.run.scope_id, family=record.run.target.family, artifact_id=record.run.target.artifact_id + ), + idempotency_key=f"dream-candidate-owner:{record.run.run_id}", + ) + + async def authorize_candidate( + self, connection: AsyncConnection, record: DreamRecord, candidate_id: str, family: str + ) -> None: + bound = type(self)(self.access.with_connection(connection)) + await bound.authorize(record.run.scope_id, record.principal_id, "read", record.run.target) + if record.run.operation == "revise_tags" and record.run.tag_target is not None: + await bound.authorize( + record.run.scope_id, + record.principal_id, + "read", + record.run.tag_target.basis_ref, + ) + return + owner = await bound.access.candidate_owner(record.run.scope_id, candidate_id) + if owner is None or owner.proposed_owner != _principal(record.principal_id): + raise DreamError("access_revoked") diff --git a/src/powercontext/server/authz/errors.py b/src/powercontext/builtin/authz/errors.py similarity index 98% rename from src/powercontext/server/authz/errors.py rename to src/powercontext/builtin/authz/errors.py index e87bf81e31..281cbee431 100644 --- a/src/powercontext/server/authz/errors.py +++ b/src/powercontext/builtin/authz/errors.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Stable failures owned by the Server Access Control boundary.""" +"""Stable failures owned by the Access Control boundary.""" from powercontext.errors import PowerContextError diff --git a/src/powercontext/server/authz/keys.py b/src/powercontext/builtin/authz/keys.py similarity index 100% rename from src/powercontext/server/authz/keys.py rename to src/powercontext/builtin/authz/keys.py diff --git a/src/powercontext/server/authz/models.py b/src/powercontext/builtin/authz/models.py similarity index 99% rename from src/powercontext/server/authz/models.py rename to src/powercontext/builtin/authz/models.py index aa0f5f3d71..0bc8042c6b 100644 --- a/src/powercontext/server/authz/models.py +++ b/src/powercontext/builtin/authz/models.py @@ -22,7 +22,7 @@ from enum import StrEnum from typing import TypeAlias -from powercontext.server.authz.errors import AccessInvalidRequestError +from powercontext.builtin.authz.errors import AccessInvalidRequestError DEFAULT_DEPLOYMENT_ID = "powercontext" diff --git a/src/powercontext/server/authz/owner_recovery.py b/src/powercontext/builtin/authz/owner_recovery.py similarity index 99% rename from src/powercontext/server/authz/owner_recovery.py rename to src/powercontext/builtin/authz/owner_recovery.py index 757757d54e..29765c9742 100644 --- a/src/powercontext/server/authz/owner_recovery.py +++ b/src/powercontext/builtin/authz/owner_recovery.py @@ -33,14 +33,12 @@ from sqlalchemy.ext.asyncio import AsyncConnection from sqlalchemy.schema import CreateTable -from powercontext.builtin.persistence.database import AsyncDatabase -from powercontext.builtin.persistence.tables import ARTIFACT_HEADS_TABLE, CANDIDATE_HEADS_TABLE, identity_string -from powercontext.server.authz.errors import ( +from powercontext.builtin.authz.errors import ( AccessConflictError, AccessInvalidRequestError, AccessUnavailableError, ) -from powercontext.server.authz.models import ( +from powercontext.builtin.authz.models import ( AccessAction, AccessAuditEvent, AccessResourceType, @@ -50,14 +48,16 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.profiles import ARTIFACT_FAMILY_PROFILES -from powercontext.server.authz.service import ( +from powercontext.builtin.authz.profiles import ARTIFACT_FAMILY_PROFILES +from powercontext.builtin.authz.service import ( AccessAuditContext, AccessControlService, IdempotentAccessAuditStore, _access_call, _validate_idempotency_key, ) +from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.tables import ARTIFACT_HEADS_TABLE, CANDIDATE_HEADS_TABLE, identity_string _METADATA = MetaData() OWNER_RECOVERY_TABLE = Table( diff --git a/src/powercontext/server/authz/profiles.py b/src/powercontext/builtin/authz/profiles.py similarity index 98% rename from src/powercontext/server/authz/profiles.py rename to src/powercontext/builtin/authz/profiles.py index ccd5d63de0..84623fd972 100644 --- a/src/powercontext/server/authz/profiles.py +++ b/src/powercontext/builtin/authz/profiles.py @@ -12,15 +12,15 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Server-owned Artifact Family Access Profiles.""" +"""Built-in Artifact Family Access Profiles.""" from __future__ import annotations from dataclasses import dataclass from typing import Literal -from powercontext.server.authz.errors import AccessInvalidRequestError -from powercontext.server.authz.models import ( +from powercontext.builtin.authz.errors import AccessInvalidRequestError +from powercontext.builtin.authz.models import ( ROLE_SUBJECT_TYPES, AccessAction, AccessResourceType, diff --git a/src/powercontext/server/authz/repository.py b/src/powercontext/builtin/authz/repository.py similarity index 99% rename from src/powercontext/server/authz/repository.py rename to src/powercontext/builtin/authz/repository.py index 0f21160fd0..04c09113c9 100644 --- a/src/powercontext/server/authz/repository.py +++ b/src/powercontext/builtin/authz/repository.py @@ -47,16 +47,8 @@ from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.asyncio import AsyncConnection -from powercontext.builtin.persistence.database import SELECTION_BATCH_SIZE, AsyncDatabase -from powercontext.builtin.persistence.tables import identity_string -from powercontext.limits import ( - MAX_ARTIFACT_FAMILY_LENGTH, - MAX_ARTIFACT_ID_LENGTH, - MAX_POLICY_REVISION_LENGTH, - MAX_SCOPE_ID_LENGTH, -) -from powercontext.server.authz.errors import AccessConflictError, AccessInvalidRequestError, AccessUnavailableError -from powercontext.server.authz.models import ( +from powercontext.builtin.authz.errors import AccessConflictError, AccessInvalidRequestError, AccessUnavailableError +from powercontext.builtin.authz.models import ( ROLE_CARDINALITIES, AccessAction, AccessAuditEvent, @@ -74,12 +66,20 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.service import ( +from powercontext.builtin.authz.service import ( BindingReplacement, BindingSearchRequest, DecisionState, ReplaceBinding, ) +from powercontext.builtin.persistence.database import SELECTION_BATCH_SIZE, AsyncDatabase +from powercontext.builtin.persistence.tables import identity_string +from powercontext.limits import ( + MAX_ARTIFACT_FAMILY_LENGTH, + MAX_ARTIFACT_ID_LENGTH, + MAX_POLICY_REVISION_LENGTH, + MAX_SCOPE_ID_LENGTH, +) ACCESS_METADATA = MetaData() diff --git a/src/powercontext/server/authz/service.py b/src/powercontext/builtin/authz/service.py similarity index 97% rename from src/powercontext/server/authz/service.py rename to src/powercontext/builtin/authz/service.py index 5a6b0a3f5e..09b3407d27 100644 --- a/src/powercontext/server/authz/service.py +++ b/src/powercontext/builtin/authz/service.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Authorization Provider SPI and Server-owned Access use cases.""" +"""Authorization Provider SPI and Access Control use cases.""" from __future__ import annotations @@ -33,8 +33,7 @@ from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine -from powercontext.limits import MAX_POLICY_REVISION_LENGTH -from powercontext.server.authz.errors import ( +from powercontext.builtin.authz.errors import ( AccessBindingNotFoundError, AccessConflictError, AccessControlError, @@ -43,7 +42,7 @@ AccessInvalidRequestError, AccessUnavailableError, ) -from powercontext.server.authz.models import ( +from powercontext.builtin.authz.models import ( DEFAULT_DEPLOYMENT_ID, ROLE_ACTIONS, ROLE_CHILD_ACTIONS, @@ -62,16 +61,17 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.profiles import ( +from powercontext.builtin.authz.profiles import ( ARTIFACT_FAMILY_PROFILES, artifact_family_profile, validate_action_resource, validate_binding_role, validate_binding_subject, ) +from powercontext.limits import MAX_POLICY_REVISION_LENGTH if TYPE_CHECKING: - from powercontext.server.authz.casbin import CasbinAuthorizationProvider + from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider _T = TypeVar("_T") @@ -433,7 +433,7 @@ async def read_decision_state( comparison in the decision. """ - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository native = type(repository) is RelationalAccessRepository options = {"binding_resources": binding_resources} if native else {} @@ -671,7 +671,7 @@ async def point_decision_batch( self, principal: PrincipalRef | None, *, context: AccessAuditContext ) -> AsyncIterator[None]: """Reuse canonical local policy inputs while a single generation attempt prepares work.""" - from powercontext.server.authz.casbin import CasbinAuthorizationProvider + from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider actor = _required_principal(principal) provider = self.provider @@ -700,8 +700,8 @@ async def prefetch_point_decisions( An observed revision can reuse only a complete matching batch. False asks the caller to retry under a pinned snapshot, without admitting any inputs. """ - from powercontext.server.authz.casbin import CasbinAuthorizationProvider - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider + from powercontext.builtin.authz.repository import RelationalAccessRepository provider = self.provider repository = getattr(provider, "_repository", None) @@ -763,8 +763,8 @@ async def prefetch_point_decisions( def with_connection(self, connection): """Bind relationships, builtin authorization reads, and audit to a transaction.""" - from powercontext.server.authz.casbin import CasbinAuthorizationProvider - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider + from powercontext.builtin.authz.repository import RelationalAccessRepository if not isinstance(self.relationships, RelationalAccessRepository) or self.audit is not self.relationships: raise AccessUnavailableError("transactional_relationships_unavailable") @@ -786,12 +786,12 @@ def with_connection(self, connection): def supports_read_snapshot(self, engine: AsyncEngine) -> bool: """Whether binding local policy to this engine preserves the Provider's rules.""" - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository provider = self.provider canonical = type(provider) is BuiltinAuthorizationProvider - if not canonical and type(provider).__module__ == "powercontext.server.authz.casbin": - from powercontext.server.authz.casbin import CasbinAuthorizationProvider + if not canonical and type(provider).__module__ == "powercontext.builtin.authz.casbin": + from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider canonical = type(provider) is CasbinAuthorizationProvider if not canonical: @@ -808,7 +808,7 @@ def supports_read_snapshot(self, engine: AsyncEngine) -> bool: def supports_write_transaction(self, engine: AsyncEngine) -> bool: """Whether owner relations and audit can join this business database.""" - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository if type(self.relationships) is not RelationalAccessRepository or self.audit is not self.relationships: return False @@ -821,7 +821,7 @@ def supports_write_transaction(self, engine: AsyncEngine) -> bool: def for_read(self, connection: AsyncConnection) -> AccessControlService: """Use a local policy snapshot when available, preserving external point decisions.""" - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository if not self.supports_read_snapshot(connection.engine): return self @@ -840,7 +840,7 @@ async def require_scope_read(self, principal, scope_id: str, *, connection, cont async def bootstrap_subject_scope(self, connection, principal, scope_id, *, context): """Grant only a newly created ordinary Scope, in the Source transaction.""" - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository if not isinstance(self.relationships, RelationalAccessRepository): raise AccessUnavailableError("transactional_relationships_unavailable") @@ -915,8 +915,8 @@ async def static_scope_bootstrap_would_grant( """ if not self.can_bootstrap_static_scope(principal, action, resource): return False - from powercontext.server.authz.casbin import CasbinAuthorizationProvider - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider + from powercontext.builtin.authz.repository import RelationalAccessRepository repository = self.relationships if type(repository) is not RelationalAccessRepository or type(self.provider) not in { @@ -948,7 +948,7 @@ async def bootstrap_static_scope( actor = _required_principal(principal) if self._static_scope_principal is None or actor != self._static_scope_principal: return - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository resource = ResourceRef.scope(scope_id) keys = tuple( @@ -1303,7 +1303,7 @@ async def establish_artifact_owners( context: AccessAuditContext, ) -> tuple[ArtifactOwnerRelation, ...]: """Establish an independent local owner set, retaining each relation and audit.""" - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository if not resources: return () @@ -1366,7 +1366,7 @@ async def attest_candidate_owners( self, attestations: Sequence[CandidateOwnerAttestation] ) -> tuple[CandidateOwnerAttestation, ...]: """Persist one independent candidate window under the configured relationship store.""" - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository if not attestations: return () @@ -1382,7 +1382,7 @@ async def candidate_owner(self, scope_id: str, candidate_id: str) -> CandidateOw async def candidate_owners(self, scope_id, candidate_ids): """Read persisted owner attestations without deriving ownership from grants.""" - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository repository = self._relationship_reader() if type(repository) is RelationalAccessRepository: @@ -1564,7 +1564,7 @@ async def defer_decision_audit(self) -> AsyncIterator[None]: yield finally: self._deferred_decisions.reset(token) - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository if type(self.audit) is RelationalAccessRepository: await _access_call(self.audit.append_audits(events)) diff --git a/src/powercontext/builtin/authz/worker.py b/src/powercontext/builtin/authz/worker.py new file mode 100644 index 0000000000..ab1e1d81a6 --- /dev/null +++ b/src/powercontext/builtin/authz/worker.py @@ -0,0 +1,153 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Reconstruct the Server's authorization inside a processing child. + +Runtime-only SDK users do not import or require this adapter. The serialized +identity is resolved from trusted deployment settings, never from model output. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator, Sequence +from contextlib import asynccontextmanager +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field +from sqlalchemy.ext.asyncio import AsyncConnection + +from powercontext.builtin.authz.keys import bounded_idempotency_key +from powercontext.builtin.authz.models import AccessAction, CandidateOwnerAttestation, PrincipalRef, ResourceRef +from powercontext.builtin.authz.repository import RelationalAccessRepository +from powercontext.builtin.authz.service import AccessAuditContext, AccessControlService, BuiltinAuthorizationProvider +from powercontext.builtin.persistence.database import AsyncDatabase + + +class WorkerSecuritySpec(BaseModel): + model_config = ConfigDict(extra="forbid") + + provider: Literal["builtin"] = "builtin" + principal: PrincipalRef = Field(repr=False) + deployment_id: str + static_preset: bool = False + + +class WorkerSecurity: + def __init__(self, access: AccessControlService, principal: PrincipalRef) -> None: + self.access = access + self.principal = principal + self.context = AccessAuditContext(transport="background", operation="artifact_processing") + + async def authorize_scope(self, scope_id: str) -> None: + await self._authorize_scope(self.access, scope_id) + + async def _authorize_scope(self, access: AccessControlService, scope_id: str) -> None: + await access.bootstrap_static_scope(self.principal, scope_id, context=self.context) + await access.require( + self.principal, AccessAction.SCOPE_CONTRIBUTE, ResourceRef.scope(scope_id), context=self.context + ) + + async def authorize_transaction(self, connection: AsyncConnection, scope_id: str) -> None: + await self._authorize_scope(self.access.with_connection(connection), scope_id) + + async def experience_commit(self, connection: AsyncConnection, candidates: Sequence[Any], *, scope_id: str) -> None: + bound = self.access.with_connection(connection) + await bound.attest_candidate_owners( + tuple( + CandidateOwnerAttestation( + scope_id=scope_id, + candidate_id=candidate.candidate_id, + family="experience", + proposed_owner=self.principal, + target=None, + idempotency_key=bounded_idempotency_key( + "background-candidate-owner", scope_id, candidate.candidate_id + ), + ) + for candidate in candidates + ) + ) + + async def authorize_profile(self, scope_id: str, current: Any) -> None: + if current is not None: + await self.access.require( + self.principal, + AccessAction.ARTIFACT_WRITE, + ResourceRef.artifact(scope_id, family="profile", artifact_id="profile"), + context=self.context, + ) + + async def authorize_profile_commit(self, connection: AsyncConnection, current: Any, *, scope_id: str) -> None: + if current is not None: + await self.access.with_connection(connection).require( + self.principal, + AccessAction.ARTIFACT_WRITE, + ResourceRef.artifact(scope_id, family="profile", artifact_id="profile"), + context=self.context, + ) + + async def profile_commit( + self, connection: AsyncConnection, artifact: Any, candidate: Any, *, scope_id: str + ) -> None: + bound = self.access.with_connection(connection) + resource = ResourceRef.artifact(scope_id, family="profile", artifact_id="profile") + if artifact is not None: + if await bound.artifact_owner(resource) is None: + await bound.establish_artifact_owner( + resource, + self.principal, + idempotency_key=bounded_idempotency_key("profile-owner", scope_id), + context=self.context, + ) + else: + await bound.require(self.principal, AccessAction.ARTIFACT_WRITE, resource, context=self.context) + if candidate is not None: + if candidate.target is not None: + await bound.require(self.principal, AccessAction.ARTIFACT_WRITE, resource, context=self.context) + await bound.attest_candidate_owner( + scope_id=scope_id, + candidate_id=candidate.candidate_id, + family="profile", + proposed_owner=self.principal, + target=None if candidate.target is None else resource, + idempotency_key=bounded_idempotency_key("candidate-owner", scope_id, candidate.candidate_id), + ) + + async def topic_commit(self, connection: AsyncConnection, scope_id: str, _operations: Sequence[Any]) -> None: + """Authorize one Scope-owned Topic Memory publication. + + Topic Memory is shared Scope knowledge: it registers no Artifact Family + Access Profile and carries no per-topic owner, so its publications are + authorized by Scope authority alone. The batch is accepted unchanged. + """ + await self._authorize_scope(self.access.with_connection(connection), scope_id) + + +@asynccontextmanager +async def open_worker_security( + security: dict[str, Any] | None, database: AsyncDatabase +) -> AsyncIterator[WorkerSecurity | None]: + if security is None: + yield None + return + spec = WorkerSecuritySpec.model_validate(security) + repository = RelationalAccessRepository(database) + access = AccessControlService( + BuiltinAuthorizationProvider(repository, deployment_id=spec.deployment_id), + relationships=repository, + audit=repository, + deployment_id=spec.deployment_id, + static_scope_principal=spec.principal if spec.static_preset else None, + ) + yield WorkerSecurity(access, spec.principal) diff --git a/src/powercontext/builtin/persistence/cursors.py b/src/powercontext/builtin/persistence/cursors.py index 42212503c7..4e2a0c11f2 100644 --- a/src/powercontext/builtin/persistence/cursors.py +++ b/src/powercontext/builtin/persistence/cursors.py @@ -30,10 +30,8 @@ from powercontext.builtin.persistence.errors import ( GenerationConflictError, InvalidRepositoryArgumentError, - InvalidStoredColumnError, - InvalidStoredPayloadError, ) -from powercontext.builtin.persistence.tables import SOURCE_CURSORS_TABLE, SOURCE_JOURNAL_HEADS_TABLE +from powercontext.builtin.persistence.tables import SOURCE_CURSORS_TABLE from powercontext.builtin.sources import SourceCursor from powercontext.limits import MAX_BINDING_NAME_LENGTH, MAX_SCOPE_ID_LENGTH @@ -50,49 +48,6 @@ class StoredSourceCursor(BaseModel): class SourceCursorRepository: """Persist source-window cursors with generation CAS.""" - async def unconsumed_scope_ids(self, connection: AsyncConnection, binding_name: str, /) -> tuple[str, ...]: - """Select journals ahead of this binding, without per-Scope transactions. - - This is advisory discovery. The processor still validates its cursor and - window inside the owning transaction. Invalid cursors remain selected so - that their failure stays isolated to that Scope. - """ - - _require_identifier("binding_name", binding_name, MAX_BINDING_NAME_LENGTH) - heads = SOURCE_JOURNAL_HEADS_TABLE - cursors = SOURCE_CURSORS_TABLE - statement = ( - select(heads.c.scope_id, heads.c.position, cursors.c.cursor) - .select_from( - heads.outerjoin( - cursors, - (cursors.c.scope_id == heads.c.scope_id) & (cursors.c.binding_name == binding_name), - ) - ) - .where(heads.c.position > 0) - .order_by(heads.c.scope_id) - ) - selected: list[str] = [] - async with connection.stream(statement) as result: - async for batch in result.partitions(SELECTION_BATCH_SIZE): - for scope_id, position, payload in batch: - if payload is None: - selected.append(str(scope_id)) - continue - try: - cursor = load_model( - SourceCursor, - stored_bytes(payload, column="cursor"), - kind="source-cursor", - name=binding_name, - ) - except (InvalidStoredColumnError, InvalidStoredPayloadError): - selected.append(str(scope_id)) - else: - if cursor.sequence < position: - selected.append(str(scope_id)) - return tuple(selected) - async def load( self, connection: AsyncConnection, diff --git a/src/powercontext/builtin/persistence/migrations/atomic_memory_v1.py b/src/powercontext/builtin/persistence/migrations/atomic_memory_v1.py index 9a36a1cf9c..0386b3b21f 100644 --- a/src/powercontext/builtin/persistence/migrations/atomic_memory_v1.py +++ b/src/powercontext/builtin/persistence/migrations/atomic_memory_v1.py @@ -45,6 +45,8 @@ from powercontext.artifacts import Artifact from powercontext.builtin.artifacts.search import analyze_text +from powercontext.builtin.authz import ArtifactOwnerRelation, PrincipalRef, ResourceRef +from powercontext.builtin.authz.repository import RelationalAccessRepository from powercontext.builtin.persistence.atomic_memory_identity import legacy_entry_artifact_id from powercontext.builtin.persistence.atomic_memory_index import ( AtomicMemoryIndex, @@ -94,8 +96,6 @@ remove_legacy_collections, residual_issues, ) -from powercontext.server.authz import ArtifactOwnerRelation, PrincipalRef, ResourceRef -from powercontext.server.authz.repository import RelationalAccessRepository MIGRATION_ID = "powercontext.memory.v1-to-atomic-memory.v1" DEFAULT_SNAPSHOT_BUDGET_BYTES = 256 * 1024 * 1024 diff --git a/src/powercontext/builtin/runtime/__init__.py b/src/powercontext/builtin/runtime/__init__.py index 8618be4519..022c069eef 100644 --- a/src/powercontext/builtin/runtime/__init__.py +++ b/src/powercontext/builtin/runtime/__init__.py @@ -59,8 +59,6 @@ RemoteIngestionApplication, RemoteSkillApplication, ReviewApplication, - ScheduledExperienceProcessor, - ScheduledSourceProcessor, ScopedArtifactApplication, ScopedAtomicMemoryApplication, ScopedBootstrapApplication, @@ -426,8 +424,6 @@ "RuntimeReadiness", "RuntimeReadinessChecks", "RuntimeReadinessStatus", - "ScheduledExperienceProcessor", - "ScheduledSourceProcessor", "ScopeStatistics", "ScopedArtifactApplication", "ScopedArtifactMerge", diff --git a/src/powercontext/builtin/runtime/application.py b/src/powercontext/builtin/runtime/application.py index 63ec259e31..989b58ac66 100644 --- a/src/powercontext/builtin/runtime/application.py +++ b/src/powercontext/builtin/runtime/application.py @@ -25,7 +25,6 @@ from dataclasses import dataclass, replace from datetime import UTC, datetime, timedelta from hashlib import sha256 -from pathlib import Path from time import perf_counter from typing import TYPE_CHECKING, Any, Protocol, TypeVar from uuid import uuid4 @@ -363,8 +362,6 @@ from powercontext.sources import ConnectorBinding, SourceDefinitionManifest, SourceRef if TYPE_CHECKING: - from apscheduler.schedulers.asyncio import AsyncIOScheduler - from powercontext.builtin.handoff_report.application import HandoffReportApplication from powercontext.builtin.portability import PortableBundleService from powercontext.builtin.runtime.artifact_processing import ArtifactProcessingSupervisors @@ -406,7 +403,6 @@ def __call__( _MEMORY_SEARCH_MODE = "powercontext.memory.search.mode" _MEMORY_SEARCH_RESULT_COUNT = "powercontext.memory.search.result_count" -ScopeIds = Callable[[], Awaitable[tuple[str, ...]]] ReviewServiceFactory = Callable[[str], ReviewService] GenerationServiceFactory = Callable[[str], ReviewedGenerationService] ExternalSkillRegistryFactory = Callable[[str], ExternalSkillRegistryService] @@ -540,8 +536,6 @@ class _RecallRoundOutcome: RecallTokenEstimator = Callable[[str, PreparedContextBuild], Awaitable[RecallTokenMeasurement | None]] RecallEffortSink = Callable[[RecallEffort], Awaitable[None]] Clock = Callable[[], datetime] -ScheduledSourceRunner = Callable[[str, "BuiltinRuntime"], Awaitable[MemoryFlushResult]] -ScheduledExperienceRunner = Callable[[str, "BuiltinRuntime"], Awaitable[ExperienceIncubationResult]] _MEMORY_SEARCH_ATTEMPTS = 3 @@ -562,7 +556,6 @@ def __init__(self, code: str) -> None: "review": "Candidate Review services are not configured", "records": "Base Source and Artifact access is not configured", "remote-skill-distribution": "Remote Skill distribution services are not configured", - "scheduler": "Built-in Runtime scheduler is already started", "scope": "Scope services are not configured", "skill-publication": "Managed Skill publication services are not configured", "skill-provenance": "Managed Skill provenance services are not configured", @@ -4157,162 +4150,6 @@ def for_scope(self, scope_id: str, /) -> ScopedTopicMemoryApplication: return ScopedTopicMemoryApplication(self._runtime, scope_id) -class ScheduledSourceProcessor: - """Map APScheduler activations to scoped Source-window policies.""" - - def __init__(self, runtime: BuiltinRuntime, scope_ids: ScopeIds) -> None: - self._runtime = runtime - self._scope_ids = scope_ids - - async def run(self) -> None: - async with self._runtime._processor_lock: - if self._runtime._closing or self._runtime._closed: - return - for scope_id in await self._scope_ids(): - if self._runtime._closing or self._runtime._closed: - return - started_at = perf_counter() - with self._runtime._background( - "scheduled.process_source_window", - operation="process_source_window", - ) as span: - try: - runner = self._runtime._scheduled_source_runner - result = ( - await self._runtime._flush_sources(scope_id) - if runner is None - else await runner(scope_id, self._runtime) - ) - except asyncio.CancelledError: - _log_scheduled_processing( - "cancelled", - operation="process_source_window", - started_at=started_at, - ) - raise - except Exception as error: - _log_scheduled_processing( - "failure", - operation="process_source_window", - started_at=started_at, - error=error, - ) - if span is not None: - span.set_outcome("failure") - else: - outcome = "hold" if result.held_count else "success" if result.processed else "noop" - _log_scheduled_processing( - outcome, - operation="process_source_window", - started_at=started_at, - source_count=result.source_count, - held_count=result.held_count, - hold_codes=result.hold_codes, - ) - if span is not None: - span.set_outcome(outcome) - span.set_attributes({ - "powercontext.background.source_count": result.source_count, - "powercontext.background.memory_held_count": result.held_count, - "powercontext.background.memory_hold_codes": ",".join(result.hold_codes), - }) - - -class ScheduledExperienceProcessor: - """Map APScheduler activations to scoped Experience incubation windows.""" - - def __init__(self, runtime: BuiltinRuntime, scope_ids: ScopeIds) -> None: - self._runtime = runtime - self._scope_ids = scope_ids - - async def run(self) -> None: - async with self._runtime._processor_lock: - if self._runtime._closing or self._runtime._closed: - return - for scope_id in await self._scope_ids(): - if self._runtime._closing or self._runtime._closed: - return - started_at = perf_counter() - with self._runtime._background( - "scheduled.incubate_experience_candidates", - operation="incubate_experience_candidates", - ) as span: - try: - runner = self._runtime._scheduled_experience_runner - result = ( - await self._runtime.experience.for_scope(scope_id).incubate() - if runner is None - else await runner(scope_id, self._runtime) - ) - except asyncio.CancelledError: - _log_scheduled_processing( - "cancelled", - operation="incubate_experience_candidates", - started_at=started_at, - ) - raise - except Exception as error: - _log_scheduled_processing( - "failure", - operation="incubate_experience_candidates", - started_at=started_at, - error=error, - ) - if span is not None: - span.set_outcome("failure") - else: - outcome = "success" if result.processed else "noop" - _log_scheduled_processing( - outcome, - operation="incubate_experience_candidates", - started_at=started_at, - source_count=result.source_count, - candidate_count=result.candidate_count, - ) - if span is not None: - span.set_outcome(outcome) - span.set_attributes({ - "powercontext.background.source_count": result.source_count, - "powercontext.background.candidate_count": result.candidate_count, - }) - - -def _log_scheduled_processing( - outcome: str, - *, - operation: str, - started_at: float, - error: Exception | None = None, - source_count: int | None = None, - candidate_count: int | None = None, - held_count: int | None = None, - hold_codes: tuple[str, ...] = (), -) -> None: - extra = { - "event": "background.operation.completed", - "operation": operation, - "outcome": outcome, - "unit": "background", - "duration_ms": max(perf_counter() - started_at, 0) * 1_000, - } - if source_count is not None: - extra["source_count"] = source_count - if candidate_count is not None: - extra["candidate_count"] = candidate_count - if held_count is not None: - extra["held_count"] = held_count - if hold_codes: - extra["hold_codes"] = hold_codes - level = logging.ERROR if error is not None else logging.INFO - log_safely( - logger, - level, - "Scheduled background processing completed" if error is None else "Scheduled background processing failed", - exc_info=error, - extra=extra, - ) - - class BuiltinRuntime: """Add business-specific operations over composed built-in contexts.""" @@ -4333,8 +4170,6 @@ def __init__( scope_cache_size: int = DEFAULT_SCOPE_CACHE_SIZE, scope_evictor: ScopeEvictor | None = None, scope_cache_observer: ScopeCacheObserver | None = None, - scope_ids: ScopeIds | None = None, - source_scope_ids: ScopeIds | None = None, review_service: ReviewServiceFactory | None = None, catalog_change_service: Callable[[str], CatalogChangeService] | None = None, profiles: RelationalProfileService | None = None, @@ -4379,8 +4214,6 @@ def __init__( readiness: RuntimeReadinessChecks | None = None, clock: Clock | None = None, tracing: RuntimeTracing | None = None, - scheduled_source_runner: ScheduledSourceRunner | None = None, - scheduled_experience_runner: ScheduledExperienceRunner | None = None, remote_ingestion: RemoteIngestion | None = None, dream_service: DreamService | None = None, generation_concurrency: int = 4, @@ -4476,8 +4309,6 @@ def __init__( self._readiness = RuntimeReadinessChecks() if readiness is None else readiness self._clock = _utc_now if clock is None else clock self._tracing = tracing - self._scheduled_source_runner = scheduled_source_runner - self._scheduled_experience_runner = scheduled_experience_runner self.source_window_limit = source_window_limit self.context_assembly_max_entries = context_assembly_max_entries self.recall_sufficiency_policy = recall_sufficiency_policy @@ -4487,15 +4318,12 @@ def __init__( evictor=scope_evictor, observer=scope_cache_observer, ) - self._processor_lock = asyncio.Lock() self._close_lock = asyncio.Lock() self._lifecycle = asyncio.Condition() self._active_operations = 0 self._operation_depths: dict[asyncio.Task[Any], int] = {} self._closing = False self._closed = False - self._scheduler: AsyncIOScheduler | None = None - self._scheduler_runtime_key: str | None = None self.sources = SourceApplication(self) self.ingestion = RemoteIngestionApplication(self, remote_ingestion) self.code = CodeApplication(self, code_service or CodeService(CodeConfig())) @@ -4520,11 +4348,6 @@ def __init__( self.archive = archive_service self.handoff_report: HandoffReportApplication | None = None self.artifact_processing_supervisor: ArtifactProcessingSupervisors | None = None - source_ids = scope_ids if source_scope_ids is None else source_scope_ids - self.processor = None if source_ids is None else ScheduledSourceProcessor(self, source_ids) - self.experience_processor = ( - None if scope_ids is None or experience_incubator is None else ScheduledExperienceProcessor(self, scope_ids) - ) async def __aenter__(self) -> BuiltinRuntime: return self @@ -4628,83 +4451,6 @@ async def readiness(self) -> RuntimeReadiness: }, ) - def start_scheduler( # noqa: C901 - self, - scheduler_path: str | Path, - schedule_seconds: float | None, - *, - experience_schedule_seconds: float | None = None, - profile_cron: str | None = None, - profile_timezone: str = "Asia/Shanghai", - profile_max_concurrency: int = 4, - ) -> None: - """Start the APScheduler time adapter for this Runtime.""" - - if schedule_seconds is None and experience_schedule_seconds is None and profile_cron is None: - raise _RuntimeConfigurationError("schedule_seconds") - if schedule_seconds is not None and schedule_seconds <= 0: - raise _RuntimeConfigurationError("schedule_seconds") - if experience_schedule_seconds is not None and experience_schedule_seconds <= 0: - raise _RuntimeConfigurationError("experience_schedule_seconds") - if schedule_seconds is not None and self.processor is None: - raise _RuntimeConfigurationError("scope_ids") - if experience_schedule_seconds is not None and self.experience_processor is None: - raise _RuntimeStateError("experience-incubation") - if self._scheduler is not None or self.artifact_processing_supervisor is not None: - raise _RuntimeStateError("scheduler") - from powercontext.builtin.runtime.scheduler import ( - configure_experience_incubation_job, - configure_profile_job, - configure_source_window_job, - create_scheduler, - register_processors, - scheduler_runtime_key, - unregister_processor, - ) - - runtime_key = scheduler_runtime_key(scheduler_path) - scheduler: AsyncIOScheduler | None = None - - async def process_profiles(): - async with self._operation(): - if self.profiles is not None: - await self.profiles.scan(max_concurrency=profile_max_concurrency) - - register_processors( - runtime_key, - profile=process_profiles if profile_cron is not None else None, - source_window=None if schedule_seconds is None or self.processor is None else self.processor.run, - experience_incubation=( - None - if experience_schedule_seconds is None or self.experience_processor is None - else self.experience_processor.run - ), - ) - self._scheduler_runtime_key = runtime_key - try: - scheduler = create_scheduler(scheduler_path) - self._scheduler = scheduler - scheduler.start(paused=True) - configure_source_window_job( - scheduler, - runtime_key=runtime_key, - schedule_seconds=schedule_seconds, - ) - configure_experience_incubation_job( - scheduler, - runtime_key=runtime_key, - schedule_seconds=experience_schedule_seconds, - ) - configure_profile_job(scheduler, runtime_key=runtime_key, cron=profile_cron, timezone=profile_timezone) - scheduler.resume() - except BaseException: - if scheduler is not None and scheduler.running: - scheduler.shutdown(wait=False) - unregister_processor(runtime_key) - self._scheduler_runtime_key = None - self._scheduler = None - raise - def configure_evidence_authorization( self, *, @@ -4736,26 +4482,11 @@ async def close(self) -> None: async with self._close_lock: if self._closed: return - if self._scheduler is not None and self._scheduler.running: - self._scheduler.pause() async with self._lifecycle: self._closing = True await self._lifecycle.wait_for(lambda: self._active_operations == 0) if self.artifact_processing_supervisor is not None: await self.artifact_processing_supervisor.close() - async with self._processor_lock: - pass - try: - if self._scheduler is not None and self._scheduler.running: - self._scheduler.shutdown(wait=False) - await asyncio.sleep(0) - finally: - if self._scheduler_runtime_key is not None: - from powercontext.builtin.runtime.scheduler import unregister_processor - - unregister_processor(self._scheduler_runtime_key) - self._scheduler_runtime_key = None - self._scheduler = None self._scope_cache.clear() self._closed = True @@ -4903,16 +4634,6 @@ def _stage( return nullcontext(None) return self._tracing.stage(name, attributes=attributes) - def _background( - self, - name: str, - *, - operation: str, - ) -> AbstractContextManager[RuntimeSpan | None]: - if self._tracing is None: - return nullcontext(None) - return self._tracing.background(name, operation=operation, attributes={}) - def _review(self, scope_id: str) -> ReviewService: if self._review_service is None: raise _RuntimeStateError("review") diff --git a/src/powercontext/builtin/runtime/artifact_merge.py b/src/powercontext/builtin/runtime/artifact_merge.py index 456c2d4da4..f0a6a667c7 100644 --- a/src/powercontext/builtin/runtime/artifact_merge.py +++ b/src/powercontext/builtin/runtime/artifact_merge.py @@ -65,7 +65,7 @@ async def authorize( action: str, ref: ArtifactRef | None = None, ) -> None: - from powercontext.server.authz import AccessAction, AccessDeniedError, ResourceRef + from powercontext.builtin.authz import AccessAction, AccessDeniedError, ResourceRef if context is None: return @@ -109,7 +109,7 @@ async def establish_owners( ) -> None: if context is None or context.access is None or not artifact_ids: return - from powercontext.server.authz import ResourceRef + from powercontext.builtin.authz import ResourceRef await context.access.with_connection(connection).establish_artifact_owners( tuple( diff --git a/src/powercontext/builtin/runtime/artifact_plugins.py b/src/powercontext/builtin/runtime/artifact_plugins.py index 64689fad9f..c3dbea3a3e 100644 --- a/src/powercontext/builtin/runtime/artifact_plugins.py +++ b/src/powercontext/builtin/runtime/artifact_plugins.py @@ -103,7 +103,7 @@ def run_artifact_plugin_worker( async def _restore_access_families(database) -> None: - from powercontext.server.authz.profiles import register_custom_artifact_access_family + from powercontext.builtin.authz.profiles import register_custom_artifact_access_family async with database.transaction() as connection: families = (await connection.execute(select(ARTIFACT_FAMILY_SCHEMAS_TABLE.c.family).distinct())).scalars().all() @@ -113,7 +113,7 @@ async def _restore_access_families(database) -> None: async def _process_window(spec: ArtifactPluginWorkerSpec, assignment: ArtifactProcessingWorkAssignment): # noqa: C901 - One authorized window with preparation outside its commit. # Server authorization is reconstructed in this child using deployment identity. - from powercontext.server.processing_security import open_worker_security + from powercontext.builtin.authz.worker import open_worker_security definition = spec.definition declaration = definition["declaration"] @@ -296,7 +296,7 @@ async def _commit_window( security, prepared_indexes=None, ): - from powercontext.server.authz import AccessAction, ResourceRef, bounded_idempotency_key + from powercontext.builtin.authz import AccessAction, ResourceRef, bounded_idempotency_key validated = _validate_drafts(declaration, source_evidence, artifact_evidence, drafts) repository = custom_artifact_repository(declaration["family"], sources, prepared=prepared_indexes) diff --git a/src/powercontext/builtin/runtime/artifact_reads.py b/src/powercontext/builtin/runtime/artifact_reads.py index c5d21caee7..60a33660cd 100644 --- a/src/powercontext/builtin/runtime/artifact_reads.py +++ b/src/powercontext/builtin/runtime/artifact_reads.py @@ -25,6 +25,7 @@ from powercontext.artifacts.search import ( ArtifactSearchExecutionContext, ) +from powercontext.builtin.authz import AccessAction, BuiltinAuthorizationProvider, ResourceRef from powercontext.builtin.persistence.artifacts import ArtifactRepository from powercontext.builtin.persistence.cursor_codec import SignedCursorCodec from powercontext.builtin.persistence.custom_artifacts import StoredArtifactContent, custom_artifact_repository @@ -33,7 +34,6 @@ from powercontext.builtin.records import BaseArtifactFamily, BaseValueNotFoundError, InvalidBaseAccessRequestError from powercontext.builtin.runtime.artifact_search import ArtifactSearchService from powercontext.builtin.runtime.custom_artifact_search import CustomArtifactSearcher -from powercontext.server.authz import AccessAction, BuiltinAuthorizationProvider, ResourceRef class _StoredJsonContent(RootModel[dict[str, JsonValue]]): diff --git a/src/powercontext/builtin/runtime/atomic_memory.py b/src/powercontext/builtin/runtime/atomic_memory.py index dfae937e7d..24910d1333 100644 --- a/src/powercontext/builtin/runtime/atomic_memory.py +++ b/src/powercontext/builtin/runtime/atomic_memory.py @@ -263,7 +263,7 @@ async def authorize( and context.access is not None and context.access._deferred_decisions.get() is not None ): - from powercontext.server.authz import AccessAction, ResourceRef + from powercontext.builtin.authz import AccessAction, ResourceRef access = context.access.for_read(connection) await access.require( @@ -460,7 +460,7 @@ async def get_many(self, artifact_ids: Sequence[str], *, context=None) -> tuple[ async with self._read(context) as connection: identities = tuple(dict.fromkeys(artifact_ids)) if context is not None and context.access is not None: - from powercontext.server.authz import ResourceRef + from powercontext.builtin.authz import ResourceRef access = context.access.for_read(connection) policy = access.prefetch_point_decisions( diff --git a/src/powercontext/builtin/runtime/atomic_memory_processing.py b/src/powercontext/builtin/runtime/atomic_memory_processing.py index 59834be2b2..1e5fa9a167 100644 --- a/src/powercontext/builtin/runtime/atomic_memory_processing.py +++ b/src/powercontext/builtin/runtime/atomic_memory_processing.py @@ -404,8 +404,8 @@ async def _publish( _conflict("Source generation eligibility changed during preparation") local_policy = False if context is not None and context.access is not None: - from powercontext.server.authz import BuiltinAuthorizationProvider - from powercontext.server.authz.casbin import CasbinAuthorizationProvider + from powercontext.builtin.authz import BuiltinAuthorizationProvider + from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider local_policy = ( type(context.access.provider) in {BuiltinAuthorizationProvider, CasbinAuthorizationProvider} @@ -612,7 +612,7 @@ async def compare_page(page_keys: tuple[str, ...]) -> str: return workset, tuple(artifacts.values()) async def _load_related_items(self, connection, scope_id, hits, context, workset, *, joined_heads): - from powercontext.server.authz import AccessDeniedError + from powercontext.builtin.authz import AccessDeniedError allowed = [] for hit in hits: @@ -847,7 +847,7 @@ async def _observe_model_input(self, connection, scope_id, generation_sources, * sources = tuple({(item.ref.source_type, item.ref.source_id): item for item in generation_sources}.values()) policy = literal(None) if include_policy: - from powercontext.server.authz.repository import ACCESS_POLICY_HEADS_TABLE + from powercontext.builtin.authz.repository import ACCESS_POLICY_HEADS_TABLE policy = func.coalesce( select(ACCESS_POLICY_HEADS_TABLE.c.revision) @@ -907,7 +907,7 @@ async def _prefetch_artifact_policy( if context is None or context.access is None or (not refs and not include_scope): yield True return - from powercontext.server.authz import ResourceRef + from powercontext.builtin.authz import ResourceRef access = context.access.for_read(connection) resources = tuple( @@ -934,7 +934,7 @@ async def _read_transaction(self, context, *, write_policy_first=False, consiste access = None if context is None else context.access pins_with_policy = access is not None and access.supports_read_snapshot(connection.engine) if pins_with_policy and write_policy_first: - from powercontext.server.authz import BuiltinAuthorizationProvider + from powercontext.builtin.authz import BuiltinAuthorizationProvider # Read-side Casbin binds to the business transaction; its write # path does not. Builtin policy binds both when relationships diff --git a/src/powercontext/builtin/runtime/atomic_memory_search.py b/src/powercontext/builtin/runtime/atomic_memory_search.py index 401d2e97b6..74f33a9e8b 100644 --- a/src/powercontext/builtin/runtime/atomic_memory_search.py +++ b/src/powercontext/builtin/runtime/atomic_memory_search.py @@ -16,9 +16,9 @@ from powercontext.artifacts import ArtifactSearchExecutionContext from powercontext.builtin.artifacts.atomic_memory.search import AtomicArtifactSearchRequest +from powercontext.builtin.authz import AccessDeniedError, AccessIdentityRequiredError, PrincipalRef from powercontext.builtin.runtime.atomic_memory import AtomicMemoryApplication, AtomicMemorySearchPage from powercontext.builtin.sources import validate_scope_id -from powercontext.server.authz import AccessDeniedError, AccessIdentityRequiredError, PrincipalRef class AtomicArtifactSearcher: diff --git a/src/powercontext/builtin/runtime/composition.py b/src/powercontext/builtin/runtime/composition.py index 9a44026378..227b901c9b 100644 --- a/src/powercontext/builtin/runtime/composition.py +++ b/src/powercontext/builtin/runtime/composition.py @@ -19,6 +19,7 @@ import json import logging import os +import warnings from collections.abc import AsyncIterator, Callable, Mapping, Sequence from contextlib import AsyncExitStack, asynccontextmanager, nullcontext, suppress from datetime import timedelta @@ -160,8 +161,6 @@ from powercontext.builtin.runtime.application import ( BuiltinRuntime, RecallEffortSink, - ScheduledExperienceRunner, - ScheduledSourceRunner, ) from powercontext.builtin.runtime.artifact_merge import ( ArtifactMergeAccess, @@ -530,10 +529,10 @@ def _validate_protected_inference(protection: InferenceProtectionConfig, *depend @asynccontextmanager -async def open_builtin_runtime( +async def open_builtin_runtime( # noqa: C901 config: BuiltinConfig, *, - scheduler_path: str | Path = "powercontext.scheduler.db", + scheduler_path: str | Path | None = None, candidate_pipeline: CandidatePipeline | AtomicMemoryGenerationPipeline | None = None, experience_pipeline: ExperienceCandidatePipeline | None = None, experience_generator: ExperienceGenerator | None = None, @@ -565,8 +564,6 @@ async def open_builtin_runtime( processing_observer: Callable[[str, str, float], None] | None = None, worker_initializer: Callable[[], None] | WorkerInitializerPreparation | None = None, worker_entrypoint_wrapper: Callable[[WorkerEntrypoint], WorkerEntrypoint] | None = None, - scheduled_source_runner: ScheduledSourceRunner | None = None, - scheduled_experience_runner: ScheduledExperienceRunner | None = None, scheduled_profile_runner: Any = None, source_registry: SourceDefinitionRegistry | None = None, cursor_secret: bytes | None = None, @@ -590,8 +587,18 @@ async def open_builtin_runtime( a context manager yielding the picklable child bootstrap. Its resources remain open until spawn or cancellation cleanup finishes. Custom bindings own their launchers and initialization. The default does not configure process logging. + + ``scheduler_path`` is deprecated and ignored. """ + if scheduler_path is not None: + warnings.warn( + "scheduler_path is ignored and will be removed; automatic processing is scheduled by the " + "artifact processing supervisor", + DeprecationWarning, + stacklevel=3, + ) + async with AsyncExitStack() as resources: _validate_protected_inference( config.inference.protection, @@ -869,8 +876,6 @@ async def run_profile(scope_id, high): scope_cache_size=config.runtime.scope_cache_size, scope_evictor=contexts.evict, scope_cache_observer=scope_cache_observer, - scope_ids=contexts.scope_ids, - source_scope_ids=contexts.unconsumed_source_scope_ids, review_service=contexts.review, catalog_change_service=contexts.catalog_changes, profiles=contexts.profiles, @@ -928,8 +933,6 @@ async def run_profile(scope_id, high): disabled_dependencies=(name for name, probe in inference_readiness if probe is None), ), tracing=tracing, - scheduled_source_runner=scheduled_source_runner, - scheduled_experience_runner=scheduled_experience_runner, remote_ingestion=contexts, archive_service=contexts.portability, ) @@ -2539,8 +2542,8 @@ def _search_modes(capabilities: AtomicMemoryIndexCapabilities) -> tuple[MemorySe async def _initialize_atomic_memory_authority(connection) -> None: """Create formal authority storage without importing legacy business data.""" + from powercontext.builtin.authz.repository import ACCESS_POLICY_HEADS_TABLE, ACCESS_TABLES from powercontext.builtin.persistence.schema import create_tables - from powercontext.server.authz.repository import ACCESS_POLICY_HEADS_TABLE, ACCESS_TABLES await create_tables(connection, ACCESS_TABLES) if connection.dialect.name == "sqlite": diff --git a/src/powercontext/builtin/runtime/custom_artifact_search.py b/src/powercontext/builtin/runtime/custom_artifact_search.py index 7a076c22fa..775e5c52b7 100644 --- a/src/powercontext/builtin/runtime/custom_artifact_search.py +++ b/src/powercontext/builtin/runtime/custom_artifact_search.py @@ -48,6 +48,7 @@ ) from powercontext.builtin.artifacts.memory.models import EmbeddingProfile from powercontext.builtin.artifacts.search import analyze_fts_query, fts_match_query, lexical_search_score +from powercontext.builtin.authz import AccessAction, BuiltinAuthorizationProvider, ResourceRef from powercontext.builtin.inference.protocols import embed_query from powercontext.builtin.persistence.artifact_indexes import ( DEFINITIONS, @@ -63,7 +64,6 @@ from powercontext.builtin.persistence.custom_artifacts import custom_artifact_repository from powercontext.builtin.persistence.sqlite.profile import ensure_sqlite_vector_extension from powercontext.builtin.persistence.tables import ARTIFACT_HEADS_TABLE, ARTIFACT_PROCESSING_BINDING_STATES_TABLE -from powercontext.server.authz import AccessAction, BuiltinAuthorizationProvider, ResourceRef class ArtifactQueryVector(BaseModel): diff --git a/src/powercontext/builtin/runtime/decision_projection.py b/src/powercontext/builtin/runtime/decision_projection.py index 8f2e8ee103..9ba9f7688b 100644 --- a/src/powercontext/builtin/runtime/decision_projection.py +++ b/src/powercontext/builtin/runtime/decision_projection.py @@ -31,7 +31,7 @@ from powercontext.builtin.decision_projection_contract import DecisionProjectionFact from powercontext.builtin.runtime.decision_model import DecisionRequest -from powercontext.client.capture import REDACTED, known_secret_values, redact_known_secrets +from powercontext.redaction import REDACTED, known_secret_values, redact_known_secrets _FACT_RE = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$") _MAX_FACTS = 8 diff --git a/src/powercontext/builtin/runtime/dream_processing.py b/src/powercontext/builtin/runtime/dream_processing.py index 6ab0dc24a0..c18af35083 100644 --- a/src/powercontext/builtin/runtime/dream_processing.py +++ b/src/powercontext/builtin/runtime/dream_processing.py @@ -25,8 +25,8 @@ from powercontext.builtin.runtime.processing_execution import ScopeInvocation if TYPE_CHECKING: + from powercontext.builtin.authz.worker import WorkerSecurity from powercontext.builtin.runtime.relational import RelationalContexts - from powercontext.server.processing_security import WorkerSecurity async def process_dream_invocation( @@ -39,9 +39,9 @@ async def process_dream_invocation( ) -> bool: access = None if security is not None: - from powercontext.server.dream_access import DreamAccess + from powercontext.builtin.authz.dream import DreamAuthorization - access = DreamAccess(security.access) + access = DreamAuthorization(security.access) service = contexts.dream( generator, budget=config.runtime.dream_budget, diff --git a/src/powercontext/builtin/runtime/family_processing.py b/src/powercontext/builtin/runtime/family_processing.py index 4f03395a78..30e0b662ba 100644 --- a/src/powercontext/builtin/runtime/family_processing.py +++ b/src/powercontext/builtin/runtime/family_processing.py @@ -52,8 +52,8 @@ from powercontext.errors import RevisionConflictError if TYPE_CHECKING: + from powercontext.builtin.authz.worker import WorkerSecurity from powercontext.builtin.runtime.relational import RelationalContexts - from powercontext.server.processing_security import WorkerSecurity FAMILY_BINDINGS = { @@ -147,7 +147,7 @@ async def _run_family_worker( security = None if spec.worker_security is not None: # The optional Server adapter stays outside Runtime-only SDK composition. - from powercontext.server.processing_security import open_worker_security + from powercontext.builtin.authz.worker import open_worker_security security = await resources.enter_async_context( open_worker_security(spec.worker_security, contexts.database) diff --git a/src/powercontext/builtin/runtime/relational.py b/src/powercontext/builtin/runtime/relational.py index ffb0932214..2a7b477be4 100644 --- a/src/powercontext/builtin/runtime/relational.py +++ b/src/powercontext/builtin/runtime/relational.py @@ -168,7 +168,7 @@ ArtifactProcessingBindingStateRepository, ArtifactProcessingLeaseRepository, ) -from powercontext.builtin.persistence.tables import ARTIFACT_HEADS_TABLE, SOURCE_JOURNAL_HEADS_TABLE +from powercontext.builtin.persistence.tables import ARTIFACT_HEADS_TABLE from powercontext.builtin.persistence.tags import RelationalTagService from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository from powercontext.builtin.persistence.topic_memory_index import NoTopicMemoryIndex, TopicMemoryIndex @@ -1078,7 +1078,7 @@ async def search_topic_memories( scope = validate_scope_id(scope_id) access = None if execution_context is None else execution_context.access if execution_context is not None and access is None and not execution_context.trusted_local: - from powercontext.server.authz import AccessDeniedError + from powercontext.builtin.authz import AccessDeniedError raise AccessDeniedError audit = nullcontext() if access is None else access.defer_decision_audit() @@ -1394,23 +1394,6 @@ async def import_external_skill( on_commit=on_commit, ) - async def scope_ids(self) -> tuple[str, ...]: - """Return scopes with a Source journal, in deterministic order.""" - - async with self.database.transaction() as connection: - values = ( - await connection.execute( - select(SOURCE_JOURNAL_HEADS_TABLE.c.scope_id).order_by(SOURCE_JOURNAL_HEADS_TABLE.c.scope_id) - ) - ).scalars() - return tuple(str(value) for value in values) - - async def unconsumed_source_scope_ids(self) -> tuple[str, ...]: - """Return built-in Source windows that still have journal input.""" - - async with self.database.transaction() as connection: - return await self.repositories.cursors.unconsumed_scope_ids(connection, SOURCE_WINDOW_TRIGGER_NAME) - async def handoff_scope_ids(self) -> tuple[str, ...]: """Return scopes with a committed Handoff head, in deterministic order.""" diff --git a/src/powercontext/builtin/runtime/scheduler.py b/src/powercontext/builtin/runtime/scheduler.py deleted file mode 100644 index cf8268e409..0000000000 --- a/src/powercontext/builtin/runtime/scheduler.py +++ /dev/null @@ -1,240 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Persistent APScheduler adapter for built-in Source-window activations.""" - -from __future__ import annotations - -from collections.abc import Awaitable, Callable -from datetime import UTC, datetime -from pathlib import Path - -from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore -from apscheduler.schedulers.asyncio import AsyncIOScheduler -from apscheduler.triggers.cron import CronTrigger -from apscheduler.triggers.interval import IntervalTrigger -from sqlalchemy import URL - -from powercontext._logging import log_context - -PROFILE_JOB_ID = "powercontext.profile.source-window.v1" -SOURCE_WINDOW_JOB_ID = "powercontext.memory.source-window.v1" -EXPERIENCE_INCUBATION_JOB_ID = "powercontext.experience.incubation.v1" -SCHEDULER_TABLE = "powercontext_scheduler_jobs" - -Processor = Callable[[], Awaitable[None]] -_SOURCE_WINDOW_PROCESSOR = "source-window" -_EXPERIENCE_INCUBATION_PROCESSOR = "experience-incubation" -_processors: dict[str, dict[str, Processor]] = {} - - -class SchedulerConfigurationError(ValueError): - """Report an unsupported scheduler sidecar configuration.""" - - def __init__(self) -> None: - super().__init__("scheduler_path must reference a file") - - -class SchedulerStateError(RuntimeError): - """Report conflicting runtime ownership for a persisted scheduler.""" - - def __init__(self, code: str, runtime_key: str) -> None: - messages = { - "duplicate": f"a scheduled runtime is already open for {runtime_key}", - "missing": f"no live scheduled runtime is registered for {runtime_key}", - } - super().__init__(messages[code]) - - -def scheduler_runtime_key(scheduler_path: str | Path) -> str: - """Return the stable in-process lookup key for one scheduler sidecar.""" - - if str(scheduler_path) == ":memory:": - raise SchedulerConfigurationError - return str(Path(scheduler_path).expanduser().resolve()) - - -def scheduler_database_path(scheduler_path: str | Path) -> str: - """Return the sidecar database used only by the persisted job store.""" - - return str(Path(scheduler_runtime_key(scheduler_path))) - - -def register_processors( - runtime_key: str, - *, - source_window: Processor | None, - experience_incubation: Processor | None, - profile: Processor | None = None, -) -> None: - """Register live processors referenced by persisted jobs.""" - - if runtime_key in _processors: - raise SchedulerStateError("duplicate", runtime_key) - registered = { - name: processor - for name, processor in ( - ("profile", profile), - (_SOURCE_WINDOW_PROCESSOR, source_window), - (_EXPERIENCE_INCUBATION_PROCESSOR, experience_incubation), - ) - if processor is not None - } - if not registered: - raise SchedulerStateError("missing", runtime_key) - _processors[runtime_key] = registered - - -def unregister_processor(runtime_key: str) -> None: - """Remove a live processor after its scheduler has stopped.""" - - _processors.pop(runtime_key, None) - - -async def dispatch_source_windows(runtime_key: str) -> None: - """Dispatch a persisted job to the live runtime owning its database.""" - - with log_context({"request_id": None}): - await _processor(runtime_key, _SOURCE_WINDOW_PROCESSOR)() - - -async def dispatch_experience_incubation(runtime_key: str) -> None: - """Dispatch persisted Experience incubation to its live Runtime.""" - - with log_context({"request_id": None}): - await _processor(runtime_key, _EXPERIENCE_INCUBATION_PROCESSOR)() - - -def _processor(runtime_key: str, name: str) -> Processor: - try: - return _processors[runtime_key][name] - except KeyError: - raise SchedulerStateError("missing", runtime_key) from None - - -def create_scheduler(scheduler_path: str | Path) -> AsyncIOScheduler: - """Create an APScheduler instance with an isolated SQLite job-store.""" - - database = Path(scheduler_database_path(scheduler_path)) - database.parent.mkdir(parents=True, exist_ok=True) - url = URL.create("sqlite+pysqlite", database=str(database)) - return AsyncIOScheduler( - jobstores={ - "default": SQLAlchemyJobStore( - url=url, - tablename=SCHEDULER_TABLE, - engine_options={"connect_args": {"timeout": 30}}, - ) - }, - timezone="UTC", - ) - - -def configure_source_window_job( - scheduler: AsyncIOScheduler, - *, - runtime_key: str, - schedule_seconds: float | None, -) -> None: - """Create or reconcile the persisted Source-window interval job.""" - - _configure_interval_job( - scheduler, - job_id=SOURCE_WINDOW_JOB_ID, - processor=dispatch_source_windows, - runtime_key=runtime_key, - schedule_seconds=schedule_seconds, - ) - - -def configure_experience_incubation_job( - scheduler: AsyncIOScheduler, - *, - runtime_key: str, - schedule_seconds: float | None, -) -> None: - """Create or reconcile the persisted Experience incubation job.""" - - _configure_interval_job( - scheduler, - job_id=EXPERIENCE_INCUBATION_JOB_ID, - processor=dispatch_experience_incubation, - runtime_key=runtime_key, - schedule_seconds=schedule_seconds, - ) - - -def _configure_interval_job( - scheduler: AsyncIOScheduler, - *, - job_id: str, - processor: Callable[[str], Awaitable[None]], - runtime_key: str, - schedule_seconds: float | None, -) -> None: - job = scheduler.get_job(job_id) - if schedule_seconds is None: - if job is not None: - scheduler.remove_job(job_id) - return - if job is None: - scheduler.add_job( - processor, - "interval", - args=(runtime_key,), - seconds=schedule_seconds, - coalesce=True, - max_instances=1, - misfire_grace_time=None, - id=job_id, - ) - return - scheduler.modify_job( - job_id, - func=processor, - args=(runtime_key,), - coalesce=True, - max_instances=1, - misfire_grace_time=None, - ) - if not isinstance(job.trigger, IntervalTrigger) or job.trigger.interval.total_seconds() != schedule_seconds: - scheduler.reschedule_job( - job_id, - trigger="interval", - seconds=schedule_seconds, - ) - - -async def dispatch_profile_windows(runtime_key: str) -> None: - with log_context({"request_id": None}): - await _processor(runtime_key, "profile")() - - -def configure_profile_job(scheduler, *, runtime_key: str, cron: str | None, timezone: str) -> None: - if cron is None: - if scheduler.get_job(PROFILE_JOB_ID) is not None: - scheduler.remove_job(PROFILE_JOB_ID) - return - # Immediate first run catches up missed windows; subsequent runs use the cron. - scheduler.add_job( - dispatch_profile_windows, - trigger=CronTrigger.from_crontab(cron, timezone=timezone), - id=PROFILE_JOB_ID, - replace_existing=True, - args=(runtime_key,), - coalesce=True, - max_instances=1, - misfire_grace_time=86400, - next_run_time=datetime.now(UTC), - ) diff --git a/src/powercontext/builtin/runtime/topic_memory_processing.py b/src/powercontext/builtin/runtime/topic_memory_processing.py index f8dee45d09..18240c8be5 100644 --- a/src/powercontext/builtin/runtime/topic_memory_processing.py +++ b/src/powercontext/builtin/runtime/topic_memory_processing.py @@ -1816,7 +1816,7 @@ async def _process_topic_dream_if_pending( generator = await _dream_generator(spec.config.inference, record.run.budget, resources, instrumentation) security = None if spec.worker_security is not None: - from powercontext.server.processing_security import open_worker_security + from powercontext.builtin.authz.worker import open_worker_security security = await resources.enter_async_context( open_worker_security(spec.worker_security, contexts.database) @@ -2019,7 +2019,7 @@ def stage( security = None if spec.worker_security is not None: # Runtime-only SDK workers do not require the optional Server adapter. - from powercontext.server.processing_security import open_worker_security + from powercontext.builtin.authz.worker import open_worker_security security = await resources.enter_async_context( open_worker_security(spec.worker_security, contexts.database) diff --git a/src/powercontext/cli/app.py b/src/powercontext/cli/app.py index f4ded89c30..ad79f9645c 100644 --- a/src/powercontext/cli/app.py +++ b/src/powercontext/cli/app.py @@ -33,7 +33,7 @@ # Extras are not recorded as installed. Check their declared requirements before # loading these providers; unrelated packages must not enable an incomplete role. _OPTIONAL_COMMAND_ROLES = { - "powercontext.builtin.code.cli:app": "builtin", + "powercontext.cli.code:app": "builtin", "powercontext.server.cli:app": "server", "powercontext.service.cli:app": "server", } diff --git a/src/powercontext/cli/archive.py b/src/powercontext/cli/archive.py index 17757f7b03..157befbdbb 100644 --- a/src/powercontext/cli/archive.py +++ b/src/powercontext/cli/archive.py @@ -51,7 +51,6 @@ from powercontext.builtin.runtime import BuiltinConfig, open_builtin_runtime from powercontext.builtin.runtime.relational import BUILTIN_ARTIFACT_TYPES, BUILTIN_CANDIDATE_PROPOSAL_TYPES from powercontext.builtin.sources import BUILTIN_SOURCE_REGISTRY -from powercontext.paths import default_scheduler_path from powercontext.server.configuration import server_settings_context HELP_OPTION_NAMES = ("-h", "--help") @@ -139,9 +138,7 @@ async def _run_archive( handoff_report=settings.handoff_report, external_skills=settings.external_skills, ) - async with open_builtin_runtime( - config, scheduler_path=default_scheduler_path(), _archive_recovery=recovery - ) as runtime: + async with open_builtin_runtime(config, _archive_recovery=recovery) as runtime: if runtime.archive is None: raise RuntimeError("portable archive service is unavailable") # noqa: TRY003 return await operation(runtime.archive) diff --git a/src/powercontext/builtin/code/cli.py b/src/powercontext/cli/code.py similarity index 100% rename from src/powercontext/builtin/code/cli.py rename to src/powercontext/cli/code.py diff --git a/src/powercontext/cli/config.py b/src/powercontext/cli/config.py index 53ff86b3fe..e9d3aedf9b 100644 --- a/src/powercontext/cli/config.py +++ b/src/powercontext/cli/config.py @@ -36,8 +36,8 @@ import typer from pydantic import ValidationError -from powercontext.cli.env_file import EnvironmentFileError, parse_environment -from powercontext.cli.inference_notice import write_inference_capability_notice +from powercontext.env_file import EnvironmentFileError, parse_environment +from powercontext.server.inference_notice import write_inference_capability_notice if TYPE_CHECKING: from powercontext.server.settings import ServerSettings diff --git a/src/powercontext/cli/config_wizard.py b/src/powercontext/cli/config_wizard.py index ec06780a55..2a7d4ea954 100644 --- a/src/powercontext/cli/config_wizard.py +++ b/src/powercontext/cli/config_wizard.py @@ -48,8 +48,8 @@ start_seekdb_install, ) from powercontext.cli.config_wizard_ui import WizardUI, choose_language -from powercontext.cli.env_file import EnvironmentFileError, parse_environment from powercontext.client.settings import normalize_server_url +from powercontext.env_file import EnvironmentFileError, parse_environment from powercontext.paths import default_database_path, default_seekdb_path, sqlite_url SERVER = "POWERCONTEXT_SERVER_" diff --git a/src/powercontext/cli/config_wizard_document.py b/src/powercontext/cli/config_wizard_document.py index 5d33382f2b..fa5b3fb742 100644 --- a/src/powercontext/cli/config_wizard_document.py +++ b/src/powercontext/cli/config_wizard_document.py @@ -25,7 +25,7 @@ from contextlib import closing from pathlib import Path -from powercontext.cli.env_file import EnvironmentFileError, _split_assignment, parse_environment +from powercontext.env_file import EnvironmentFileError, _split_assignment, parse_environment _BEGIN = "# >>> powercontext managed configuration >>>" _END = "# <<< powercontext managed configuration <<<" diff --git a/src/powercontext/cli/transport.py b/src/powercontext/cli/transport.py index 361dd51da8..548a924049 100644 --- a/src/powercontext/cli/transport.py +++ b/src/powercontext/cli/transport.py @@ -177,7 +177,7 @@ def _setup_consent(host: str, endpoint: str, requested: bool | None, native: dic def setup_environment() -> dict[str, str]: """Read setup configuration without executing shell code or changing the process.""" - from powercontext.cli.env_file import read_environment_file + from powercontext.env_file import read_environment_file explicit = setup_environment_file.get() path = explicit.expanduser() if explicit is not None else Path.cwd() / ".env" diff --git a/src/powercontext/client/capture.py b/src/powercontext/client/capture.py index 3fbe0d20a8..1be888d0e0 100644 --- a/src/powercontext/client/capture.py +++ b/src/powercontext/client/capture.py @@ -17,17 +17,13 @@ from __future__ import annotations import json -import os -from collections.abc import Iterable, Mapping -from functools import lru_cache -from pathlib import Path +from collections.abc import Mapping from typing import Any from pydantic import TypeAdapter -SENSITIVE_KEY_PARTS = ("api_key", "authorization", "cookie", "password", "secret", "token") -SENSITIVE_KEY_COMPACT_PARTS = tuple(part.replace("_", "") for part in SENSITIVE_KEY_PARTS) -REDACTED = "[REDACTED]" +from powercontext.redaction import REDACTED, is_sensitive_key, redact_known_secrets + UNSERIALIZABLE = "[UNSERIALIZABLE]" _CAPTURE_VALUE_ADAPTER = TypeAdapter(Any) @@ -135,79 +131,3 @@ def _capture_key(value: Any) -> str: if structured is None or isinstance(structured, bool | int | float): return str(structured) return UNSERIALIZABLE - - -def known_secret_values(*, codex_home: Path | None = None) -> frozenset[str]: - """Return the known secret values used by all PowerContext redaction paths.""" - - secrets = {secret for name, secret in os.environ.items() if secret and len(secret) >= 8 and is_sensitive_key(name)} - secrets.update(_codex_auth_secrets(codex_home=codex_home)) - return frozenset(secrets) - - -def redact_known_secrets( - value: str, - *, - codex_home: Path | None = None, - secrets: Iterable[str] | None = None, -) -> str: - """Redact known environment and Codex-auth secret values. - - When ``secrets`` is supplied it is treated as a complete, precomputed snapshot; - ``codex_home`` is intentionally ignored in that mode. - """ - - values = known_secret_values(codex_home=codex_home) if secrets is None else secrets - known: Iterable[str] = sorted(values, key=len, reverse=True) - for secret in known: - value = value.replace(secret, REDACTED) - return value - - -def is_sensitive_key(key: str) -> bool: - """Return whether a key name conventionally contains secret material.""" - - folded = "".join(character for character in key.casefold() if character.isalnum()) - return any(part in folded for part in SENSITIVE_KEY_COMPACT_PARTS) - - -def _codex_auth_secrets(*, codex_home: Path | None = None) -> frozenset[str]: - root = codex_home if codex_home is not None else Path(os.getenv("CODEX_HOME", str(Path.home() / ".codex"))) - auth_path = root.expanduser() / "auth.json" - try: - stat = auth_path.stat() - except OSError: - return frozenset() - fingerprint = (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns) - return _cached_codex_auth_secrets(str(auth_path), fingerprint) - - -@lru_cache(maxsize=8) -def _cached_codex_auth_secrets( - auth_path: str, - fingerprint: tuple[int, int, int, int, int], -) -> frozenset[str]: - """Read Codex credentials once for each observed auth-file version.""" - - del fingerprint - try: - auth = json.loads(Path(auth_path).read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return frozenset() - return frozenset(_sensitive_values(auth)) - - -def _sensitive_values(value: Any, *, sensitive: bool = False) -> set[str]: - if isinstance(value, Mapping): - secrets: set[str] = set() - for key, item in value.items(): - secrets.update(_sensitive_values(item, sensitive=sensitive or is_sensitive_key(str(key)))) - return secrets - if isinstance(value, list | tuple): - secrets = set() - for item in value: - secrets.update(_sensitive_values(item, sensitive=sensitive)) - return secrets - if sensitive and isinstance(value, str) and len(value) >= 8: - return {value} - return set() diff --git a/src/powercontext/client/session_import.py b/src/powercontext/client/session_import.py index 0d072cf535..de4a260e25 100644 --- a/src/powercontext/client/session_import.py +++ b/src/powercontext/client/session_import.py @@ -27,7 +27,6 @@ from shutil import which from typing import Literal, Protocol, cast -from powercontext.client.capture import redact_known_secrets from powercontext.client.errors import ClientError, ServerResponseError from powercontext.http import ( CaptureContentSourceRequest, @@ -36,6 +35,7 @@ ScopeBindingKey, ScopeDescriptor, ) +from powercontext.redaction import redact_known_secrets SUPPORTED_SESSION_IMPORT_HOSTS = ("codex",) _MAX_CONTENT_LENGTH = 200_000 diff --git a/src/powercontext/cli/env_file.py b/src/powercontext/env_file.py similarity index 100% rename from src/powercontext/cli/env_file.py rename to src/powercontext/env_file.py diff --git a/src/powercontext/observability/profile.py b/src/powercontext/observability/profile.py index d59f147df1..8238ffce03 100644 --- a/src/powercontext/observability/profile.py +++ b/src/powercontext/observability/profile.py @@ -21,7 +21,7 @@ from collections.abc import Mapping from importlib.util import find_spec -from powercontext.cli.env_file import read_environment_file +from powercontext.env_file import read_environment_file from powercontext.observability.deployment import ObservabilityError, load_state, state_directory diff --git a/src/powercontext/ops/local_policy.py b/src/powercontext/ops/local_policy.py index ef19adb714..594c27a5d8 100644 --- a/src/powercontext/ops/local_policy.py +++ b/src/powercontext/ops/local_policy.py @@ -27,7 +27,7 @@ from sqlalchemy.engine import make_url from sqlalchemy.exc import ArgumentError -from powercontext.cli.env_file import environment_context +from powercontext.env_file import environment_context from powercontext.ops.protocol import OpsError, digest from powercontext.paths import POWERCONTEXT_HOME_ENV, powercontext_data_dir, sqlite_url from powercontext.server.configuration import server_settings_context diff --git a/src/powercontext/paths.py b/src/powercontext/paths.py index 81e2f18e0d..1d932e06d0 100644 --- a/src/powercontext/paths.py +++ b/src/powercontext/paths.py @@ -45,12 +45,6 @@ def default_seekdb_path() -> Path: return powercontext_data_dir() / "seekdb" -def default_scheduler_path() -> Path: - """Return the installed Server's default scheduler database path.""" - - return powercontext_data_dir() / "scheduler.db" - - def sqlite_url(path: Path) -> str: """Render an absolute path as an async SQLAlchemy SQLite URL.""" @@ -60,7 +54,6 @@ def sqlite_url(path: Path) -> str: __all__ = [ "POWERCONTEXT_HOME_ENV", "default_database_path", - "default_scheduler_path", "default_seekdb_path", "powercontext_data_dir", "sqlite_url", diff --git a/src/powercontext/redaction.py b/src/powercontext/redaction.py new file mode 100644 index 0000000000..730ef4cf03 --- /dev/null +++ b/src/powercontext/redaction.py @@ -0,0 +1,104 @@ +# Copyright (c) 2026 OceanBase. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Redact credential values shared by Client capture and Runtime projections.""" + +from __future__ import annotations + +import json +import os +from collections.abc import Iterable, Mapping +from functools import lru_cache +from pathlib import Path +from typing import Any + +SENSITIVE_KEY_PARTS = ("api_key", "authorization", "cookie", "password", "secret", "token") +SENSITIVE_KEY_COMPACT_PARTS = tuple(part.replace("_", "") for part in SENSITIVE_KEY_PARTS) +REDACTED = "[REDACTED]" + + +def known_secret_values(*, codex_home: Path | None = None) -> frozenset[str]: + """Return the known secret values used by all PowerContext redaction paths.""" + + secrets = {secret for name, secret in os.environ.items() if secret and len(secret) >= 8 and is_sensitive_key(name)} + secrets.update(_codex_auth_secrets(codex_home=codex_home)) + return frozenset(secrets) + + +def redact_known_secrets( + value: str, + *, + codex_home: Path | None = None, + secrets: Iterable[str] | None = None, +) -> str: + """Redact known environment and Codex-auth secret values. + + When ``secrets`` is supplied it is treated as a complete, precomputed snapshot; + ``codex_home`` is intentionally ignored in that mode. + """ + + values = known_secret_values(codex_home=codex_home) if secrets is None else secrets + known: Iterable[str] = sorted(values, key=len, reverse=True) + for secret in known: + value = value.replace(secret, REDACTED) + return value + + +def is_sensitive_key(key: str) -> bool: + """Return whether a key name conventionally contains secret material.""" + + folded = "".join(character for character in key.casefold() if character.isalnum()) + return any(part in folded for part in SENSITIVE_KEY_COMPACT_PARTS) + + +def _codex_auth_secrets(*, codex_home: Path | None = None) -> frozenset[str]: + root = codex_home if codex_home is not None else Path(os.getenv("CODEX_HOME", str(Path.home() / ".codex"))) + auth_path = root.expanduser() / "auth.json" + try: + stat = auth_path.stat() + except OSError: + return frozenset() + fingerprint = (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns) + return _cached_codex_auth_secrets(str(auth_path), fingerprint) + + +@lru_cache(maxsize=8) +def _cached_codex_auth_secrets( + auth_path: str, + fingerprint: tuple[int, int, int, int, int], +) -> frozenset[str]: + """Read Codex credentials once for each observed auth-file version.""" + + del fingerprint + try: + auth = json.loads(Path(auth_path).read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return frozenset() + return frozenset(_sensitive_values(auth)) + + +def _sensitive_values(value: Any, *, sensitive: bool = False) -> set[str]: + if isinstance(value, Mapping): + secrets: set[str] = set() + for key, item in value.items(): + secrets.update(_sensitive_values(item, sensitive=sensitive or is_sensitive_key(str(key)))) + return secrets + if isinstance(value, list | tuple): + secrets = set() + for item in value: + secrets.update(_sensitive_values(item, sensitive=sensitive)) + return secrets + if sensitive and isinstance(value, str) and len(value) >= 8: + return {value} + return set() diff --git a/src/powercontext/server/app.py b/src/powercontext/server/app.py index 7fd165c609..e568fe36d1 100644 --- a/src/powercontext/server/app.py +++ b/src/powercontext/server/app.py @@ -142,6 +142,56 @@ TopicMemoryRetryResult as RuntimeTopicMemoryRetryResult, ) from powercontext.builtin.artifacts.topic_memory.processing import TopicMemoryWorkBlock as RuntimeTopicMemoryWorkBlock +from powercontext.builtin.authz import ( + AccessAction, + AccessAuditContext, + AccessAuditEvent, + AccessBinding, + AccessBindingNotFoundError, + AccessBindingState, + AccessConflictError, + AccessControlError, + AccessControlService, + AccessDecision, + AccessDeniedError, + AccessIdentityRequiredError, + AccessInvalidRequestError, + AccessResourceType, + AccessRole, + AccessSubjectRef, + AccessUnavailableError, + AuditSearchRequest, + AuthorizedResourceFilter, + BindingSearchRequest, + CreateBinding, + GroupRef, + MemoryEntrySelector, + PrincipalRef, + ReplaceBinding, + ResourceRef, + access_control_for_mode, + bounded_idempotency_key, +) +from powercontext.builtin.authz.dream import principal_identity +from powercontext.builtin.authz.models import ( + ROLE_ACTIONS, + ROLE_CARDINALITIES, + ROLE_RESOURCE_TYPES, + ROLE_SUBJECT_TYPES, + HandoffReceiptIdentity, +) +from powercontext.builtin.authz.owner_recovery import ( + flush_owner_writes, + owner_recovery_available, + owner_recovery_session, + owner_write_access, +) +from powercontext.builtin.authz.profiles import ( + ARTIFACT_FAMILY_PROFILES, + artifact_family_profile, + register_custom_artifact_access_family, +) +from powercontext.builtin.authz.service import _require_allowed from powercontext.builtin.catalog_changes.models import CatalogChangeCandidate as RuntimeTagCandidate from powercontext.builtin.code.application import CodeApplication from powercontext.builtin.code.errors import CodeError @@ -859,62 +909,13 @@ from powercontext.server.atomic_memory import add_atomic_memory_routes from powercontext.server.atomic_memory import record_response as atomic_record_response from powercontext.server.authentication import AuthenticationProvider -from powercontext.server.authz import ( - AccessAction, - AccessAuditContext, - AccessAuditEvent, - AccessBinding, - AccessBindingNotFoundError, - AccessBindingState, - AccessConflictError, - AccessControlError, - AccessControlService, - AccessDecision, - AccessDeniedError, - AccessIdentityRequiredError, - AccessInvalidRequestError, - AccessResourceType, - AccessRole, - AccessSubjectRef, - AccessUnavailableError, - AuditSearchRequest, - AuthorizedResourceFilter, - BindingSearchRequest, - CreateBinding, - GroupRef, - MemoryEntrySelector, - PrincipalRef, - ReplaceBinding, - ResourceRef, - access_control_for_mode, - bounded_idempotency_key, -) -from powercontext.server.authz.models import ( - ROLE_ACTIONS, - ROLE_CARDINALITIES, - ROLE_RESOURCE_TYPES, - ROLE_SUBJECT_TYPES, - HandoffReceiptIdentity, -) -from powercontext.server.authz.owner_recovery import ( - flush_owner_writes, - owner_recovery_available, - owner_recovery_session, - owner_write_access, -) -from powercontext.server.authz.profiles import ( - ARTIFACT_FAMILY_PROFILES, - artifact_family_profile, - register_custom_artifact_access_family, -) -from powercontext.server.authz.service import _require_allowed from powercontext.server.context import ( current_authentication, current_principal, current_request_id, is_internal_bridge, ) -from powercontext.server.dream_access import DreamAccess, principal_identity +from powercontext.server.dream_access import DreamAccess from powercontext.server.dream_compatibility import ( LEGACY_DREAM_OPERATIONS, DreamContractMiddleware, diff --git a/src/powercontext/server/artifact_plugins.py b/src/powercontext/server/artifact_plugins.py index 04fb4f4b19..2e90df2629 100644 --- a/src/powercontext/server/artifact_plugins.py +++ b/src/powercontext/server/artifact_plugins.py @@ -31,6 +31,7 @@ from powercontext._logging import log_safely from powercontext.builtin.artifact_plugin_validation import validate_plugin +from powercontext.builtin.authz.profiles import ARTIFACT_FAMILY_PROFILES, register_custom_artifact_access_family from powercontext.builtin.dream.bindings import DREAM_BINDINGS from powercontext.builtin.persistence.artifact_indexes import ArtifactIndexBuilder from powercontext.builtin.persistence.database import AsyncDatabase @@ -65,7 +66,6 @@ EnableArtifactPluginResult, ReloadArtifactPluginRequest, ) -from powercontext.server.authz.profiles import ARTIFACT_FAMILY_PROFILES, register_custom_artifact_access_family _STABLE_PHASES = frozenset({"enabled", "disabled", "unloaded", "failed"}) _STATES = ARTIFACT_PROCESSING_BINDING_STATES_TABLE diff --git a/src/powercontext/server/authentication.py b/src/powercontext/server/authentication.py index 40c0b06043..d677a56e9e 100644 --- a/src/powercontext/server/authentication.py +++ b/src/powercontext/server/authentication.py @@ -21,7 +21,7 @@ from secrets import compare_digest from typing import Any, Protocol -from powercontext.server.authz import GroupRef, PrincipalRef +from powercontext.builtin.authz import GroupRef, PrincipalRef _MAX_AUTHENTICATED_GROUPS = 100 diff --git a/src/powercontext/server/cli.py b/src/powercontext/server/cli.py index 1be081ef21..5d1ab89b4c 100644 --- a/src/powercontext/server/cli.py +++ b/src/powercontext/server/cli.py @@ -32,6 +32,9 @@ from sqlalchemy.exc import OperationalError from typing_extensions import override +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.owner_recovery import OwnerRecovery from powercontext.builtin.persistence.bootstrap import ( DatabaseAccessError, DatabaseCreationError, @@ -56,14 +59,9 @@ from powercontext.builtin.runtime.composition import _embedding_models, open_builtin_runtime from powercontext.builtin.runtime.config import BuiltinConfig from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest -from powercontext.cli.env_file import environment_context -from powercontext.cli.inference_notice import write_inference_capability_notice -from powercontext.cli.observability_notice import write_observability_notice +from powercontext.env_file import environment_context from powercontext.server import database_migration from powercontext.server.app import access_readiness_checks -from powercontext.server.authz import PrincipalRef -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.owner_recovery import OwnerRecovery from powercontext.server.background_metrics import serve_background_metrics from powercontext.server.configuration import ( ServerConfigurationError, @@ -73,8 +71,10 @@ from powercontext.server.database_migration import app as database_migration_app from powercontext.server.factory import _ServerReadinessProbe, create_background_metrics_app, create_server_app from powercontext.server.identity import open_server_identity_repository +from powercontext.server.inference_notice import write_inference_capability_notice from powercontext.server.logging import configure_server_logging, shutdown_server_logging, worker_logging from powercontext.server.metrics import ServerMetrics +from powercontext.server.observability_notice import write_observability_notice from powercontext.server.ownership import ( apply_ownership_migration, ownership_report, diff --git a/src/powercontext/server/configuration.py b/src/powercontext/server/configuration.py index 9848c6dcf5..15f34fe4b0 100644 --- a/src/powercontext/server/configuration.py +++ b/src/powercontext/server/configuration.py @@ -27,7 +27,7 @@ from pydantic_settings import BaseSettings, EnvSettingsSource, PydanticBaseSettingsSource, SettingsError from typing_extensions import override -from powercontext.cli.env_file import EnvironmentFileError, environment_context, read_environment_file +from powercontext.env_file import EnvironmentFileError, environment_context, read_environment_file from powercontext.paths import POWERCONTEXT_HOME_ENV from powercontext.server.settings import HttpConfig, ServerSettings diff --git a/src/powercontext/server/context.py b/src/powercontext/server/context.py index 873fc08abc..2568a550da 100644 --- a/src/powercontext/server/context.py +++ b/src/powercontext/server/context.py @@ -18,8 +18,8 @@ from contextvars import ContextVar, Token +from powercontext.builtin.authz import PrincipalRef from powercontext.server.authentication import AuthenticationResult -from powercontext.server.authz import PrincipalRef _internal_bridge: ContextVar[bool] = ContextVar("powercontext_internal_bridge", default=False) _request_id: ContextVar[str | None] = ContextVar("powercontext_request_id", default=None) diff --git a/src/powercontext/server/dashboard/api.py b/src/powercontext/server/dashboard/api.py index 659c5b410e..d1be403094 100644 --- a/src/powercontext/server/dashboard/api.py +++ b/src/powercontext/server/dashboard/api.py @@ -29,11 +29,11 @@ from powercontext.artifacts import ArtifactRef from powercontext.builtin.artifacts.topic_memory import TopicMemoryBrowseCursor +from powercontext.builtin.authz import AccessAction, ResourceRef +from powercontext.builtin.authz.service import _require_allowed, access_control_for_mode from powercontext.builtin.runtime.models import GetTopicMemoryRequest from powercontext.errors import ArtifactNotFoundError from powercontext.server import mapping -from powercontext.server.authz import AccessAction, ResourceRef -from powercontext.server.authz.service import _require_allowed, access_control_for_mode from powercontext.server.context import current_principal from powercontext.server.dashboard.errors import ReadError as ReadError from powercontext.server.dashboard.session import authentication_headers diff --git a/src/powercontext/server/dashboard/page.py b/src/powercontext/server/dashboard/page.py index a05689d75c..3f99cb9fa9 100644 --- a/src/powercontext/server/dashboard/page.py +++ b/src/powercontext/server/dashboard/page.py @@ -14,10 +14,10 @@ import asyncio from contextlib import asynccontextmanager, nullcontext +from powercontext.builtin.authz import AccessAction, AccessDeniedError, ResourceRef +from powercontext.builtin.authz.service import _require_allowed, access_control_for_mode from powercontext.builtin.scope.errors import ScopeBindingTargetMissingError from powercontext.builtin.sources import validate_scope_id -from powercontext.server.authz import AccessAction, AccessDeniedError, ResourceRef -from powercontext.server.authz.service import _require_allowed, access_control_for_mode from powercontext.server.context import current_principal from powercontext.server.dashboard.content import ( RECORDS, diff --git a/src/powercontext/server/dream_access.py b/src/powercontext/server/dream_access.py index 7a83a8188a..2852fc6bcd 100644 --- a/src/powercontext/server/dream_access.py +++ b/src/powercontext/server/dream_access.py @@ -12,57 +12,30 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Current-principal authorization for durable Dream and Review evidence.""" +"""Bind Dream and Review authorization to the current Server request principal.""" from __future__ import annotations -import json from typing import TYPE_CHECKING, Any -from sqlalchemy.ext.asyncio import AsyncConnection +from typing_extensions import override -from powercontext.artifacts import ArtifactRef +from powercontext.builtin.authz.dream import DreamAuthorization, evidence_resource, principal_identity +from powercontext.builtin.authz.errors import AccessControlError, AccessDeniedError, AccessIdentityRequiredError +from powercontext.builtin.authz.models import AccessAction, ResourceRef +from powercontext.builtin.authz.service import AccessAuditContext from powercontext.builtin.catalog_changes.models import TagDreamTarget -from powercontext.builtin.dream.models import DreamError, DreamRecord -from powercontext.builtin.dream.service import DreamPermission +from powercontext.builtin.dream.models import DreamError from powercontext.builtin.evidence.resolver import EvidenceReference from powercontext.builtin.review.models import Candidate -from powercontext.server.authz.errors import AccessControlError, AccessDeniedError, AccessIdentityRequiredError -from powercontext.server.authz.models import AccessAction, PrincipalRef, ResourceRef -from powercontext.server.authz.service import AccessAuditContext, AccessControlService from powercontext.server.context import current_principal, current_request_id if TYPE_CHECKING: from powercontext.builtin.runtime.application import BuiltinRuntime -def principal_identity(principal: PrincipalRef) -> str: - return json.dumps({"type": principal.type, "id": principal.id}, ensure_ascii=False, separators=(",", ":")) - - -def _principal(identity: str) -> PrincipalRef: - try: - value = json.loads(identity) - except (ValueError, TypeError) as error: - raise DreamError("access_revoked") from error - if not isinstance(value, dict) or set(value) != {"type", "id"}: - raise DreamError("access_revoked") - try: - return PrincipalRef(type=value["type"], id=value["id"]) - except (ValueError, TypeError, AccessControlError) as error: - raise DreamError("access_revoked") from error - - -def _resource(scope_id: str, ref: EvidenceReference | None) -> ResourceRef: - if isinstance(ref, ArtifactRef) and ref.family != "topic-memory": - return ResourceRef.artifact(scope_id, family=ref.family, artifact_id=ref.artifact_id) - # Sources and Topic Memory reads belong to the Scope. - return ResourceRef.scope(scope_id) - - -class DreamAccess: - def __init__(self, access: AccessControlService) -> None: - self.access = access +class DreamAccess(DreamAuthorization): + """Add request-principal Review checks to Dream authorization.""" def bind(self, runtime: BuiltinRuntime) -> None: runtime.configure_evidence_authorization( @@ -76,39 +49,9 @@ def bind(self, runtime: BuiltinRuntime) -> None: review_action=self.review_action, ) - async def authorize( - self, - scope_id: str, - principal_id: str, - permission: DreamPermission, - ref: EvidenceReference | None, - ) -> None: - principal = _principal(principal_id) - resource = _resource(scope_id, ref) - if permission == "contribute": - action = AccessAction.SCOPE_CONTRIBUTE - elif permission in {"write", "write_tags"}: - if isinstance(ref, ArtifactRef) and ref.family in {"prompt", "topic-memory"}: - action, resource = AccessAction.SCOPE_ADMIN, ResourceRef.scope(scope_id) - else: - action = AccessAction.ARTIFACT_WRITE - else: - action = AccessAction.SCOPE_READ if resource == ResourceRef.scope(scope_id) else AccessAction.ARTIFACT_READ - try: - await self.access.require( - principal, - action, - resource, - context=AccessAuditContext( - request_id=current_request_id(), - transport="background", - operation="artifact_dreaming", - ), - ) - except AccessDeniedError as error: - raise DreamError("access_revoked") from error - except AccessControlError as error: - raise DreamError("access_unavailable") from error + @override + def _request_id(self) -> str | None: + return current_request_id() async def review(self, scope_id: str, ref: EvidenceReference) -> None: principal = current_principal() @@ -129,7 +72,7 @@ async def review_many(self, scope_id, refs, connection): raise AccessIdentityRequiredError checks = {} for ref in refs: - resource = _resource(scope_id, ref) + resource = evidence_resource(scope_id, ref) action = AccessAction.SCOPE_READ if resource == ResourceRef.scope(scope_id) else AccessAction.ARTIFACT_READ checks[action, resource.key] = (action, resource) try: @@ -145,41 +88,6 @@ async def review_many(self, scope_id, refs, connection): except AccessControlError as error: raise DreamError("access_unavailable") from error - async def attest_candidate( - self, connection: AsyncConnection, record: DreamRecord, candidate_id: str, family: str - ) -> None: - bound = DreamAccess(self.access.with_connection(connection)) - await bound.authorize(record.run.scope_id, record.principal_id, "contribute", None) - await bound.access.attest_candidate_owner( - scope_id=record.run.scope_id, - candidate_id=candidate_id, - family=family, - proposed_owner=_principal(record.principal_id), - target=None - if record.run.target is None - else ResourceRef.artifact( - record.run.scope_id, family=record.run.target.family, artifact_id=record.run.target.artifact_id - ), - idempotency_key=f"dream-candidate-owner:{record.run.run_id}", - ) - - async def authorize_candidate( - self, connection: AsyncConnection, record: DreamRecord, candidate_id: str, family: str - ) -> None: - bound = DreamAccess(self.access.with_connection(connection)) - await bound.authorize(record.run.scope_id, record.principal_id, "read", record.run.target) - if record.run.operation == "revise_tags" and record.run.tag_target is not None: - await bound.authorize( - record.run.scope_id, - record.principal_id, - "read", - record.run.tag_target.basis_ref, - ) - return - owner = await bound.access.candidate_owner(record.run.scope_id, candidate_id) - if owner is None or owner.proposed_owner != _principal(record.principal_id): - raise DreamError("access_revoked") - async def catalog_action(self, scope_id: str, action: str, target: TagDreamTarget) -> None: principal = current_principal() if principal is None: diff --git a/src/powercontext/server/factory.py b/src/powercontext/server/factory.py index 76d3b88fc3..e578fe16c8 100644 --- a/src/powercontext/server/factory.py +++ b/src/powercontext/server/factory.py @@ -19,6 +19,7 @@ import asyncio import hmac import logging +import warnings from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence from contextlib import AsyncExitStack, asynccontextmanager, nullcontext, suppress from functools import partial @@ -30,25 +31,38 @@ from starlette.middleware import Middleware from powercontext._logging import log_safely -from powercontext.artifacts.search import ArtifactSearchExecutionContext from powercontext.builtin.artifacts.atomic_memory.extraction import AtomicMemoryGenerationPipeline from powercontext.builtin.artifacts.experience import ExperienceCandidatePipeline, ExperienceGenerator from powercontext.builtin.artifacts.handoff import HandoffGenerationPipeline from powercontext.builtin.artifacts.memory import CandidatePipeline from powercontext.builtin.artifacts.profile.service import ProfileGenerator from powercontext.builtin.artifacts.skill import ExternalSkillProvider, SkillGenerator +from powercontext.builtin.authz import ( + AccessAction, + AccessAuditContext, + AccessControlService, + PrincipalRef, + ResourceRef, + access_control_for_mode, + bounded_idempotency_key, +) +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.owner_recovery import ( + OwnerRecovery, + flush_owner_writes, + owner_recovery_session, + owner_write_access, +) +from powercontext.builtin.authz.profiles import register_custom_artifact_access_family +from powercontext.builtin.authz.repository import RelationalAccessRepository from powercontext.builtin.dream.generation import DreamGenerator from powercontext.builtin.inference import EmbeddingModel from powercontext.builtin.persistence.records import RelationalRecordService from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.persistence.tables import ARTIFACT_FAMILY_SCHEMAS_TABLE -from powercontext.builtin.records import BaseOperationNotSupportedError from powercontext.builtin.runtime import ( BuiltinRuntime, - ExperienceIncubationResult, - MemoryFlushResult, ) -from powercontext.builtin.runtime.application import ScheduledExperienceRunner, ScheduledSourceRunner from powercontext.builtin.runtime.composition import open_builtin_runtime from powercontext.builtin.runtime.config import BuiltinConfig from powercontext.builtin.runtime.context_bindings import BindingCodec @@ -72,7 +86,6 @@ ReadinessResponse, ReadinessStatus, ) -from powercontext.paths import default_scheduler_path from powercontext.server.access import HttpAccessLogMiddleware from powercontext.server.app import _bind_evidence_access, access_readiness_checks, create_app from powercontext.server.artifact_plugins import ( @@ -85,25 +98,6 @@ MultiBearerAuthenticationProvider, StaticBearerAuthenticationProvider, ) -from powercontext.server.authz import ( - AccessAction, - AccessAuditContext, - AccessControlService, - CandidateOwnerAttestation, - PrincipalRef, - ResourceRef, - access_control_for_mode, - bounded_idempotency_key, -) -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.owner_recovery import ( - OwnerRecovery, - flush_owner_writes, - owner_recovery_session, - owner_write_access, -) -from powercontext.server.authz.profiles import register_custom_artifact_access_family -from powercontext.server.authz.repository import RelationalAccessRepository from powercontext.server.context import current_principal, current_request_id from powercontext.server.cursor_secret import resolve_cursor_secret from powercontext.server.dashboard import mount_dashboard @@ -175,7 +169,18 @@ def create_server_app( # noqa: C901 access_control: AccessControlService | None = None, authentication_provider: AuthenticationProvider | None = None, ) -> FastAPI: - """Build the Server process and mount MCP when configured.""" + """Build the Server process and mount MCP when configured. + + ``scheduler_path`` is deprecated and ignored. + """ + + if scheduler_path is not None: + warnings.warn( + "scheduler_path is ignored and will be removed; automatic processing is scheduled by the " + "artifact processing supervisor", + DeprecationWarning, + stacklevel=2, + ) resolved = ServerSettings() if settings is None else settings if resolved.dashboard.enabled and (authentication_provider is not None or access_control is not None): @@ -262,11 +267,6 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: # noqa: C901 - shared deployment_id=resolved.access.deployment_id, ) ) - scheduled_source_runner, scheduled_experience_runner = _scheduled_access_runners( - resolved, - active_access_control, - legacy_static_principal=static_principal if legacy_static_admin else None, - ) dream_access = ( DreamAccess(active_access_control) if resolved.access.mode == "enforced" and isinstance(active_access_control, AccessControlService) @@ -282,7 +282,6 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: # noqa: C901 - shared runtime = await resources.enter_async_context( open_builtin_runtime( config, - scheduler_path=default_scheduler_path() if scheduler_path is None else scheduler_path, candidate_pipeline=candidate_pipeline, experience_pipeline=experience_pipeline, experience_generator=experience_generator, @@ -307,8 +306,6 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: # noqa: C901 - shared provider_observer=None if metrics is None else metrics.observe_provider, worker_provider_observer=None if metrics is None else metrics.observe_worker_provider, processing_observer=None if metrics is None else metrics.observe_processing, - scheduled_source_runner=scheduled_source_runner, - scheduled_experience_runner=scheduled_experience_runner, worker_security=worker_security, worker_initializer=logging_bootstrap, worker_entrypoint_wrapper=WorkerTracing( @@ -605,89 +602,6 @@ async def _remove_legacy_topic_owners(access: AccessControlService) -> None: _log_lifecycle("server.topic_owner_cleanup", f"Removed {removed} legacy topic-memory Artifact owner rows") -def _scheduled_access_runners( - settings: ServerSettings, - access: AccessControlService | None, - *, - legacy_static_principal: PrincipalRef | None, -) -> tuple[ScheduledSourceRunner | None, ScheduledExperienceRunner | None]: - source_scheduled = settings.runtime.schedule_seconds is not None - experience_scheduled = settings.runtime.experience_schedule_seconds is not None - if settings.access.mode == "disabled" or not (source_scheduled or experience_scheduled): - return None, None - if access is None: - raise ValueError("scheduled processing in enforced mode requires an Authorization Provider") # noqa: TRY003 - principal = _scheduled_principal(settings, legacy_static_principal=legacy_static_principal) - - async def process_sources(scope_id: str, runtime: BuiltinRuntime) -> MemoryFlushResult: - context = AccessAuditContext(transport="background", operation="process_source_window") - await access.bootstrap_static_scope(principal, scope_id, context=context) - await access.require(principal, AccessAction.SCOPE_CONTRIBUTE, ResourceRef.scope(scope_id), context=context) - if runtime.atomic_memory is None: - raise BaseOperationNotSupportedError("artifact_family", "atomic-memory", "runtime application") - return await runtime.atomic_memory.for_scope(scope_id).flush( - context=ArtifactSearchExecutionContext(principal=principal, access=access, audit=context), - ) - - async def incubate_experience(scope_id: str, runtime: BuiltinRuntime) -> ExperienceIncubationResult: - context = AccessAuditContext(transport="background", operation="incubate_experience_candidates") - await access.bootstrap_static_scope(principal, scope_id, context=context) - await access.require(principal, AccessAction.SCOPE_CONTRIBUTE, ResourceRef.scope(scope_id), context=context) - - async def on_commit(connection, candidates): - bound = owner_write_access(access, connection) - await bound.attest_candidate_owners( - tuple( - CandidateOwnerAttestation( - scope_id=scope_id, - candidate_id=candidate.candidate_id, - family="experience", - proposed_owner=principal, - target=None - if candidate.target is None - else ResourceRef.artifact( - scope_id, - family=candidate.target.family, - artifact_id=candidate.target.artifact_id, - ), - idempotency_key=bounded_idempotency_key( - "background-candidate-owner", scope_id, candidate.candidate_id - ), - ) - for candidate in candidates - ) - ) - - if runtime.owner_write_database is not None: - recovery = ( - None - if access.supports_write_transaction(runtime.owner_write_database.engine) - else OwnerRecovery(runtime.owner_write_database, access) - ) - async with owner_recovery_session(recovery): - return await runtime.experience.for_scope(scope_id).incubate(on_commit=on_commit) - result = await runtime.experience.for_scope(scope_id).incubate() - await access.attest_candidate_owners( - tuple( - CandidateOwnerAttestation( - scope_id=scope_id, - candidate_id=candidate_id, - family="experience", - proposed_owner=principal, - target=None, - idempotency_key=bounded_idempotency_key("background-candidate-owner", scope_id, candidate_id), - ) - for candidate_id in result.candidate_ids - ) - ) - return result - - return ( - process_sources if source_scheduled else None, - incubate_experience if experience_scheduled else None, - ) - - def _scheduled_profile_runner(settings, access, *, enabled, legacy_static_principal): if settings.access.mode == "disabled" or not enabled: return None diff --git a/src/powercontext/cli/inference_notice.py b/src/powercontext/server/inference_notice.py similarity index 100% rename from src/powercontext/cli/inference_notice.py rename to src/powercontext/server/inference_notice.py diff --git a/src/powercontext/server/middleware.py b/src/powercontext/server/middleware.py index 1f09045518..a9d659acfd 100644 --- a/src/powercontext/server/middleware.py +++ b/src/powercontext/server/middleware.py @@ -20,6 +20,7 @@ from starlette.responses import JSONResponse from starlette.types import ASGIApp, Receive, Scope, Send +from powercontext.builtin.authz import PrincipalRef from powercontext.http import ErrorDetail, ErrorResponse from powercontext.server.authentication import ( AuthenticationProvider, @@ -28,7 +29,6 @@ AuthenticationUnavailableError, StaticBearerAuthenticationProvider, ) -from powercontext.server.authz import PrincipalRef from powercontext.server.context import bind_authentication, is_internal_bridge, reset_authentication from powercontext.server.dashboard.session import authentication_headers, login_response diff --git a/src/powercontext/cli/observability_notice.py b/src/powercontext/server/observability_notice.py similarity index 100% rename from src/powercontext/cli/observability_notice.py rename to src/powercontext/server/observability_notice.py diff --git a/src/powercontext/server/ownership.py b/src/powercontext/server/ownership.py index 9282c95a52..0292c36a1d 100644 --- a/src/powercontext/server/ownership.py +++ b/src/powercontext/server/ownership.py @@ -29,7 +29,7 @@ from hashlib import sha256 from typing import TYPE_CHECKING, Literal -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAction, AccessAuditContext, AccessConflictError, @@ -39,14 +39,14 @@ ResourceRef, bounded_idempotency_key, ) -from powercontext.server.authz.models import MemoryEntrySelector -from powercontext.server.authz.owner_recovery import flush_owner_writes, owner_recovery_session, owner_write_access +from powercontext.builtin.authz.models import MemoryEntrySelector +from powercontext.builtin.authz.owner_recovery import flush_owner_writes, owner_recovery_session, owner_write_access if TYPE_CHECKING: + from powercontext.builtin.authz.owner_recovery import OwnerCommit, OwnerRecovery + from powercontext.builtin.authz.service import AccessControlService from powercontext.builtin.runtime import BuiltinRuntime from powercontext.server.app import ServerApplication - from powercontext.server.authz.owner_recovery import OwnerCommit, OwnerRecovery - from powercontext.server.authz.service import AccessControlService Application = ServerApplication | BuiltinRuntime diff --git a/src/powercontext/server/processing_security.py b/src/powercontext/server/processing_security.py index c20edd5457..e3893cab16 100644 --- a/src/powercontext/server/processing_security.py +++ b/src/powercontext/server/processing_security.py @@ -12,46 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Reconstruct Server authorization inside a processing child. - -Runtime-only SDK users do not import or require this adapter. The serialized -identity is resolved from trusted deployment settings, never from model output. -""" +"""Serialize the processing-child authorization identity from Server settings.""" from __future__ import annotations -from collections.abc import AsyncIterator, Sequence -from contextlib import asynccontextmanager -from typing import Any, Literal - -from pydantic import BaseModel, ConfigDict, Field -from sqlalchemy.ext.asyncio import AsyncConnection +from typing import Any -from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.authz import AccessControlService, PrincipalRef +from powercontext.builtin.authz.repository import RelationalAccessRepository +from powercontext.builtin.authz.service import BuiltinAuthorizationProvider +from powercontext.builtin.authz.worker import WorkerSecuritySpec from powercontext.builtin.runtime.composition import BuiltinConfigurationError -from powercontext.server.authz import ( - AccessAction, - AccessAuditContext, - AccessControlService, - CandidateOwnerAttestation, - PrincipalRef, - ResourceRef, - bounded_idempotency_key, -) -from powercontext.server.authz.repository import RelationalAccessRepository -from powercontext.server.authz.service import BuiltinAuthorizationProvider from powercontext.server.settings import ServerSettings -class WorkerSecuritySpec(BaseModel): - model_config = ConfigDict(extra="forbid") - - provider: Literal["builtin"] = "builtin" - principal: PrincipalRef = Field(repr=False) - deployment_id: str - static_preset: bool = False - - def build_worker_security( settings: ServerSettings, access: AccessControlService | None, @@ -88,113 +62,3 @@ def build_worker_security( deployment_id=settings.access.deployment_id, static_preset=principal == legacy_static_principal, ).model_dump(mode="json") - - -class WorkerSecurity: - def __init__(self, access: AccessControlService, principal: PrincipalRef) -> None: - self.access = access - self.principal = principal - self.context = AccessAuditContext(transport="background", operation="artifact_processing") - - async def authorize_scope(self, scope_id: str) -> None: - await self._authorize_scope(self.access, scope_id) - - async def _authorize_scope(self, access: AccessControlService, scope_id: str) -> None: - await access.bootstrap_static_scope(self.principal, scope_id, context=self.context) - await access.require( - self.principal, AccessAction.SCOPE_CONTRIBUTE, ResourceRef.scope(scope_id), context=self.context - ) - - async def authorize_transaction(self, connection: AsyncConnection, scope_id: str) -> None: - await self._authorize_scope(self.access.with_connection(connection), scope_id) - - async def experience_commit(self, connection: AsyncConnection, candidates: Sequence[Any], *, scope_id: str) -> None: - bound = self.access.with_connection(connection) - await bound.attest_candidate_owners( - tuple( - CandidateOwnerAttestation( - scope_id=scope_id, - candidate_id=candidate.candidate_id, - family="experience", - proposed_owner=self.principal, - target=None, - idempotency_key=bounded_idempotency_key( - "background-candidate-owner", scope_id, candidate.candidate_id - ), - ) - for candidate in candidates - ) - ) - - async def authorize_profile(self, scope_id: str, current: Any) -> None: - if current is not None: - await self.access.require( - self.principal, - AccessAction.ARTIFACT_WRITE, - ResourceRef.artifact(scope_id, family="profile", artifact_id="profile"), - context=self.context, - ) - - async def authorize_profile_commit(self, connection: AsyncConnection, current: Any, *, scope_id: str) -> None: - if current is not None: - await self.access.with_connection(connection).require( - self.principal, - AccessAction.ARTIFACT_WRITE, - ResourceRef.artifact(scope_id, family="profile", artifact_id="profile"), - context=self.context, - ) - - async def profile_commit( - self, connection: AsyncConnection, artifact: Any, candidate: Any, *, scope_id: str - ) -> None: - bound = self.access.with_connection(connection) - resource = ResourceRef.artifact(scope_id, family="profile", artifact_id="profile") - if artifact is not None: - if await bound.artifact_owner(resource) is None: - await bound.establish_artifact_owner( - resource, - self.principal, - idempotency_key=bounded_idempotency_key("profile-owner", scope_id), - context=self.context, - ) - else: - await bound.require(self.principal, AccessAction.ARTIFACT_WRITE, resource, context=self.context) - if candidate is not None: - if candidate.target is not None: - await bound.require(self.principal, AccessAction.ARTIFACT_WRITE, resource, context=self.context) - await bound.attest_candidate_owner( - scope_id=scope_id, - candidate_id=candidate.candidate_id, - family="profile", - proposed_owner=self.principal, - target=None if candidate.target is None else resource, - idempotency_key=bounded_idempotency_key("candidate-owner", scope_id, candidate.candidate_id), - ) - - async def topic_commit(self, connection: AsyncConnection, scope_id: str, _operations: Sequence[Any]) -> None: - """Authorize one Scope-owned Topic Memory publication. - - Topic Memory is shared Scope knowledge: it registers no Artifact Family - Access Profile and carries no per-topic owner, so its publications are - authorized by Scope authority alone. The batch is accepted unchanged. - """ - await self._authorize_scope(self.access.with_connection(connection), scope_id) - - -@asynccontextmanager -async def open_worker_security( - security: dict[str, Any] | None, database: AsyncDatabase -) -> AsyncIterator[WorkerSecurity | None]: - if security is None: - yield None - return - spec = WorkerSecuritySpec.model_validate(security) - repository = RelationalAccessRepository(database) - access = AccessControlService( - BuiltinAuthorizationProvider(repository, deployment_id=spec.deployment_id), - relationships=repository, - audit=repository, - deployment_id=spec.deployment_id, - static_scope_principal=spec.principal if spec.static_preset else None, - ) - yield WorkerSecurity(access, spec.principal) diff --git a/src/powercontext/service/cli.py b/src/powercontext/service/cli.py index 1639130d17..a002c2363f 100644 --- a/src/powercontext/service/cli.py +++ b/src/powercontext/service/cli.py @@ -23,9 +23,9 @@ import typer -from powercontext.cli.inference_notice import write_inference_capability_notice from powercontext.server import cli as _server_role_dependency from powercontext.server.configuration import ServerConfigurationError, server_settings_context +from powercontext.server.inference_notice import write_inference_capability_notice from powercontext.service.controller import ServiceController from powercontext.service.model import ManagerState, ServiceError, ServiceStatus diff --git a/src/powercontext/service/controller.py b/src/powercontext/service/controller.py index d97b88e04f..c0a89a6dfe 100644 --- a/src/powercontext/service/controller.py +++ b/src/powercontext/service/controller.py @@ -32,7 +32,7 @@ from urllib.parse import urlsplit from uuid import UUID, uuid4 -from powercontext.cli.env_file import environment_context +from powercontext.env_file import environment_context from powercontext.paths import POWERCONTEXT_HOME_ENV, powercontext_data_dir from powercontext.server.configuration import ServerConfigurationError, server_settings_context from powercontext.service.adapters import NativeServiceAdapter, native_service_adapter diff --git a/src/powercontext/service/environment.py b/src/powercontext/service/environment.py index b9d0d07fe6..d5e2a77517 100644 --- a/src/powercontext/service/environment.py +++ b/src/powercontext/service/environment.py @@ -27,7 +27,7 @@ from pathlib import Path from typing import Any -from powercontext.cli.env_file import EnvironmentFileError, parse_environment +from powercontext.env_file import EnvironmentFileError, parse_environment from powercontext.service._windows_command import run_windows_command from powercontext.service.model import EnvironmentFileIdentity diff --git a/src/powercontext/service/launcher.py b/src/powercontext/service/launcher.py index 0709eaad67..181532d4fc 100644 --- a/src/powercontext/service/launcher.py +++ b/src/powercontext/service/launcher.py @@ -25,7 +25,7 @@ from typing import TextIO from urllib.parse import urlsplit -from powercontext.cli.env_file import environment_context +from powercontext.env_file import environment_context from powercontext.server.configuration import ServerConfigurationError, server_settings_context from powercontext.server.settings import ServerLoggingConfig from powercontext.service.environment import ProtectedEnvironmentFileError, load_protected_environment_file diff --git a/src/powercontext/source_management/gateway.py b/src/powercontext/source_management/gateway.py index d460d2e0ee..f6f912ec21 100644 --- a/src/powercontext/source_management/gateway.py +++ b/src/powercontext/source_management/gateway.py @@ -22,10 +22,10 @@ from fastapi import FastAPI, Request from fastapi.responses import JSONResponse +from powercontext.builtin.authz import AccessAction, AccessAuditContext, ResourceRef, access_control_for_mode from powercontext.builtin.runtime.models import CaptureSource from powercontext.http._generated import operations as operations from powercontext.server.authentication import AuthenticationRequest -from powercontext.server.authz import AccessAction, AccessAuditContext, ResourceRef, access_control_for_mode from powercontext.server.context import current_principal from powercontext.source_management.channel import ReverseChannel from powercontext.source_management.models import ( diff --git a/tests/builtin/artifacts/profile/test_scheduler.py b/tests/builtin/artifacts/profile/test_scheduler.py index 72b4cc241c..43556531a6 100644 --- a/tests/builtin/artifacts/profile/test_scheduler.py +++ b/tests/builtin/artifacts/profile/test_scheduler.py @@ -104,22 +104,18 @@ async def run(): await asyncio.sleep(0.02) saved = await runtime.records.for_scope(sid).get_artifact("profile", "profile") assert saved.revision == 1 - assert not (tmp_path / "jobs.db").exists() asyncio.run(run()) -def test_manual_profile_generation_does_not_create_scheduler_when_disabled(tmp_path): +def test_manual_profile_flush_works_without_automatic_processing(tmp_path): class Generator: async def generate(self, value): return "# Manual flush" async def run(): config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'manual.db'}")) - scheduler_path = tmp_path / "jobs.db" - async with open_builtin_runtime( - config, profile_generator=Generator(), scheduler_path=scheduler_path - ) as runtime: + async with open_builtin_runtime(config, profile_generator=Generator()) as runtime: assert runtime.scopes is not None and runtime.profiles is not None sid = ( await runtime.scopes.create(ScopeDraft(title="User", summary="User", idempotency_key="User")) @@ -128,6 +124,5 @@ async def run(): await runtime.records.for_scope(sid).create_source("content", "Chinese") result = await runtime.profiles.flush(sid) assert result.status == "updated" - assert not scheduler_path.exists() asyncio.run(run()) diff --git a/tests/builtin/persistence/test_artifact_storage_lifecycle.py b/tests/builtin/persistence/test_artifact_storage_lifecycle.py index 133afa3075..563527b7cc 100644 --- a/tests/builtin/persistence/test_artifact_storage_lifecycle.py +++ b/tests/builtin/persistence/test_artifact_storage_lifecycle.py @@ -217,7 +217,7 @@ async def server_registration(): mcp=McpConfig(enabled=False), metrics=MetricsConfig(enabled=False), ) - app = create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=settings) async with ( app.router.lifespan_context(app), httpx.AsyncClient( diff --git a/tests/builtin/persistence/test_atomic_memory_startup_legacy_schema.py b/tests/builtin/persistence/test_atomic_memory_startup_legacy_schema.py index f6d22de279..7ba3f3871b 100644 --- a/tests/builtin/persistence/test_atomic_memory_startup_legacy_schema.py +++ b/tests/builtin/persistence/test_atomic_memory_startup_legacy_schema.py @@ -27,14 +27,14 @@ import rfc8785 from sqlalchemy import text +from powercontext.builtin.authz import ArtifactOwnerRelation, MemoryEntrySelector, PrincipalRef, ResourceRef +from powercontext.builtin.authz.repository import ACCESS_TABLES, RelationalAccessRepository from powercontext.builtin.persistence.migrations.atomic_memory_v1 import AtomicMemoryMigrationError from powercontext.builtin.persistence.processing_migration import bootstrap_processing_schema from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.persistence.tables import BUILTIN_TABLES from powercontext.builtin.runtime import BuiltinConfig, open_builtin_contexts from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest -from powercontext.server.authz import ArtifactOwnerRelation, MemoryEntrySelector, PrincipalRef, ResourceRef -from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository from tests.legacy_memory import add_legacy_citation_columns diff --git a/tests/builtin/persistence/test_full_server_migrations.py b/tests/builtin/persistence/test_full_server_migrations.py index 74af6392ae..066c748d1f 100644 --- a/tests/builtin/persistence/test_full_server_migrations.py +++ b/tests/builtin/persistence/test_full_server_migrations.py @@ -271,7 +271,7 @@ def test_code_with_separate_cache_upgrades_and_reopens_server(source, tmp_path): assert runner.plan().source_revision == "s1300" apply(runner) assert runner.verify().readiness_scope == "server" - app = create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=settings) with TestClient(app) as client: assert client.get("/health/ready").status_code == 200 response = client.get("/v1/scopes") diff --git a/tests/builtin/persistence/test_partial_maintenance_profile_admission.py b/tests/builtin/persistence/test_partial_maintenance_profile_admission.py index d7d88c8097..efdc097a93 100644 --- a/tests/builtin/persistence/test_partial_maintenance_profile_admission.py +++ b/tests/builtin/persistence/test_partial_maintenance_profile_admission.py @@ -37,7 +37,6 @@ def test_missing_configuration_cannot_admit_partial_vector_maintenance(tmp_path, create_server_app( settings=settings, embedding_model=ControlledEmbedding(profile), - scheduler_path=tmp_path / "scheduler", ) ) as client: response = client.post( diff --git a/tests/builtin/persistence/test_release140_server_migrations.py b/tests/builtin/persistence/test_release140_server_migrations.py index fd95f653eb..450d1acecc 100644 --- a/tests/builtin/persistence/test_release140_server_migrations.py +++ b/tests/builtin/persistence/test_release140_server_migrations.py @@ -176,7 +176,6 @@ def test_release140_four_sqlite_configurations_preserve_candidates_and_serve(tmp app = create_server_app( settings=settings, embedding_model=ControlledEmbedding(embedding) if embedding is not None else None, - scheduler_path=tmp_path / "scheduler", ) with TestClient(app) as client: assert client.get("/health/ready").status_code == 200 @@ -377,7 +376,6 @@ def connect(): app = create_server_app( settings=settings, embedding_model=ControlledEmbedding(embedding) if embedding is not None else None, - scheduler_path=tmp_path / "scheduler", ) with TestClient(app) as client: response = client.get("/v1/scopes/scope/artifacts/atomic-memory/historical-memory/revisions/1") diff --git a/tests/builtin/persistence/test_server_vector_migrations.py b/tests/builtin/persistence/test_server_vector_migrations.py index 68b4ca5df3..69dc90dca4 100644 --- a/tests/builtin/persistence/test_server_vector_migrations.py +++ b/tests/builtin/persistence/test_server_vector_migrations.py @@ -144,9 +144,7 @@ def test_vector_upgrade_preserves_history_shape_and_matches_fresh_storage(tmp_pa settings = ServerSettings( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{database}"), mcp=McpConfig(enabled=False) ) - app = create_server_app( - settings=settings, embedding_model=ControlledEmbedding(embedding), scheduler_path=tmp_path / "scheduler" - ) + app = create_server_app(settings=settings, embedding_model=ControlledEmbedding(embedding)) with TestClient(app) as client: remembered = client.post( "/v1/memory/remember", @@ -237,9 +235,7 @@ def test_vector_readiness_rejects_incomplete_atomic_projections(tmp_path, damage settings = ServerSettings( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{database}"), mcp=McpConfig(enabled=False) ) - app = create_server_app( - settings=settings, embedding_model=ControlledEmbedding(embedding), scheduler_path=tmp_path / "scheduler" - ) + app = create_server_app(settings=settings, embedding_model=ControlledEmbedding(embedding)) with TestClient(app) as client: remembered = client.post( "/v1/memory/remember", @@ -256,9 +252,7 @@ def test_vector_readiness_rejects_incomplete_atomic_projections(tmp_path, damage for inspect_state in (runner.plan, runner.verify): with pytest.raises(MigrationError, match="projection_verification_failed"): inspect_state() - app = create_server_app( - settings=settings, embedding_model=ControlledEmbedding(embedding), scheduler_path=tmp_path / "scheduler" - ) + app = create_server_app(settings=settings, embedding_model=ControlledEmbedding(embedding)) with pytest.raises(MigrationError, match="projection_verification_failed"), TestClient(app): pytest.fail("Incomplete projections must block vector Server startup") assert database.read_bytes() == original diff --git a/tests/builtin/runtime/test_artifact_read_context.py b/tests/builtin/runtime/test_artifact_read_context.py index 15cc39ac4f..578217c2a6 100644 --- a/tests/builtin/runtime/test_artifact_read_context.py +++ b/tests/builtin/runtime/test_artifact_read_context.py @@ -28,6 +28,21 @@ from powercontext.artifacts.search import ArtifactSearchUnsupported from powercontext.builtin.artifacts.profile.models import Profile, ProfileContent, ProfileGeneration from powercontext.builtin.artifacts.topic_memory.models import TopicMemory, TopicMemoryContent +from powercontext.builtin.authz import ( + AccessAuditContext, + AccessControlService, + AccessDecision, + AccessDeniedError, + AccessRole, + BuiltinAuthorizationProvider, + CreateBinding, + PrincipalRef, + ResourceRef, +) +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.profiles import register_custom_artifact_access_family +from powercontext.builtin.authz.repository import RelationalAccessRepository +from powercontext.builtin.authz.worker import WorkerSecurity from powercontext.builtin.persistence.artifact_indexes import ArtifactIndexBuilder from powercontext.builtin.persistence.artifacts import ArtifactRepository, RepositoryArtifactDraft from powercontext.builtin.persistence.custom_artifacts import ( @@ -47,21 +62,6 @@ from powercontext.builtin.runtime.processing_contracts import ArtifactProcessingWorkAssignment from powercontext.builtin.runtime.processing_execution import ScopeInvocation from powercontext.builtin.sources import BUILTIN_SOURCE_REGISTRY -from powercontext.server.authz import ( - AccessAuditContext, - AccessControlService, - AccessDecision, - AccessDeniedError, - AccessRole, - BuiltinAuthorizationProvider, - CreateBinding, - PrincipalRef, - ResourceRef, -) -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.profiles import register_custom_artifact_access_family -from powercontext.server.authz.repository import RelationalAccessRepository -from powercontext.server.processing_security import WorkerSecurity class FilteredProvider(BuiltinAuthorizationProvider): diff --git a/tests/builtin/runtime/test_context_reuse.py b/tests/builtin/runtime/test_context_reuse.py index eb3b1f6463..ec007022cb 100644 --- a/tests/builtin/runtime/test_context_reuse.py +++ b/tests/builtin/runtime/test_context_reuse.py @@ -214,7 +214,7 @@ async def scenario(): def test_denied_revalidation_reveals_nothing_about_changed_roots(tmp_path): from powercontext.artifacts.search import ArtifactSearchExecutionContext - from powercontext.server.authz import AccessDeniedError, PrincipalRef + from powercontext.builtin.authz import AccessDeniedError, PrincipalRef from tests.e2e.test_access_control_regressions import AUDIT, _grant, _server from tests.e2e.test_access_control_regressions import _scope as http_scope from tests.e2e.test_atomic_memory_prepare_lifecycle import _change, _remember, _revoke @@ -552,7 +552,7 @@ async def scenario(): def test_reuse_rechecks_current_scope_authority_even_when_artifact_grant_remains(tmp_path): from powercontext.artifacts.search import ArtifactSearchExecutionContext - from powercontext.server.authz import AccessDeniedError, PrincipalRef + from powercontext.builtin.authz import AccessDeniedError, PrincipalRef from tests.e2e.test_access_control_regressions import AUDIT, _grant, _server from tests.e2e.test_access_control_regressions import _scope as http_scope from tests.e2e.test_atomic_memory_prepare_lifecycle import _remember, _revoke @@ -593,8 +593,8 @@ async def scenario(): @pytest.mark.parametrize("mutation", ["forget", "revoke"]) def test_reuse_revalidation_keeps_authority_and_evidence_in_one_snapshot(tmp_path, monkeypatch, mutation): from powercontext.artifacts.search import ArtifactSearchExecutionContext + from powercontext.builtin.authz import AccessDeniedError, PrincipalRef from powercontext.builtin.runtime.atomic_memory import AtomicMemoryAccess - from powercontext.server.authz import AccessDeniedError, PrincipalRef from tests.e2e.test_access_control_regressions import AUDIT, _grant, _server from tests.e2e.test_access_control_regressions import _scope as http_scope from tests.e2e.test_atomic_memory_prepare_lifecycle import _change, _finish_read, _Pause, _remember, _revoke diff --git a/tests/builtin/runtime/test_experience_incubation.py b/tests/builtin/runtime/test_experience_incubation.py index 6c622576ff..77a46cd70d 100644 --- a/tests/builtin/runtime/test_experience_incubation.py +++ b/tests/builtin/runtime/test_experience_incubation.py @@ -269,7 +269,6 @@ async def scenario() -> None: database=SQLiteConfig(), runtime=RuntimeConfig(experience_schedule_seconds=60), ), - scheduler_path=tmp_path / "scheduler.db", ): pass diff --git a/tests/builtin/runtime/test_family_processing.py b/tests/builtin/runtime/test_family_processing.py index 63d1762b66..f6e31328f1 100644 --- a/tests/builtin/runtime/test_family_processing.py +++ b/tests/builtin/runtime/test_family_processing.py @@ -25,6 +25,9 @@ from powercontext.builtin.artifacts.atomic_memory.extraction import AtomicMemoryCandidate, AtomicMemoryExtractionOutput from powercontext.builtin.artifacts.experience import ExperienceCandidateInput, ExperienceContent +from powercontext.builtin.authz import AccessConflictError, AccessDeniedError, PrincipalRef +from powercontext.builtin.authz.repository import ACCESS_OWNERS_TABLE, ACCESS_TABLES +from powercontext.builtin.authz.worker import WorkerSecuritySpec, open_worker_security from powercontext.builtin.inference import InferenceTimeoutError from powercontext.builtin.inference.models import GenerationResult, InferenceUsage from powercontext.builtin.inference.usage import UsageReportingStructuredGenerator @@ -58,9 +61,6 @@ from powercontext.builtin.runtime.relational import RelationalContexts from powercontext.builtin.scope import ScopeDraft from powercontext.builtin.sources import SourceCursor -from powercontext.server.authz import AccessConflictError, AccessDeniedError, PrincipalRef -from powercontext.server.authz.repository import ACCESS_OWNERS_TABLE, ACCESS_TABLES -from powercontext.server.processing_security import WorkerSecuritySpec, open_worker_security from powercontext.sources import SourceRef from tests.e2e.dream_support import atomic_memory_pipeline, memory_source_text diff --git a/tests/builtin/runtime/test_processing_composition.py b/tests/builtin/runtime/test_processing_composition.py index ec8aef0613..22f6dc9118 100644 --- a/tests/builtin/runtime/test_processing_composition.py +++ b/tests/builtin/runtime/test_processing_composition.py @@ -110,12 +110,25 @@ async def scenario() -> None: assert marker["phase"] == "complete" assert marker["migration_id"] == "fresh" await connection.execute(insert(SOURCE_JOURNAL_HEADS_TABLE).values(scope_id="project", position=1)) - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.artifact_processing_supervisor is None asyncio.run(scenario()) +def test_runtime_ignores_deprecated_scheduler_path(tmp_path: Path) -> None: + sidecar = tmp_path / "scheduler.db" + + async def scenario() -> None: + config = BuiltinConfig(database=_sqlite(tmp_path / "runtime.db")) + with pytest.warns(DeprecationWarning, match="scheduler_path is ignored"): + async with open_builtin_runtime(config, scheduler_path=sidecar) as runtime: + assert runtime.artifact_processing_supervisor is None + + asyncio.run(scenario()) + assert not sidecar.exists() + + def test_startup_rejects_legacy_dream_manifest_without_rewriting_it(tmp_path: Path) -> None: async def scenario() -> None: database = _sqlite(tmp_path / "pre-dream-bindings.db") @@ -156,7 +169,7 @@ async def scenario() -> None: ) ) with pytest.raises(ProcessingSchemaNotReadyError, match="offline processing migration"): - async with open_builtin_runtime(BuiltinConfig(database=database), scheduler_path=tmp_path / "scheduler.db"): + async with open_builtin_runtime(BuiltinConfig(database=database)): pytest.fail("legacy work must not be accepted as a fresh database") async with ( SQLiteProfile.open(database, tables=SHARED_TABLES) as profile, @@ -188,7 +201,7 @@ async def local_profile(_config, *, tables, _archive_recovery=False): monkeypatch.setattr(composition.OceanBaseProfile, "open", local_profile) config = BuiltinConfig(database=_OCEANBASE, runtime=RuntimeConfig(artifact_processing_role=role)) with pytest.raises(ProcessingSchemaNotReadyError, match="not ready"): - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db"): + async with open_builtin_runtime(config): pytest.fail("split-role startup must reject a partial migration") asyncio.run(scenario()) @@ -222,7 +235,7 @@ async def scenario() -> None: ) changed = config.model_copy(update={"runtime": settings}) with pytest.raises(ProcessingSchemaNotReadyError, match="completed maintenance manifest"): - async with open_builtin_runtime(changed, scheduler_path=tmp_path / "scheduler.db"): + async with open_builtin_runtime(changed): pytest.fail("ownership identity changes require explicit maintenance") asyncio.run(scenario()) @@ -329,7 +342,7 @@ async def scenario() -> None: inference=InferenceConfig(generation_model="test"), runtime=RuntimeConfig(artifact_processing_supervisor_mode=mode), ) - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: group = runtime.artifact_processing_supervisor assert group is not None assert group.status == ArtifactProcessingSupervisorStatus.LEADER diff --git a/tests/builtin/runtime/test_processing_source_registry.py b/tests/builtin/runtime/test_processing_source_registry.py index 7468f52343..5a9a4a5c60 100644 --- a/tests/builtin/runtime/test_processing_source_registry.py +++ b/tests/builtin/runtime/test_processing_source_registry.py @@ -60,9 +60,7 @@ async def scenario(): ) # Schedules are disabled, but explicit requests would still spawn children. with pytest.raises(BuiltinConfigurationError, match="built-in Source definitions"): - async with open_builtin_runtime( - config, source_registry=_custom_registry(), scheduler_path=tmp_path / "scheduler.db" - ): + async with open_builtin_runtime(config, source_registry=_custom_registry()): pytest.fail("unsupported child Source capabilities must fail before accepting work") launcher.assert_not_called() # A configuration rejection must not freeze a completed deployment @@ -71,9 +69,7 @@ async def scenario(): corrected = config.model_copy( update={"runtime": RuntimeConfig(artifact_processing_families=(), artifact_processing_supervisor_mode=mode)} ) - async with open_builtin_runtime( - corrected, source_registry=_custom_registry(), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(corrected, source_registry=_custom_registry()) as runtime: context = await runtime._provider.get("project") resolved = await context.sources.resolve(CustomCapture(source_id="custom", value="corrected startup")) stored = await context.sources.add(resolved) @@ -93,9 +89,7 @@ async def scenario(): runtime=RuntimeConfig(artifact_processing_families=()), ) registry = _custom_registry() - async with open_builtin_runtime( - config, source_registry=registry, scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(config, source_registry=registry) as runtime: context = await runtime._provider.get("project") resolved = await context.sources.resolve(CustomCapture(source_id="custom", value="retained typed value")) stored = await context.sources.add(resolved) diff --git a/tests/builtin/runtime/test_profile_automatic_admission.py b/tests/builtin/runtime/test_profile_automatic_admission.py index 2f0b8a438d..7577b54e5d 100644 --- a/tests/builtin/runtime/test_profile_automatic_admission.py +++ b/tests/builtin/runtime/test_profile_automatic_admission.py @@ -24,6 +24,9 @@ import pytest from powercontext.builtin.artifacts.profile.models import PROFILE_SOURCE_WINDOW_BINDING as BINDING +from powercontext.builtin.authz import AccessDeniedError +from powercontext.builtin.authz.repository import ACCESS_TABLES +from powercontext.builtin.authz.worker import open_worker_security from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile @@ -36,9 +39,6 @@ from powercontext.builtin.runtime.family_processing import process_family_invocation from powercontext.builtin.runtime.relational import RelationalContexts from powercontext.builtin.scope import ScopeDraft -from powercontext.server.authz import AccessDeniedError -from powercontext.server.authz.repository import ACCESS_TABLES -from powercontext.server.processing_security import open_worker_security from tests.builtin.runtime.test_family_processing import security_spec from tests.builtin.runtime.test_processing_scheduler import _intent, _Launcher diff --git a/tests/builtin/runtime/test_scheduler.py b/tests/builtin/runtime/test_scheduler.py deleted file mode 100644 index 913d806acc..0000000000 --- a/tests/builtin/runtime/test_scheduler.py +++ /dev/null @@ -1,595 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import asyncio -import json -import logging -import sqlite3 -from collections import Counter -from contextlib import asynccontextmanager -from typing import Any - -import pytest -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.sdk.trace.export import SimpleSpanProcessor -from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter - -from powercontext import PowerContext -from powercontext.builtin.artifacts.atomic_memory.extraction import AtomicMemoryExtractionOutput -from powercontext.builtin.inference import GenerationResult -from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.runtime import ( - BuiltinConfig, - BuiltinRuntime, - CaptureSource, - ExperienceIncubationResult, - MemoryFlushResult, - RuntimeCapabilities, - open_builtin_runtime, -) -from powercontext.builtin.runtime.application import ScheduledSourceProcessor -from powercontext.builtin.runtime.scheduler import ( - EXPERIENCE_INCUBATION_JOB_ID, - SOURCE_WINDOW_JOB_ID, - SchedulerConfigurationError, - SchedulerStateError, - scheduler_database_path, -) -from powercontext.builtin.scope import ScopeDescriptor, ScopeDraft -from powercontext.builtin.sources import SourceCursor -from powercontext.server.context import bind_request_id, current_request_id, reset_request_id -from powercontext.server.logging import OperationalContextFilter -from powercontext.server.tracing import ServerTracing -from tests.e2e.dream_support import atomic_memory_pipeline - - -class _Provider: - def __init__(self, context: PowerContext[Any, Any, Any]) -> None: - self.context = context - - async def get(self, scope_id: str, /) -> PowerContext[Any, Any, Any]: - del scope_id - return self.context - - -class _Scopes: - async def get(self, scope_id: str, /) -> ScopeDescriptor: - return ScopeDescriptor(scope_id=scope_id, title="Scheduled", summary="Scheduled scope", version=1) - - -class _ScheduledTriggers: - def __init__(self, *, source_count: int = 0) -> None: - self.dispatched = asyncio.Event() - self.source_count = source_count - - async def flush(self, *, limit: int, atomic_context=None) -> MemoryFlushResult: - del limit, atomic_context - self.dispatched.set() - return MemoryFlushResult( - previous_cursor=0, - high_watermark=self.source_count, - current_cursor=self.source_count, - source_count=self.source_count, - memory_ref=None, - ) - - async def cursor(self) -> SourceCursor: - return SourceCursor() - - -class _FailingTriggers: - async def flush(self, *, limit: int, atomic_context=None) -> MemoryFlushResult: - del limit, atomic_context - raise RuntimeError("flush failed") # noqa: TRY003 - - async def cursor(self) -> SourceCursor: - return SourceCursor() - - -class _BlockingTriggers: - def __init__(self) -> None: - self.entered = asyncio.Event() - - async def flush(self, *, limit: int, atomic_context=None) -> MemoryFlushResult: - del limit, atomic_context - self.entered.set() - await asyncio.Event().wait() - raise AssertionError("unreachable") - - async def cursor(self) -> SourceCursor: - return SourceCursor() - - -class _ScheduledExperience: - def __init__(self) -> None: - self.dispatched = asyncio.Event() - - async def __call__(self, scope_id: str, limit: int) -> ExperienceIncubationResult: - del scope_id, limit - self.dispatched.set() - return ExperienceIncubationResult( - previous_cursor=0, - high_watermark=1, - current_cursor=1, - source_count=1, - candidate_count=1, - ) - - -class _NoopExperience: - async def __call__(self, scope_id: str, limit: int) -> ExperienceIncubationResult: - del scope_id, limit - return ExperienceIncubationResult( - previous_cursor=0, - high_watermark=0, - current_cursor=0, - source_count=0, - candidate_count=0, - ) - - -class _FailingExperience: - async def __call__(self, scope_id: str, limit: int) -> ExperienceIncubationResult: - del scope_id, limit - raise RuntimeError("incubation failed") # noqa: TRY003 - - -class _BlockingExperience: - def __init__(self) -> None: - self.entered = asyncio.Event() - - async def __call__(self, scope_id: str, limit: int) -> ExperienceIncubationResult: - del scope_id, limit - self.entered.set() - await asyncio.Event().wait() - raise AssertionError("unreachable") - - -async def _scope_ids() -> tuple[str, ...]: - return ("scheduled",) - - -def _runtime( - triggers: object, - *, - scope_ids=_scope_ids, - experience_incubator: ( - _ScheduledExperience | _NoopExperience | _FailingExperience | _BlockingExperience | None - ) = None, - tracing: ServerTracing | None = None, -) -> BuiltinRuntime: - return BuiltinRuntime( - provider=_Provider(PowerContext(sources=object(), artifacts=object(), triggers=triggers)), # type: ignore[arg-type] - capabilities=RuntimeCapabilities(memory_extraction=True, memory_search_modes=("fts",)), - scope_ids=scope_ids, - scope_application=_Scopes(), # ty: ignore[invalid-argument-type] - experience_incubator=experience_incubator, - tracing=tracing, - ) - - -def _tracing() -> tuple[ServerTracing, InMemorySpanExporter]: - exporter = InMemorySpanExporter() - provider = TracerProvider(shutdown_on_exit=False) - provider.add_span_processor(SimpleSpanProcessor(exporter)) - return ServerTracing(provider), exporter - - -def _scope_id_leak(spans) -> str: - return json.dumps( - [{"name": span.name, "attributes": dict(span.attributes or {})} for span in spans], - default=str, - ) - - -def _stored_jobs(database) -> list[tuple[str, float | None]]: - with sqlite3.connect(scheduler_database_path(database)) as connection: - return connection.execute("SELECT id, next_run_time FROM powercontext_scheduler_jobs ORDER BY id").fetchall() - - -def test_scheduler_persists_one_stable_source_window_job(tmp_path) -> None: - async def scenario() -> None: - database = tmp_path / "runtime.db" - first = _runtime(_ScheduledTriggers()) - first.start_scheduler(database, 3_600) - await first.close() - jobs = _stored_jobs(database) - - restored = _runtime(_ScheduledTriggers()) - restored.start_scheduler(database, 3_600) - await restored.close() - - assert jobs == _stored_jobs(database) - assert len(jobs) == 1 - assert jobs[0][0] == SOURCE_WINDOW_JOB_ID - - asyncio.run(scenario()) - - -def test_scheduler_creates_missing_database_parent_directory(tmp_path) -> None: - async def scenario() -> None: - database = tmp_path / "missing" / "nested" / "scheduler.db" - assert not database.parent.exists() - - runtime = _runtime(_ScheduledTriggers()) - try: - runtime.start_scheduler(database, 3_600) - assert database.is_file() - finally: - await runtime.close() - - asyncio.run(scenario()) - - -def test_scheduler_interval_activates_the_source_window_policy(tmp_path) -> None: - async def scenario() -> None: - triggers = _ScheduledTriggers() - runtime = _runtime(triggers) - runtime.start_scheduler(tmp_path / "runtime.db", 0.01) - try: - await asyncio.wait_for(triggers.dispatched.wait(), timeout=2) - finally: - await runtime.close() - - asyncio.run(scenario()) - - -def test_scheduler_interval_activates_experience_incubation(tmp_path) -> None: - async def scenario() -> None: - incubation = _ScheduledExperience() - runtime = _runtime(_ScheduledTriggers(), experience_incubator=incubation) - runtime.start_scheduler( - tmp_path / "runtime.db", - None, - experience_schedule_seconds=0.01, - ) - try: - await asyncio.wait_for(incubation.dispatched.wait(), timeout=2) - finally: - await runtime.close() - - asyncio.run(scenario()) - - -def test_scheduler_persists_and_reconciles_independent_jobs(tmp_path) -> None: - async def scenario() -> None: - database = tmp_path / "runtime.db" - first = _runtime(_ScheduledTriggers(), experience_incubator=_ScheduledExperience()) - first.start_scheduler(database, 3_600, experience_schedule_seconds=7_200) - await first.close() - - assert [job_id for job_id, _ in _stored_jobs(database)] == [ - EXPERIENCE_INCUBATION_JOB_ID, - SOURCE_WINDOW_JOB_ID, - ] - - restored = _runtime(_ScheduledTriggers(), experience_incubator=_ScheduledExperience()) - restored.start_scheduler(database, None, experience_schedule_seconds=7_200) - await restored.close() - - assert [job_id for job_id, _ in _stored_jobs(database)] == [EXPERIENCE_INCUBATION_JOB_ID] - - asyncio.run(scenario()) - - -def test_scheduled_noop_logs_a_bounded_outcome(caplog) -> None: - async def scenario() -> None: - runtime = _runtime(_ScheduledTriggers()) - assert runtime.processor is not None - await runtime.processor.run() - - with caplog.at_level(logging.INFO, logger="powercontext.builtin.runtime.application"): - asyncio.run(scenario()) - - record = next(record for record in caplog.records if record.event == "background.operation.completed") - assert record.operation == "process_source_window" - assert record.outcome == "noop" - assert record.source_count == 0 - assert "scope_id" not in vars(record) - - -def test_scheduled_experience_logs_candidate_count_without_scope(caplog) -> None: - async def scenario() -> None: - runtime = _runtime(_ScheduledTriggers(), experience_incubator=_ScheduledExperience()) - assert runtime.experience_processor is not None - await runtime.experience_processor.run() - - with caplog.at_level(logging.INFO, logger="powercontext.builtin.runtime.application"): - asyncio.run(scenario()) - - record = next(record for record in caplog.records if record.operation == "incubate_experience_candidates") - assert record.outcome == "success" - assert record.source_count == 1 - assert record.candidate_count == 1 - assert "scope_id" not in vars(record) - - -async def _private_scope_ids() -> tuple[str, ...]: - return ("project:private-scheduled-scope",) - - -class _MemoryExtractor: - def __init__(self, *, fail=False): - self.fail = fail - - async def generate(self, request): - if self.fail: - raise RuntimeError("flush failed") # noqa: TRY003 - injected generation failure - return GenerationResult(output=AtomicMemoryExtractionOutput()) - - -@asynccontextmanager -async def _memory_runtime(tmp_path, tracing, *, source_count=0, fail=False): - async with open_builtin_runtime( - BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'tracing.db'}")), - candidate_pipeline=atomic_memory_pipeline(_MemoryExtractor(fail=fail)), - tracing=tracing, - ) as runtime: - assert runtime.scopes is not None - scope = await runtime.scopes.create( - ScopeDraft(title="Private scheduled scope", summary="Scheduled processor trace", idempotency_key="trace") - ) - for position in range(source_count): - await runtime.sources.for_scope(scope.scope_id).capture( - CaptureSource(source_id=str(position), content=f"Fact {position}", metadata={}) - ) - - async def scope_ids(): - return (scope.scope_id,) - - runtime.processor = ScheduledSourceProcessor(runtime, scope_ids) - yield runtime - - -def test_scheduled_processor_records_root_and_flush_spans(tmp_path) -> None: - tracing, exporter = _tracing() - - async def scenario() -> None: - async with _memory_runtime(tmp_path, tracing) as runtime: - assert runtime.processor is not None - await runtime.processor.run() - - asyncio.run(scenario()) - - spans = {span.name: span for span in exporter.get_finished_spans()} - root = spans["scheduled.process_source_window"] - flush = spans["memory.flush"] - assert root.parent is None - assert flush.parent is not None and flush.parent.span_id == root.context.span_id - assert root.attributes is not None - assert root.attributes["powercontext.operation.name"] == "process_source_window" - assert root.attributes["powercontext.operation.unit"] == "background" - assert root.attributes["powercontext.operation.outcome"] == "noop" - assert root.attributes["powercontext.background.source_count"] == 0 - assert flush.attributes is not None - assert flush.attributes["powercontext.operation.unit"] == "stage" - assert flush.attributes["powercontext.operation.outcome"] == "noop" - assert flush.attributes["powercontext.memory.flush.source_count"] == 0 - assert "project:private-scheduled-scope" not in _scope_id_leak(exporter.get_finished_spans()) - - -def test_scheduled_processor_records_success_outcome(tmp_path) -> None: - tracing, exporter = _tracing() - - async def scenario() -> None: - async with _memory_runtime(tmp_path, tracing, source_count=3) as runtime: - assert runtime.processor is not None - await runtime.processor.run() - - asyncio.run(scenario()) - - spans = {span.name: span for span in exporter.get_finished_spans()} - root = spans["scheduled.process_source_window"] - flush = spans["memory.flush"] - assert root.attributes is not None and root.attributes["powercontext.operation.outcome"] == "success" - assert root.attributes["powercontext.background.source_count"] == 3 - assert flush.attributes is not None and flush.attributes["powercontext.operation.outcome"] == "success" - assert flush.attributes["powercontext.memory.flush.source_count"] == 3 - - -def test_scheduled_processor_records_failure_and_swallows_error(tmp_path) -> None: - tracing, exporter = _tracing() - - async def scenario() -> None: - async with _memory_runtime(tmp_path, tracing, source_count=1, fail=True) as runtime: - assert runtime.processor is not None - await runtime.processor.run() - - asyncio.run(scenario()) - - spans = {span.name: span for span in exporter.get_finished_spans()} - root = spans["scheduled.process_source_window"] - flush = spans["memory.flush"] - assert root.attributes is not None and root.attributes["powercontext.operation.outcome"] == "failure" - assert flush.attributes is not None and flush.attributes["powercontext.operation.outcome"] == "failure" - - -def test_scheduled_processor_records_cancellation() -> None: - tracing, exporter = _tracing() - - async def scenario() -> None: - triggers = _BlockingTriggers() - runtime = _runtime(triggers, tracing=tracing) - assert runtime.processor is not None - task = asyncio.create_task(runtime.processor.run()) - await triggers.entered.wait() - task.cancel() - with pytest.raises(asyncio.CancelledError): - await task - - asyncio.run(scenario()) - - spans = {span.name: span for span in exporter.get_finished_spans()} - root = spans["scheduled.process_source_window"] - assert root.attributes is not None and root.attributes["powercontext.operation.outcome"] == "cancelled" - - -def test_scheduled_experience_records_root_and_incubation_spans() -> None: - tracing, exporter = _tracing() - - async def scenario() -> None: - runtime = _runtime( - _ScheduledTriggers(), - experience_incubator=_ScheduledExperience(), - tracing=tracing, - scope_ids=_private_scope_ids, - ) - assert runtime.experience_processor is not None - await runtime.experience_processor.run() - - asyncio.run(scenario()) - - spans = {span.name: span for span in exporter.get_finished_spans()} - root = spans["scheduled.incubate_experience_candidates"] - incubation = spans["experience.incubation"] - assert root.parent is None - assert incubation.parent is not None and incubation.parent.span_id == root.context.span_id - assert root.attributes is not None - assert root.attributes["powercontext.operation.name"] == "incubate_experience_candidates" - assert root.attributes["powercontext.operation.unit"] == "background" - assert root.attributes["powercontext.operation.outcome"] == "success" - assert root.attributes["powercontext.background.source_count"] == 1 - assert root.attributes["powercontext.background.candidate_count"] == 1 - assert incubation.attributes is not None - assert incubation.attributes["powercontext.experience.incubation.source_count"] == 1 - assert incubation.attributes["powercontext.experience.incubation.candidate_count"] == 1 - assert "project:private-scheduled-scope" not in _scope_id_leak(exporter.get_finished_spans()) - - -def test_scheduled_experience_records_noop_outcome() -> None: - tracing, exporter = _tracing() - - async def scenario() -> None: - runtime = _runtime(_ScheduledTriggers(), experience_incubator=_NoopExperience(), tracing=tracing) - assert runtime.experience_processor is not None - await runtime.experience_processor.run() - - asyncio.run(scenario()) - - spans = {span.name: span for span in exporter.get_finished_spans()} - root = spans["scheduled.incubate_experience_candidates"] - incubation = spans["experience.incubation"] - assert root.attributes is not None and root.attributes["powercontext.operation.outcome"] == "noop" - assert root.attributes["powercontext.background.source_count"] == 0 - assert root.attributes["powercontext.background.candidate_count"] == 0 - assert incubation.attributes is not None and incubation.attributes["powercontext.operation.outcome"] == "noop" - assert incubation.attributes["powercontext.experience.incubation.source_count"] == 0 - assert incubation.attributes["powercontext.experience.incubation.candidate_count"] == 0 - - -def test_scheduled_experience_records_failure_and_swallows_error() -> None: - tracing, exporter = _tracing() - - async def scenario() -> None: - runtime = _runtime(_ScheduledTriggers(), experience_incubator=_FailingExperience(), tracing=tracing) - assert runtime.experience_processor is not None - await runtime.experience_processor.run() - - asyncio.run(scenario()) - - spans = {span.name: span for span in exporter.get_finished_spans()} - root = spans["scheduled.incubate_experience_candidates"] - incubation = spans["experience.incubation"] - assert root.attributes is not None and root.attributes["powercontext.operation.outcome"] == "failure" - assert incubation.attributes is not None and incubation.attributes["powercontext.operation.outcome"] == "failure" - - -def test_scheduled_experience_records_cancellation() -> None: - tracing, exporter = _tracing() - - async def scenario() -> None: - incubator = _BlockingExperience() - runtime = _runtime(_ScheduledTriggers(), experience_incubator=incubator, tracing=tracing) - assert runtime.experience_processor is not None - task = asyncio.create_task(runtime.experience_processor.run()) - await incubator.entered.wait() - task.cancel() - with pytest.raises(asyncio.CancelledError): - await task - - asyncio.run(scenario()) - - spans = {span.name: span for span in exporter.get_finished_spans()} - root = spans["scheduled.incubate_experience_candidates"] - assert root.attributes is not None and root.attributes["powercontext.operation.outcome"] == "cancelled" - - -def test_scheduler_requires_file_storage_and_one_live_owner(tmp_path) -> None: - async def scenario() -> None: - with pytest.raises(SchedulerConfigurationError): - _runtime(_ScheduledTriggers()).start_scheduler(":memory:", 60) - - database = tmp_path / "runtime.db" - first = _runtime(_ScheduledTriggers()) - second = _runtime(_ScheduledTriggers()) - first.start_scheduler(database, 60) - try: - with pytest.raises(SchedulerStateError): - second.start_scheduler(database, 60) - finally: - await first.close() - - second.start_scheduler(database, 60) - await second.close() - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("family", ["memory", "experience"]) -def test_scheduler_activation_drops_finished_startup_request(tmp_path, caplog, family) -> None: - context_filter = OperationalContextFilter() - caplog.handler.addFilter(context_filter) - caplog.set_level(logging.INFO, logger="powercontext.builtin.runtime.application") - - async def scenario() -> None: - tracing, exporter = _tracing() - triggers = _ScheduledTriggers(source_count=1) - incubation = _ScheduledExperience() - runtime = _runtime(triggers, experience_incubator=incubation, tracing=tracing) - token = bind_request_id("finished-startup-request") - try: - runtime.start_scheduler( - tmp_path / "request-context.db", - 0.02 if family == "memory" else None, - experience_schedule_seconds=0.02 if family == "experience" else None, - ) - finally: - reset_request_id(token) - assert current_request_id() is None - try: - dispatched = triggers.dispatched if family == "memory" else incubation.dispatched - # Exercise multiple activations without assuming how many run before shutdown. - for _ in range(2): - await asyncio.wait_for(dispatched.wait(), timeout=3) - dispatched.clear() - finally: - await runtime.close() - - records = [r for r in caplog.records if getattr(r, "event", None) == "background.operation.completed"] - assert records - assert all(r.outcome == "success" for r in records) - assert all(r.request_id is None for r in records) - roots = [s for s in exporter.get_finished_spans() if s.name.startswith("scheduled.")] - assert len(roots) >= 2 and all(s.parent is None for s in roots) - assert len({s.context.trace_id for s in roots}) == len(roots) - assert Counter((r.trace_id, r.span_id) for r in records) == Counter( - (format(s.context.trace_id, "032x"), format(s.context.span_id, "016x")) for s in roots - ) - - try: - asyncio.run(scenario()) - finally: - caplog.handler.removeFilter(context_filter) diff --git a/tests/builtin/runtime/test_scheduler_selection.py b/tests/builtin/runtime/test_scheduler_selection.py deleted file mode 100644 index 39e6fabbfa..0000000000 --- a/tests/builtin/runtime/test_scheduler_selection.py +++ /dev/null @@ -1,169 +0,0 @@ -# Copyright (c) 2026 OceanBase. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from __future__ import annotations - -import asyncio - -from sqlalchemy import update - -from powercontext.builtin.artifacts.atomic_memory.extraction import AtomicMemoryExtractionOutput -from powercontext.builtin.inference import GenerationResult -from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.persistence.tables import SOURCE_CURSORS_TABLE -from powercontext.builtin.runtime import BuiltinConfig, CaptureSource, RuntimeConfig, open_builtin_runtime -from powercontext.builtin.scope import ScopeDraft -from tests.e2e.dream_support import atomic_memory_pipeline - - -class _Extractor: - async def generate(self, request): - return GenerationResult(output=AtomicMemoryExtractionOutput()) - - -def _config(tmp_path): - return BuiltinConfig( - database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'selection.db'}"), - runtime=RuntimeConfig(source_window_limit=1, atomic_memory_related_mode="fts"), - ) - - -async def _scope(runtime, name): - return await runtime.scopes.create(ScopeDraft(title=name, summary=name, idempotency_key=name)) - - -async def _capture(runtime, scope_id, source_id): - await runtime.sources.for_scope(scope_id).capture( - CaptureSource(source_id=source_id, content=f"Fact {source_id}", metadata={}) - ) - - -def test_buffered_windows_remain_eligible_without_new_sources(tmp_path): - async def scenario(): - async with open_builtin_runtime( - _config(tmp_path), candidate_pipeline=atomic_memory_pipeline(_Extractor()) - ) as runtime: - assert runtime.atomic_memory is not None - assert runtime.processor is not None - scope = await _scope(runtime, "Buffered") - await _capture(runtime, scope.scope_id, "one") - await _capture(runtime, scope.scope_id, "two") - await runtime.processor.run() - assert (await runtime.atomic_memory.for_scope(scope.scope_id).cursor()).sequence == 1 - await runtime.processor.run() - assert (await runtime.atomic_memory.for_scope(scope.scope_id).cursor()).sequence == 2 - - asyncio.run(scenario()) - - -def test_failed_scope_does_not_suppress_peers_or_concurrently_captured_work(tmp_path): - async def scenario(): - entered = asyncio.Event() - release = asyncio.Event() - attempted = [] - - async def runner(scope_id, runtime): - attempted.append(scope_id) - if len(attempted) == 1: - entered.set() - await release.wait() - raise RuntimeError("Injected first-Scope failure") # noqa: TRY003 - return await runtime.atomic_memory.for_scope(scope_id).flush() - - async with open_builtin_runtime( - _config(tmp_path), - candidate_pipeline=atomic_memory_pipeline(_Extractor()), - scheduled_source_runner=runner, - ) as runtime: - assert runtime.atomic_memory is not None - assert runtime.processor is not None - scopes = [await _scope(runtime, name) for name in ("First", "Second", "Late")] - for scope in scopes: - await _capture(runtime, scope.scope_id, "one") - await runtime.atomic_memory.for_scope(scopes[2].scope_id).flush() - tick = asyncio.create_task(runtime.processor.run()) - try: - await asyncio.wait_for(entered.wait(), timeout=5) - await _capture(runtime, scopes[2].scope_id, "two") - finally: - release.set() - await tick - first_attempts = set(attempted) - assert {scope.scope_id for scope in scopes[:2]} <= first_attempts - await runtime.processor.run() - for scope in scopes[:2]: - assert (await runtime.atomic_memory.for_scope(scope.scope_id).cursor()).sequence == 1 - assert (await runtime.atomic_memory.for_scope(scopes[2].scope_id).cursor()).sequence == 2 - - asyncio.run(scenario()) - - -def test_invalid_cursor_isolated_from_other_scopes(tmp_path): - async def scenario(): - async with open_builtin_runtime( - _config(tmp_path), candidate_pipeline=atomic_memory_pipeline(_Extractor()) - ) as runtime: - assert runtime.atomic_memory is not None - assert runtime.processor is not None - broken = await _scope(runtime, "Broken") - peer = await _scope(runtime, "Peer") - for scope in (broken, peer): - await _capture(runtime, scope.scope_id, "one") - await runtime.atomic_memory.for_scope(broken.scope_id).flush() - async with runtime.primary_database.transaction() as connection: - await connection.execute( - update(SOURCE_CURSORS_TABLE) - .where(SOURCE_CURSORS_TABLE.c.scope_id == broken.scope_id) - .values(cursor=b"invalid cursor") - ) - await runtime.processor.run() - assert (await runtime.atomic_memory.for_scope(peer.scope_id).cursor()).sequence == 1 - - asyncio.run(scenario()) - - -def test_refilled_scope_does_not_starve_other_selected_windows(tmp_path): - async def scenario(): - active_scope = "" - refill = 0 - - async def runner(scope_id, runtime): - nonlocal refill - if scope_id == active_scope: - refill += 1 - await _capture(runtime, scope_id, f"refill-{refill}") - return await runtime.atomic_memory.for_scope(scope_id).flush() - - async with open_builtin_runtime( - _config(tmp_path), - candidate_pipeline=atomic_memory_pipeline(_Extractor()), - scheduled_source_runner=runner, - ) as runtime: - assert runtime.atomic_memory is not None - assert runtime.processor is not None - scopes = [await _scope(runtime, name) for name in ("Active", "Peer A", "Peer B")] - active_scope = min(scope.scope_id for scope in scopes) - for scope in scopes: - await _capture(runtime, scope.scope_id, "initial") - await asyncio.wait_for(runtime.processor.run(), timeout=5) - for scope in scopes: - assert (await runtime.atomic_memory.for_scope(scope.scope_id).cursor()).sequence == 1 - await asyncio.wait_for(runtime.processor.run(), timeout=5) - assert (await runtime.atomic_memory.for_scope(active_scope).cursor()).sequence == 2 - # The active Scope is still dirty after both ticks; its peers were - # processed without waiting for that journal to become clean. - result = await runtime.atomic_memory.for_scope(active_scope).flush() - assert result.source_count == 1 - - asyncio.run(scenario()) diff --git a/tests/builtin/runtime/test_topic_memory_search.py b/tests/builtin/runtime/test_topic_memory_search.py index 91d79209b9..258a7e1b9c 100644 --- a/tests/builtin/runtime/test_topic_memory_search.py +++ b/tests/builtin/runtime/test_topic_memory_search.py @@ -164,9 +164,9 @@ def test_topic_service_requires_declared_public_search_capabilities(): @pytest.mark.parametrize("mode", [None, "text", "vector", "hybrid"]) def test_topic_empty_scope_rejects_a_supplied_context_without_authority(mode): from powercontext.artifacts.search import ArtifactSearchExecutionContext + from powercontext.builtin.authz import AccessDeniedError from powercontext.builtin.runtime import BuiltinConfig, open_builtin_contexts from powercontext.builtin.runtime.topic_memory_search import TopicMemorySearcher - from powercontext.server.authz import AccessDeniedError async def scenario(): embedding = Embedding() diff --git a/tests/builtin/runtime/test_topic_memory_security.py b/tests/builtin/runtime/test_topic_memory_security.py index 6021129c1d..be842df6b4 100644 --- a/tests/builtin/runtime/test_topic_memory_security.py +++ b/tests/builtin/runtime/test_topic_memory_security.py @@ -33,6 +33,9 @@ TopicMemoryProbeOutput, TopicMemoryProposal, ) +from powercontext.builtin.authz import AccessAction, PrincipalRef +from powercontext.builtin.authz.repository import ACCESS_AUDIT_EVENTS_TABLE, ACCESS_OWNERS_TABLE, ACCESS_TABLES +from powercontext.builtin.authz.worker import WorkerSecuritySpec, open_worker_security from powercontext.builtin.inference import character_token_estimator from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.processing import ArtifactProcessingPendingRepository @@ -64,9 +67,6 @@ ) from powercontext.builtin.runtime.topic_memory_scope import TopicMemoryScopeProcessor from powercontext.builtin.sources import SourceCursor -from powercontext.server.authz import AccessAction, PrincipalRef -from powercontext.server.authz.repository import ACCESS_AUDIT_EVENTS_TABLE, ACCESS_OWNERS_TABLE, ACCESS_TABLES -from powercontext.server.processing_security import WorkerSecuritySpec, open_worker_security from powercontext.sources import SourceMaterialization from tests.builtin.persistence.contract import SOURCE_ADAPTERS, NoteSource from tests.builtin.runtime.test_topic_memory_processing import _content, _stages diff --git a/tests/builtin/runtime/test_worker_prompt_usage.py b/tests/builtin/runtime/test_worker_prompt_usage.py index addb447188..558752881a 100644 --- a/tests/builtin/runtime/test_worker_prompt_usage.py +++ b/tests/builtin/runtime/test_worker_prompt_usage.py @@ -31,6 +31,9 @@ from powercontext.builtin.artifacts.memory import EmbeddingProfile from powercontext.builtin.artifacts.memory.prompts import MemoryExtractionProfile from powercontext.builtin.artifacts.prompt import PromptError +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.repository import ACCESS_OWNERS_TABLE, ACCESS_TABLES +from powercontext.builtin.authz.worker import WorkerSecuritySpec from powercontext.builtin.inference import EmbeddingResult, GenerationResult from powercontext.builtin.inference.models import InferenceUsage from powercontext.builtin.inference.usage import UsageReportingEmbeddingModel, bind_usage_reporter @@ -53,9 +56,6 @@ from powercontext.builtin.runtime.processing_contracts import ArtifactProcessingWorkAssignment from powercontext.builtin.scope import ScopeDraft from powercontext.builtin.statistics import ModelUsagePurpose -from powercontext.server.authz import PrincipalRef -from powercontext.server.authz.repository import ACCESS_OWNERS_TABLE, ACCESS_TABLES -from powercontext.server.processing_security import WorkerSecuritySpec from tests.e2e.dream_support import atomic_memory_pipeline diff --git a/tests/builtin/test_native_code.py b/tests/builtin/test_native_code.py index 0872d6a49a..e203681e19 100644 --- a/tests/builtin/test_native_code.py +++ b/tests/builtin/test_native_code.py @@ -760,7 +760,6 @@ def test_http_client_mcp_and_prepared_code_share_freshness(repository, tmp_path) database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'http.db'}"), code=code, ), - scheduler_path=tmp_path / "bootstrap-scheduler.db", ) def http_client(headers=None, timeout=None, auth=None, **_): @@ -779,9 +778,7 @@ async def exercise(): async with app.router.lifespan_context(app): pass database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'http.db'}") - async with open_builtin_runtime( - BuiltinConfig(database=database), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(BuiltinConfig(database=database)) as runtime: assert runtime.scopes is not None scope = await runtime.scopes.create( ScopeDraft(title="Code fixture", summary="Native acceptance", idempotency_key="code-test") diff --git a/tests/conftest.py b/tests/conftest.py index 7f0ff16817..b35253bc36 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -47,7 +47,7 @@ def short_tmp_path() -> Iterator[Path]: @pytest.fixture(autouse=True) def isolated_artifact_family_profiles(): """Plugin registration in one test must not change another Server's readiness.""" - from powercontext.server.authz.profiles import ARTIFACT_FAMILY_PROFILES + from powercontext.builtin.authz.profiles import ARTIFACT_FAMILY_PROFILES original = dict(ARTIFACT_FAMILY_PROFILES) try: diff --git a/tests/e2e/artifact_supervisor_real.py b/tests/e2e/artifact_supervisor_real.py index ba72c1855c..59a104be24 100644 --- a/tests/e2e/artifact_supervisor_real.py +++ b/tests/e2e/artifact_supervisor_real.py @@ -38,6 +38,9 @@ from powercontext.builtin.artifacts.prompt import PromptKey from powercontext.builtin.artifacts.prompt.builtin import builtin_prompt_definitions from powercontext.builtin.artifacts.topic_memory import TOPIC_MEMORY_SOURCE_WINDOW_BINDING +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.repository import ACCESS_OWNERS_TABLE, ACCESS_TABLES +from powercontext.builtin.authz.worker import WorkerSecuritySpec from powercontext.builtin.persistence.cursors import SourceCursorRepository from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository @@ -62,10 +65,7 @@ from powercontext.builtin.runtime.processing_registry import canonical_processing_manifest from powercontext.builtin.runtime.relational import RelationalContexts from powercontext.builtin.scope import ScopeDraft -from powercontext.server.authz import PrincipalRef -from powercontext.server.authz.repository import ACCESS_OWNERS_TABLE, ACCESS_TABLES from powercontext.server.configuration import server_settings_context -from powercontext.server.processing_security import WorkerSecuritySpec from powercontext.server.settings import ServerSettings # This acceptance covers Source-driven processors; Dream has its own explicit-request acceptance. diff --git a/tests/e2e/atomic_memory_migration_fixture.py b/tests/e2e/atomic_memory_migration_fixture.py index a462e8ef6e..8c5bc85b09 100644 --- a/tests/e2e/atomic_memory_migration_fixture.py +++ b/tests/e2e/atomic_memory_migration_fixture.py @@ -25,6 +25,8 @@ from powercontext.artifacts import ArtifactRef from powercontext.builtin.artifacts.experience import ExperienceContent, ExperienceDraft from powercontext.builtin.artifacts.memory.canonical import canonical_json, entry_content_hash, normalize_refs +from powercontext.builtin.authz import ArtifactOwnerRelation, MemoryEntrySelector, PrincipalRef, ResourceRef +from powercontext.builtin.authz.repository import RelationalAccessRepository from powercontext.builtin.inference import EmbeddingModel from powercontext.builtin.persistence.atomic_memory_identity import legacy_entry_artifact_id from powercontext.builtin.persistence.migrations.atomic_memory_v1 import ( @@ -42,8 +44,6 @@ from powercontext.builtin.runtime import BuiltinConfig, open_builtin_contexts from powercontext.builtin.runtime.config import DatabaseConfig from powercontext.builtin.sources.content import ContentSource, ContentSourceInternal, ContentSourceTarget -from powercontext.server.authz import ArtifactOwnerRelation, MemoryEntrySelector, PrincipalRef, ResourceRef -from powercontext.server.authz.repository import RelationalAccessRepository from powercontext.sources import SourceMaterialization, SourceRef from tests.e2e.atomic_memory_migration_backend import migration_index, migration_profile from tests.legacy_memory import add_legacy_citation_columns diff --git a/tests/e2e/dify_server.py b/tests/e2e/dify_server.py index 14e88f4228..968541dd1b 100644 --- a/tests/e2e/dify_server.py +++ b/tests/e2e/dify_server.py @@ -79,7 +79,6 @@ def main() -> None: experience_generator=ExperienceGenerator(), skill_generator=SkillGenerator(), handoff_pipeline=HandoffPipeline(), - scheduler_path=args.database.parent / "scheduler.db", ) uvicorn.run(app, host="127.0.0.1", port=args.port, log_level="warning", access_log=False) diff --git a/tests/e2e/real_experience_skill/harness.py b/tests/e2e/real_experience_skill/harness.py index ce74f0691a..992d6d15ff 100644 --- a/tests/e2e/real_experience_skill/harness.py +++ b/tests/e2e/real_experience_skill/harness.py @@ -381,7 +381,7 @@ def main(argv: Sequence[str] | None = None) -> int: # noqa: C901 - one exceptio "embedding_dimension": configured_settings.inference.embedding_dimension, "database": configured_settings.database.kind, "database_isolated": isinstance(configured_settings.database, SQLiteConfig), - "experience_incubation": "APScheduler with the configured real generation model", + "experience_incubation": "artifact processing supervisor with the configured real generation model", "experience_schedule_seconds": CONFIGURED_EXPERIENCE_SCHEDULE_SECONDS, }) recorder.write_report() @@ -398,10 +398,7 @@ def main(argv: Sequence[str] | None = None) -> int: # noqa: C901 - one exceptio validation_command="python test_config.py" if configured_settings is None else "python3 test_config.py", ) if configured_settings is None: - server = _start_server( - recorder.directory / "runtime.db", - recorder.directory / "scheduler.db", - ) + server = _start_server(recorder.directory / "runtime.db") else: external_skill = _prepare_external_skill(recorder.directory / "work" / "external-skills") configured_server_settings = _configured_server_settings( @@ -409,10 +406,7 @@ def main(argv: Sequence[str] | None = None) -> int: # noqa: C901 - one exceptio recorder.directory, external_skill.parent, ) - server = _start_configured_server( - configured_server_settings, - recorder.directory / "configured-scheduler.db", - ) + server = _start_configured_server(configured_server_settings) recorder.environment["server_url"] = server.base_url recorder.write_report() if configured_settings is None: @@ -452,10 +446,7 @@ def main(argv: Sequence[str] | None = None) -> int: # noqa: C901 - one exceptio ) server.stop() server = None - server = _start_configured_server( - _without_scheduled_processing(configured_server_settings), - recorder.directory / "configured-scheduler.db", - ) + server = _start_configured_server(_without_scheduled_processing(configured_server_settings)) asyncio.run( _verify_configured_restart( database=configured_settings.database, @@ -917,7 +908,7 @@ async def _run_configured_journey( ) with recorder.scenario( - "configured LLM and APScheduler incubate one gated Experience Candidate", + "configured LLM and automatic processing incubate one gated Experience Candidate", "api/experience-source.json", "api/experience-candidate.json", "api/experience-approved.json", @@ -2036,7 +2027,7 @@ def _prepare_repositories( return repositories -def _start_server(database: Path, scheduler: Path) -> RunningServer: +def _start_server(database: Path) -> RunningServer: with ExitStack() as resources: endpoint = resources.enter_context(_task_outcome_provider()) app = create_server_app( @@ -2049,7 +2040,6 @@ def _start_server(database: Path, scheduler: Path) -> RunningServer: ), mcp=McpConfig(enabled=False), ), - scheduler_path=scheduler, ) listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) resources.callback(listener.close) @@ -2073,8 +2063,8 @@ def _start_server(database: Path, scheduler: Path) -> RunningServer: ) -def _start_configured_server(settings: ServerSettings, scheduler_path: Path) -> RunningServer: - app = create_server_app(settings=settings, scheduler_path=scheduler_path) +def _start_configured_server(settings: ServerSettings) -> RunningServer: + app = create_server_app(settings=settings) listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listener.bind(("127.0.0.1", 0)) diff --git a/tests/e2e/real_experience_skill/test_access_control.py b/tests/e2e/real_experience_skill/test_access_control.py index 31dd6990fd..f6607973ef 100644 --- a/tests/e2e/real_experience_skill/test_access_control.py +++ b/tests/e2e/real_experience_skill/test_access_control.py @@ -26,11 +26,7 @@ from dotenv import load_dotenv from sqlalchemy import delete, func, or_, select -from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile -from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile -from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.builtin.runtime import DatabaseConfig -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAction, AccessAuditContext, AccessBinding, @@ -46,15 +42,19 @@ ReplaceBinding, ResourceRef, ) -from powercontext.server.authz.composition import open_builtin_access_control, open_casbin_access_control -from powercontext.server.authz.models import HandoffReceiptIdentity -from powercontext.server.authz.repository import ( +from powercontext.builtin.authz.composition import open_builtin_access_control, open_casbin_access_control +from powercontext.builtin.authz.models import HandoffReceiptIdentity +from powercontext.builtin.authz.repository import ( ACCESS_AUDIT_EVENTS_TABLE, ACCESS_BINDINGS_TABLE, ACCESS_IDEMPOTENCY_TABLE, ACCESS_OWNERS_TABLE, RelationalAccessRepository, ) +from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile +from powercontext.builtin.persistence.seekdb import SeekDBConfig, SeekDBProfile +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.runtime import DatabaseConfig from powercontext.server.settings import ServerSettings pytestmark = pytest.mark.real_e2e diff --git a/tests/e2e/real_experience_skill/test_context_text_assembly.py b/tests/e2e/real_experience_skill/test_context_text_assembly.py index 334c3b508b..7b225b1191 100644 --- a/tests/e2e/real_experience_skill/test_context_text_assembly.py +++ b/tests/e2e/real_experience_skill/test_context_text_assembly.py @@ -111,7 +111,7 @@ def test_configured_services_and_native_codex_consume_standard_text(tmp_path, py report["temporary_database"] = temporary_database (tmp_path / "assembly-report.json").write_text(json.dumps(report, indent=2)) print("Starting isolated configured-service context assembly acceptance", flush=True) - server = _start_configured_server(settings, tmp_path / "scheduler.db") + server = _start_configured_server(settings) scope_id, nonce, artifact_ref = asyncio.run(_api_scenario(server.base_url, token, scope_ids, report, tmp_path)) with tempfile.TemporaryDirectory(prefix="powercontext-assembly-host-") as temp: root = Path(temp) diff --git a/tests/e2e/real_experience_skill/test_memory_routing.py b/tests/e2e/real_experience_skill/test_memory_routing.py index 26088582d7..3e7f652e76 100644 --- a/tests/e2e/real_experience_skill/test_memory_routing.py +++ b/tests/e2e/real_experience_skill/test_memory_routing.py @@ -71,7 +71,6 @@ def __init__(self, tmp_path: Path) -> None: database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'memory-routing.db'}"), mcp=McpConfig(enabled=True), ), - scheduler_path=tmp_path / "scheduler.db", ) self._server = uvicorn.Server( uvicorn.Config( diff --git a/tests/e2e/real_experience_skill/test_native_code.py b/tests/e2e/real_experience_skill/test_native_code.py index f32b749609..3526737444 100644 --- a/tests/e2e/real_experience_skill/test_native_code.py +++ b/tests/e2e/real_experience_skill/test_native_code.py @@ -35,8 +35,8 @@ from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import BuiltinConfig, open_builtin_runtime from powercontext.builtin.scope import ScopeDraft -from powercontext.cli.env_file import environment_context from powercontext.client import PowerContextClient +from powercontext.env_file import environment_context from powercontext.http import PrepareContextRequest, RememberMemoryRequest from powercontext.http._generated.models import PreparedContext from powercontext.server.configuration import server_settings_context @@ -102,7 +102,6 @@ async def _scope(settings, root: Path) -> str: await asyncio.to_thread(prepare_server_database, settings, evidence_dir=root / "migration-evidence") async with open_builtin_runtime( BuiltinConfig(database=settings.database, inference=settings.inference, runtime=settings.runtime), - scheduler_path=root / "scheduler.db", ) as runtime: assert runtime.scopes is not None result = await runtime.scopes.create( @@ -378,7 +377,7 @@ def _real_code_acceptance(tmp_path, pytestconfig, backend, *, include_history): CodeService(code).index(scope_id) settings = settings.model_copy(update={"code": code}) token = _configured_access_token(settings) - server = _start_configured_server(settings, tmp_path / "server-scheduler.db") + server = _start_configured_server(settings) if include_history: asyncio.run(_history(server.base_url, token, scope_id, report)) else: @@ -486,7 +485,7 @@ async def experiment(): row["passed"] = True try: - server = _start_configured_server(settings, tmp_path / "server-scheduler.db") + server = _start_configured_server(settings) asyncio.run(experiment()) report["status"] = "passed" finally: diff --git a/tests/e2e/real_experience_skill/test_profile_context_assembly.py b/tests/e2e/real_experience_skill/test_profile_context_assembly.py index 1cf68d3dca..a32eef7ffe 100644 --- a/tests/e2e/real_experience_skill/test_profile_context_assembly.py +++ b/tests/e2e/real_experience_skill/test_profile_context_assembly.py @@ -84,7 +84,7 @@ def test_configured_profile_generation_review_and_context_delivery(tmp_path, pyt update={"database": SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'profile.db'}")} ) print("Starting configured Profile generation and context acceptance", flush=True) - server = _start_configured_server(settings, tmp_path / "scheduler.db") + server = _start_configured_server(settings) asyncio.run(_scenario(server.base_url, _configured_access_token(settings), scope_ids, report, settings)) finally: if server is not None: diff --git a/tests/e2e/test_access_control_http.py b/tests/e2e/test_access_control_http.py index 3605b52c09..4b9c07d343 100644 --- a/tests/e2e/test_access_control_http.py +++ b/tests/e2e/test_access_control_http.py @@ -31,6 +31,8 @@ AtomicMemoryExtractionOutput, ) from powercontext.builtin.artifacts.handoff import HandoffDraft, HandoffGenerationRequest, HandoffStatement +from powercontext.builtin.authz import AccessControlService, PrincipalRef, ResourceRef +from powercontext.builtin.authz.composition import open_builtin_access_control, open_casbin_access_control from powercontext.builtin.inference import GenerationResult from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime.config import InferenceConfig, RuntimeConfig @@ -59,8 +61,6 @@ RevokeAccessBindingRequest, ) from powercontext.server.authentication import StaticBearerAuthenticationProvider -from powercontext.server.authz import AccessControlService, PrincipalRef, ResourceRef -from powercontext.server.authz.composition import open_builtin_access_control, open_casbin_access_control from powercontext.server.factory import create_server_app from powercontext.server.settings import ( AccessControlConfig, @@ -118,7 +118,7 @@ async def scenario() -> None: deployment_id=DEPLOYMENT_ID, ) as access_control: async with _client( - _app(database, access_control, ADMIN, "admin-token", tmp_path / "admin-scheduler.db"), + _app(database, access_control, ADMIN, "admin-token"), "admin-token", ) as admin: scope = await admin.create_scope( @@ -180,7 +180,7 @@ async def scenario() -> None: assert committed.reference.revision == first_committed.reference.revision + 1 async with _client( - _app(database, access_control, RECEIVER, "receiver-token", tmp_path / "receiver-scheduler.db"), + _app(database, access_control, RECEIVER, "receiver-token"), "receiver-token", ) as receiver: exact = await receiver.continue_handoff( @@ -238,7 +238,7 @@ async def scenario() -> None: assert visible.items[0].model_dump(mode="json") == resource async with _client( - _app(database, access_control, ADMIN, "admin-token", tmp_path / "revoke-scheduler.db"), + _app(database, access_control, ADMIN, "admin-token"), "admin-token", ) as admin: revoked = await admin.revoke_access_binding( @@ -251,7 +251,7 @@ async def scenario() -> None: assert revoked.state == "revoked" async with _client( - _app(database, access_control, RECEIVER, "receiver-token", tmp_path / "denied-scheduler.db"), + _app(database, access_control, RECEIVER, "receiver-token"), "receiver-token", ) as receiver: with pytest.raises(ForbiddenResponseError): @@ -285,7 +285,7 @@ async def scenario() -> None: deployment_id=DEPLOYMENT_ID, ) as access_control: async with _client( - _app(database, access_control, ADMIN, "admin-token", tmp_path / "base-admin-scheduler.db"), + _app(database, access_control, ADMIN, "admin-token"), "admin-token", ) as admin: scope = await admin.create_scope( @@ -305,7 +305,7 @@ async def scenario() -> None: ) async with _client( - _app(database, access_control, RECEIVER, "receiver-token", tmp_path / "base-owner-scheduler.db"), + _app(database, access_control, RECEIVER, "receiver-token"), "receiver-token", ) as owner: source = await owner.create_source( @@ -380,7 +380,7 @@ async def scenario() -> None: assert relation.owner == RECEIVER async with _client( - _app(database, access_control, ADMIN, "admin-token", tmp_path / "base-share-scheduler.db"), + _app(database, access_control, ADMIN, "admin-token"), "admin-token", ) as admin: await admin.create_access_binding( @@ -398,7 +398,7 @@ async def scenario() -> None: ) async with _client( - _app(database, access_control, VIEWER, "viewer-token", tmp_path / "base-viewer-scheduler.db"), + _app(database, access_control, VIEWER, "viewer-token"), "viewer-token", ) as viewer: head = await viewer.get_artifact(scope.scope_id, "experience", created.artifact_id) @@ -443,7 +443,7 @@ async def scenario() -> None: deployment_id=DEPLOYMENT_ID, ) as access_control: async with _client( - _app(database, access_control, ADMIN, "admin-token", tmp_path / "query-admin.db"), + _app(database, access_control, ADMIN, "admin-token"), "admin-token", ) as admin: allowed = await admin.create_scope( @@ -469,7 +469,7 @@ async def scenario() -> None: }) ) - app = _app(database, access_control, VIEWER, "viewer-token", tmp_path / "query-viewer.db") + app = _app(database, access_control, VIEWER, "viewer-token") async with ( app.router.lifespan_context(app), httpx.AsyncClient( @@ -517,9 +517,9 @@ async def scenario() -> None: def _scheduled_content_memory_worker(spec, assignment): + from powercontext.builtin.authz.worker import open_worker_security from powercontext.builtin.runtime.composition import open_builtin_contexts from powercontext.builtin.runtime.family_processing import process_family_invocation - from powercontext.server.processing_security import open_worker_security async def run(): async with ( @@ -649,7 +649,6 @@ async def scenario() -> None: metrics=MetricsConfig(enabled=False), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduled-access.db", ) async with _client(app, token) as client: scope = await client.create_scope( @@ -704,7 +703,7 @@ async def scenario() -> None: database, bootstrap_administrators=(ADMIN,), deployment_id=DEPLOYMENT_ID ) as access_control: async with _client( - _app(database, access_control, ADMIN, "admin-token", tmp_path / "admin-scheduler.db"), + _app(database, access_control, ADMIN, "admin-token"), "admin-token", ) as admin: scopes = [ @@ -764,7 +763,7 @@ async def scenario() -> None: limit=1, ) async with _client( - _app(database, access_control, VIEWER, "viewer-token", tmp_path / "viewer-scheduler.db"), + _app(database, access_control, VIEWER, "viewer-token"), "viewer-token", ) as viewer: assert await viewer.get_artifact(scopes[0].scope_id, family, artifacts[1].artifact_id) is not None @@ -783,7 +782,7 @@ async def scenario() -> None: await viewer.get_artifact(scopes[1].scope_id, family, artifacts[2].artifact_id) async with _client( - _app(database, access_control, RECEIVER, "receiver-token", tmp_path / "receiver-scheduler.db"), + _app(database, access_control, RECEIVER, "receiver-token"), "receiver-token", ) as receiver: direct = await receiver.list_access_resources(query) @@ -805,7 +804,7 @@ async def scenario() -> None: database, bootstrap_administrators=(ADMIN,), deployment_id=DEPLOYMENT_ID ) as access_control: async with _client( - _app(database, access_control, ADMIN, "admin-token", tmp_path / "admin-scheduler.db"), + _app(database, access_control, ADMIN, "admin-token"), "admin-token", ) as admin: scope = await admin.create_scope( @@ -846,7 +845,7 @@ async def scenario() -> None: action=AccessAction.SCOPE_ADMIN, resource_type=AccessResourceType.SCOPE, limit=1 ) async with _client( - _app(database, access_control, RECEIVER, "receiver-token", tmp_path / "receiver-scheduler.db"), + _app(database, access_control, RECEIVER, "receiver-token"), "receiver-token", ) as receiver: discovered: list[str] = [] @@ -882,7 +881,7 @@ async def scenario() -> None: await receiver.get_artifact(scope.scope_id, "experience", artifact.artifact_id) async with _client( - _app(database, access_control, VIEWER, "viewer-token", tmp_path / "viewer-scheduler.db"), + _app(database, access_control, VIEWER, "viewer-token"), "viewer-token", ) as viewer: direct = await viewer.list_access_resources(query.model_copy(update={"cursor": None})) @@ -900,9 +899,7 @@ async def scenario() -> None: async with open_builtin_access_control( database, bootstrap_administrators=(ADMIN,), deployment_id=DEPLOYMENT_ID ) as access: - async with _client( - _app(database, access, ADMIN, "admin-token", tmp_path / "admin.db"), "admin-token" - ) as admin: + async with _client(_app(database, access, ADMIN, "admin-token"), "admin-token") as admin: scope = await admin.create_scope( CreateScopeRequest(title="Private tags", summary="Scoped tag access", idempotency_key="tags") ) @@ -914,9 +911,7 @@ async def scenario() -> None: "idempotency_key": "tag-owner", }) ) - async with _client( - _app(database, access, RECEIVER, "owner-token", tmp_path / "owner.db"), "owner-token" - ) as owner: + async with _client(_app(database, access, RECEIVER, "owner-token"), "owner-token") as owner: source = await owner.create_source(scope.scope_id, CreateSourceRequest(content="Tag access evidence")) content = { "profile": {"content": "# Profile\n\nTest before release."}, @@ -985,9 +980,7 @@ async def write_tags(client, etag): "idempotency_key": "tag-viewer", }) ) - async with _client( - _app(database, access, VIEWER, "viewer-token", tmp_path / "viewer.db"), "viewer-token" - ) as viewer: + async with _client(_app(database, access, VIEWER, "viewer-token"), "viewer-token") as viewer: visible = await read_tags(viewer) assert visible is not None and visible.tag_set.tags == saved.tag_set.tags with pytest.raises(ForbiddenResponseError): @@ -996,17 +989,13 @@ async def write_tags(client, etag): await viewer.query_artifact_tags( scope.scope_id, QueryArtifactTagsRequest.model_validate({"tags": ["release"]}) ) - async with _client( - _app(database, access, ADMIN, "admin-token", tmp_path / "admin.db"), "admin-token" - ) as admin: + async with _client(_app(database, access, ADMIN, "admin-token"), "admin-token") as admin: await admin.revoke_access_binding( RevokeAccessBindingRequest( binding_id=binding.binding_id, expected_version=binding.version, idempotency_key="revoke-tags" ) ) - async with _client( - _app(database, access, VIEWER, "viewer-token", tmp_path / "viewer.db"), "viewer-token" - ) as viewer: + async with _client(_app(database, access, VIEWER, "viewer-token"), "viewer-token") as viewer: with pytest.raises(ForbiddenResponseError): await read_tags(viewer) @@ -1018,7 +1007,6 @@ def _app( access_control: AccessControlService, principal: PrincipalRef, token: str, - scheduler_path: Path, ): authentication = StaticBearerAuthenticationProvider(token, principal) return create_server_app( @@ -1031,7 +1019,6 @@ def _app( metrics=MetricsConfig(enabled=False), mcp=McpConfig(enabled=False), ), - scheduler_path=scheduler_path, handoff_pipeline=_DeterministicHandoffPipeline(), access_control=access_control, authentication_provider=authentication, diff --git a/tests/e2e/test_access_control_regressions.py b/tests/e2e/test_access_control_regressions.py index 94330eed44..5af4924113 100644 --- a/tests/e2e/test_access_control_regressions.py +++ b/tests/e2e/test_access_control_regressions.py @@ -26,11 +26,7 @@ import httpx import pytest -from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.records import RecordService -from powercontext.builtin.runtime import BuiltinRuntime, InferenceConfig, RuntimeCapabilities, RuntimeConfig -from powercontext.server.authentication import AuthenticationResult, ProviderReadiness -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAction, AccessAuditContext, AccessDecision, @@ -39,7 +35,11 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.composition import open_builtin_access_control, open_casbin_access_control +from powercontext.builtin.authz.composition import open_builtin_access_control, open_casbin_access_control +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.records import RecordService +from powercontext.builtin.runtime import BuiltinRuntime, InferenceConfig, RuntimeCapabilities, RuntimeConfig +from powercontext.server.authentication import AuthenticationResult, ProviderReadiness from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings from tests.e2e.server_storage import prepare_server_database @@ -89,7 +89,6 @@ async def _server(tmp_path: Path, backend="builtin", *, inference: InferenceConf settings=settings, authentication_provider=_Authentication(), access_control=access, - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), @@ -848,9 +847,9 @@ async def scenario(): def test_static_preset_can_create_and_read_atomic_memories_in_a_cold_scope(tmp_path): from powercontext.artifacts.search import ArtifactSearchExecutionContext + from powercontext.builtin.authz import AccessControlService + from powercontext.builtin.authz.repository import RelationalAccessRepository from powercontext.builtin.runtime import BuiltinConfig, open_builtin_contexts - from powercontext.server.authz import AccessControlService - from powercontext.server.authz.repository import RelationalAccessRepository async def scenario(): config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'cold-preset.db'}")) @@ -953,7 +952,7 @@ async def scenario(): # A preexisting identity can be missing its Owner relation. from sqlalchemy import delete - from powercontext.server.authz.repository import ACCESS_OWNERS_TABLE + from powercontext.builtin.authz.repository import ACCESS_OWNERS_TABLE async with access.relationships._database.transaction() as connection: await connection.execute( @@ -1226,7 +1225,7 @@ async def scenario(): def test_custom_relationship_writer_preserves_its_owner_failure_semantics(tmp_path): - from powercontext.server.authz.repository import RelationalAccessRepository + from powercontext.builtin.authz.repository import RelationalAccessRepository class CustomRelationships(RelationalAccessRepository): async def establish_artifact_owner(self, relation): @@ -2189,9 +2188,9 @@ def test_static_preset_preserves_revoked_legacy_long_scope_receipts(tmp_path): from datetime import UTC, datetime from uuid import uuid4 + from powercontext.builtin.authz import AccessBinding, AccessBindingState, AccessControlService, AccessRole + from powercontext.builtin.authz.repository import RelationalAccessRepository from powercontext.builtin.runtime import BuiltinConfig, open_builtin_contexts - from powercontext.server.authz import AccessBinding, AccessBindingState, AccessControlService, AccessRole - from powercontext.server.authz.repository import RelationalAccessRepository async def scenario(): config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'legacy-preset.db'}")) diff --git a/tests/e2e/test_access_ownership_migration.py b/tests/e2e/test_access_ownership_migration.py index ac845e80d3..eb49a94fcc 100644 --- a/tests/e2e/test_access_ownership_migration.py +++ b/tests/e2e/test_access_ownership_migration.py @@ -35,12 +35,7 @@ from pydantic import SecretStr from typer.testing import CliRunner -from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.runtime import RuntimeConfig -from powercontext.builtin.scope import ScopeApplication, ScopeDraft -from powercontext.cli.app import create_cli -from powercontext.server.authentication import AuthenticationResult, ProviderReadiness -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAction, AccessAuditContext, AccessConflictError, @@ -49,7 +44,12 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.runtime import RuntimeConfig +from powercontext.builtin.scope import ScopeApplication, ScopeDraft +from powercontext.cli.app import create_cli +from powercontext.server.authentication import AuthenticationResult, ProviderReadiness from powercontext.server.factory import create_server_app from powercontext.server.ownership import ArtifactOwnershipGap, apply_ownership_migration from powercontext.server.settings import AccessControlConfig, BearerAuthConfig, McpConfig, MetricsConfig, ServerSettings @@ -143,7 +143,7 @@ def test_background_plan_accounts_for_static_preset_without_granting_bindings( ) -> None: async def scenario() -> None: database = SQLiteConfig(url=f"sqlite+aiosqlite:///{(tmp_path / 'static-background.db').as_posix()}") - app = create_server_app(settings=_settings(database, "disabled"), scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=_settings(database, "disabled")) async with app.router.lifespan_context(app): scopes = ( app.state.application.scopes @@ -162,7 +162,7 @@ async def scenario() -> None: settings = _settings(database, "enforced").model_copy( update={"auth": BearerAuthConfig(token=SecretStr("static-test-token"))} ) - app = create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=settings) async with ( app.router.lifespan_context(app), httpx.AsyncClient( @@ -249,7 +249,7 @@ async def scenario() -> None: def test_migration_inventories_published_handoff_identities(tmp_path: Path) -> None: async def scenario() -> None: database = SQLiteConfig(url=f"sqlite+aiosqlite:///{(tmp_path / 'published.db').as_posix()}") - app = create_server_app(settings=_settings(database, "disabled"), scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=_settings(database, "disabled")) async with ( app.router.lifespan_context(app), httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, @@ -344,7 +344,7 @@ def test_offline_background_plan_uses_configured_static_preset_without_grants( database = SQLiteConfig(url=f"sqlite+aiosqlite:///{(tmp_path / 'offline-static.db').as_posix()}") async def seed() -> str: - app = create_server_app(settings=_settings(database, "disabled"), scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=_settings(database, "disabled")) async with app.router.lifespan_context(app): scopes = ( app.state.application.scopes @@ -403,7 +403,6 @@ async def scenario() -> None: app = create_server_app( settings=_settings(database, "disabled"), - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), @@ -438,7 +437,6 @@ async def scenario() -> None: settings=_settings(database, "enforced"), authentication_provider=_Authentication(), access_control=access, - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), @@ -571,7 +569,6 @@ async def _enforced_server(database: SQLiteConfig, tmp_path: Path): settings=_settings(database, "enforced"), authentication_provider=_Authentication(), access_control=access, - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), @@ -588,7 +585,7 @@ async def scenario() -> None: scope_id = "s" * scope_length artifacts: list[dict[str, Any]] = [] candidate: dict[str, Any] | None = None - app = create_server_app(settings=_settings(database, "disabled"), scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=_settings(database, "disabled")) async with ( app.router.lifespan_context(app), httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, @@ -701,7 +698,7 @@ def test_migration_preserves_authority_to_undo_a_legacy_merge( ) -> None: async def scenario() -> None: database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'merged.db'}") - app = create_server_app(settings=_settings(database, "disabled"), scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=_settings(database, "disabled")) async with ( app.router.lifespan_context(app), httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, @@ -787,7 +784,7 @@ async def scenario() -> None: def test_existing_owner_and_attestation_conflicts_are_reported_in_preview_and_apply(tmp_path: Path) -> None: async def scenario() -> None: database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'existing-owners.db'}") - app = create_server_app(settings=_settings(database, "disabled"), scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=_settings(database, "disabled")) async with ( app.router.lifespan_context(app), httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, @@ -833,7 +830,7 @@ async def scenario() -> None: def test_background_checks_remain_after_migration_and_cover_profile_writes(tmp_path: Path) -> None: async def scenario() -> None: database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'background.db'}") - app = create_server_app(settings=_settings(database, "disabled"), scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=_settings(database, "disabled")) async with ( app.router.lifespan_context(app), httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, @@ -900,7 +897,7 @@ def test_offline_cli_checks_future_background_principal_before_enforcement(tmp_p database = SQLiteConfig(url=f"sqlite+aiosqlite:///{(tmp_path / 'cli-background.db').as_posix()}") async def seed() -> str: - app = create_server_app(settings=_settings(database, "disabled"), scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=_settings(database, "disabled")) async with ( app.router.lifespan_context(app), httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client, @@ -956,7 +953,6 @@ async def scenario() -> None: database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'cli.db'}") app = create_server_app( settings=_settings(database, "disabled"), - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), @@ -979,7 +975,6 @@ async def scenario() -> None: settings=_settings(database, "enforced"), authentication_provider=_Authentication(), access_control=access, - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), @@ -1016,8 +1011,8 @@ async def scenario() -> None: @pytest.mark.parametrize("store", ["local", "external", "external-retry"]) def test_migration_audit_preserves_request_context(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, store: str) -> None: + from powercontext.builtin.authz import AccessUnavailableError from powercontext.builtin.records import ArtifactWrite - from powercontext.server.authz import AccessUnavailableError actor = PrincipalRef(type="service", id="trusted-delegate") owner = PrincipalRef(type="user", id="bob") @@ -1034,7 +1029,7 @@ async def scenario() -> None: if store == "local" else SQLiteConfig(url=f"sqlite+aiosqlite:///{(tmp_path / 'audit-access.db').as_posix()}") ) - seed = create_server_app(settings=_settings(database, "disabled"), scheduler_path=tmp_path / "scheduler.db") + seed = create_server_app(settings=_settings(database, "disabled")) async with ( seed.router.lifespan_context(seed), httpx.AsyncClient(transport=httpx.ASGITransport(app=seed), base_url="http://test") as client, @@ -1056,7 +1051,6 @@ async def scenario() -> None: settings=_settings(database, "enforced"), authentication_provider=DelegatedAuthentication(), access_control=access, - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), @@ -1106,7 +1100,6 @@ async def scenario() -> None: database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'conflict.db'}") app = create_server_app( settings=_settings(database, "disabled"), - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), @@ -1122,7 +1115,6 @@ async def scenario() -> None: settings=_settings(database, "enforced"), authentication_provider=_Authentication(), access_control=access, - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), diff --git a/tests/e2e/test_applicability_selection.py b/tests/e2e/test_applicability_selection.py index 18de62e9ce..931fd57217 100644 --- a/tests/e2e/test_applicability_selection.py +++ b/tests/e2e/test_applicability_selection.py @@ -41,6 +41,8 @@ from examples.systemone.applicability_host import run_codex_host from powercontext.builtin.artifacts.skill import capture_skill_archive from powercontext.builtin.artifacts.skill.external import AgentEnvironmentProfile, AgentSkillTarget +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.inference import InferenceUsage from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import ( @@ -67,8 +69,6 @@ UpdateSkillLifecycleRequest, ) from powercontext.server.authentication import AuthenticationResult, ProviderReadiness -from powercontext.server.authz import PrincipalRef -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings from tests.e2e.server_storage import prepare_server_database @@ -104,7 +104,6 @@ async def server(directory: Path) -> AsyncIterator[tuple[PowerContextClient, htt settings=settings, authentication_provider=Authentication(), access_control=access, - scheduler_path=directory / "scheduler.db", ) async with ( app.router.lifespan_context(app), diff --git a/tests/e2e/test_artifact_authorization_startup.py b/tests/e2e/test_artifact_authorization_startup.py index 92c58870c5..895ac7219a 100644 --- a/tests/e2e/test_artifact_authorization_startup.py +++ b/tests/e2e/test_artifact_authorization_startup.py @@ -20,14 +20,14 @@ import pytest from sqlalchemy import insert +from powercontext.builtin.authz import AccessAuditContext, AccessRole, CreateBinding, PrincipalRef, ResourceRef +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.profiles import ARTIFACT_FAMILY_PROFILES from powercontext.builtin.persistence.artifacts import RepositoryArtifactDraft from powercontext.builtin.persistence.custom_artifacts import StoredArtifactContent, custom_artifact_repository from powercontext.builtin.persistence.tables import ARTIFACT_FAMILY_SCHEMAS_TABLE from powercontext.builtin.runtime.config import RuntimeConfig from powercontext.server.authentication import StaticBearerAuthenticationProvider -from powercontext.server.authz import AccessAuditContext, AccessRole, CreateBinding, PrincipalRef, ResourceRef -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.profiles import ARTIFACT_FAMILY_PROFILES from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, DashboardConfig, McpConfig, MetricsConfig, ServerSettings from tests.e2e.server_storage import prepare_server_database @@ -63,7 +63,6 @@ async def scenario(): def application(principal): return create_server_app( settings=settings, - scheduler_path=tmp_path / "scheduler.db", access_control=access, authentication_provider=StaticBearerAuthenticationProvider("test-token", principal), ) @@ -184,7 +183,6 @@ async def scenario(): async with open_builtin_access_control(database, bootstrap_administrators=(admin,)) as access: app = create_server_app( settings=settings, - scheduler_path=tmp_path / "scheduler.db", access_control=access, authentication_provider=StaticBearerAuthenticationProvider("test-token", admin), ) @@ -350,7 +348,7 @@ async def _request_family_operation(client, access, admin, entry, family, scope, async def _seed_retained_binding(access, admin, family, scope): from datetime import UTC, datetime - from powercontext.server.authz.models import AccessBinding, AccessBindingState + from powercontext.builtin.authz.models import AccessBinding, AccessBindingState # Exercise an existing relationship row; custom families still cannot grant direct roles through HTTP. await access.relationships.create_binding( @@ -419,7 +417,6 @@ async def scenario(): access.provider = _FilteringProvider(access.provider) app = create_server_app( settings=settings, - scheduler_path=tmp_path / "scheduler.db", access_control=access, authentication_provider=StaticBearerAuthenticationProvider("test-token", admin), ) diff --git a/tests/e2e/test_artifact_dreaming.py b/tests/e2e/test_artifact_dreaming.py index d443028fdf..48ef404808 100644 --- a/tests/e2e/test_artifact_dreaming.py +++ b/tests/e2e/test_artifact_dreaming.py @@ -1875,12 +1875,13 @@ def test_enforced_access_rechecks_background_actor_and_attests_candidate(databas import httpx from starlette.middleware import Middleware + from powercontext.builtin.authz import AccessRole, PrincipalRef, ResourceRef + from powercontext.builtin.authz.composition import open_builtin_access_control + from powercontext.builtin.authz.dream import principal_identity + from powercontext.builtin.authz.service import AccessAuditContext, CreateBinding from powercontext.server.app import create_app from powercontext.server.authentication import StaticBearerAuthenticationProvider - from powercontext.server.authz import AccessRole, PrincipalRef, ResourceRef - from powercontext.server.authz.composition import open_builtin_access_control - from powercontext.server.authz.service import AccessAuditContext, CreateBinding - from powercontext.server.dream_access import DreamAccess, principal_identity + from powercontext.server.dream_access import DreamAccess from powercontext.server.middleware import AuthenticationMiddleware admin = PrincipalRef(type="service", id="dream-admin") @@ -2042,10 +2043,11 @@ async def scenario() -> None: def test_dream_candidate_attestation_preserves_configured_casbin_denial(tmp_path: Path) -> None: - from powercontext.server.authz import AccessAction, AccessControlService, AccessRole, PrincipalRef, ResourceRef - from powercontext.server.authz.composition import open_builtin_access_control, open_casbin_access_control - from powercontext.server.authz.service import AccessAuditContext, CreateBinding - from powercontext.server.dream_access import DreamAccess, principal_identity + from powercontext.builtin.authz import AccessAction, AccessControlService, AccessRole, PrincipalRef, ResourceRef + from powercontext.builtin.authz.composition import open_builtin_access_control, open_casbin_access_control + from powercontext.builtin.authz.dream import principal_identity + from powercontext.builtin.authz.service import AccessAuditContext, CreateBinding + from powercontext.server.dream_access import DreamAccess database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'dream.db'}") decision_database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'decisions.db'}") @@ -3298,9 +3300,9 @@ def test_memory_approval_replays_across_servers( # noqa: C901 - keep race barri import httpx from powercontext.builtin.artifacts.atomic_memory.service import AtomicMemoryService + from powercontext.builtin.authz.errors import AccessDeniedError from powercontext.builtin.review.service import ReviewService from powercontext.server.app import create_app - from powercontext.server.authz.errors import AccessDeniedError delayed = ContextVar("delayed_memory_approval", default=False) diff --git a/tests/e2e/test_artifact_merge_experience.py b/tests/e2e/test_artifact_merge_experience.py index 478d62f798..800aee390e 100644 --- a/tests/e2e/test_artifact_merge_experience.py +++ b/tests/e2e/test_artifact_merge_experience.py @@ -32,6 +32,18 @@ from powercontext.builtin.artifacts.atomic_memory import AtomicMemoryContent from powercontext.builtin.artifacts.experience import ExperienceContent, FailureRecord from powercontext.builtin.artifacts.merge_models import ArtifactMergeRelationError +from powercontext.builtin.authz import ( + AccessAuditContext, + AccessBinding, + AccessBindingState, + AccessControlService, + AccessDeniedError, + AccessRole, + BuiltinAuthorizationProvider, + PrincipalRef, + ResourceRef, +) +from powercontext.builtin.authz.repository import RelationalAccessRepository from powercontext.builtin.persistence.artifact_governance import InvalidArtifactLifecycleError from powercontext.builtin.persistence.errors import RepositoryNotFoundError from powercontext.builtin.persistence.experience_index import ensure_artifact_head_searchable_text @@ -49,18 +61,6 @@ from powercontext.builtin.runtime.relational import RelationalContexts from powercontext.builtin.scope import ScopeDraft from powercontext.builtin.tags import ArtifactTagTarget -from powercontext.server.authz import ( - AccessAuditContext, - AccessBinding, - AccessBindingState, - AccessControlService, - AccessDeniedError, - AccessRole, - BuiltinAuthorizationProvider, - PrincipalRef, - ResourceRef, -) -from powercontext.server.authz.repository import RelationalAccessRepository from powercontext.sources import SourceRef OWNER = PrincipalRef(type="service", id="experience-owner") @@ -152,9 +152,7 @@ def test_experience_management_merge_freezes_inputs_preserves_history_and_candid database, tmp_path ) -> None: async def scenario() -> None: - async with open_builtin_runtime( - BuiltinConfig(database=database), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(BuiltinConfig(database=database)) as runtime: scope = await _scope(runtime) assert runtime.artifact_merge is not None records = runtime.records.for_scope(scope) @@ -255,9 +253,7 @@ async def scenario() -> None: def test_registered_families_keep_same_result_identity_and_projections_separate(database, tmp_path) -> None: async def scenario() -> None: - async with open_builtin_runtime( - BuiltinConfig(database=database), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(BuiltinConfig(database=database)) as runtime: scope = await _scope(runtime) assert runtime.artifact_merge is not None assert runtime.atomic_memory is not None @@ -326,7 +322,7 @@ async def scenario() -> None: database=database, runtime=RuntimeConfig(atomic_memory_preview_signing_secret=SecretStr("x" * 32)), ) - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: scope = await _scope(runtime) assert runtime.artifact_merge is not None merge = runtime.artifact_merge.for_scope(scope, "experience") @@ -408,9 +404,7 @@ async def scenario() -> None: def test_experience_merge_preserves_explicit_caller_identity_and_denies_foreign_inputs(database, tmp_path) -> None: async def scenario() -> None: - async with open_builtin_runtime( - BuiltinConfig(database=database), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(BuiltinConfig(database=database)) as runtime: scope = await _scope(runtime) assert runtime.artifact_merge is not None merge = runtime.artifact_merge.for_scope(scope, "experience") @@ -462,8 +456,7 @@ async def scenario() -> None: def test_restoration_outcome_survives_reopen_and_requires_group_read_access(database, tmp_path) -> None: async def scenario() -> None: config = BuiltinConfig(database=database) - scheduler_path = tmp_path / "scheduler.db" - async with open_builtin_runtime(config, scheduler_path=scheduler_path) as runtime: + async with open_builtin_runtime(config) as runtime: scope = await _scope(runtime) assert runtime.artifact_merge is not None merge = runtime.artifact_merge.for_scope(scope, "experience") @@ -518,7 +511,7 @@ async def scenario() -> None: assert (await merge.get(a.ref.artifact_id, revision=2, context=context)).ref == restored.primary.ref with pytest.raises(AccessDeniedError): await merge.restoration_outcome(a.ref.artifact_id, revision=2, context=context) - async with open_builtin_runtime(config, scheduler_path=scheduler_path) as reopened: + async with open_builtin_runtime(config) as reopened: assert reopened.artifact_merge is not None merge = reopened.artifact_merge.for_scope(scope, "experience") recovered = await merge.restoration_outcome(a.ref.artifact_id, revision=2) @@ -599,9 +592,7 @@ async def scenario() -> None: def test_experience_merge_rejects_unsupported_lineage_before_writing(database, tmp_path) -> None: async def scenario() -> None: - async with open_builtin_runtime( - BuiltinConfig(database=database), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(BuiltinConfig(database=database)) as runtime: scope = await _scope(runtime) assert runtime.artifact_merge is not None merge = runtime.artifact_merge.for_scope(scope, "experience") @@ -637,9 +628,7 @@ def test_merge_tags_beyond_the_label_limit_are_bounded_deterministic_and_restora expected = {"zz-all", "yy-pair", *(f"a{index:02}" for index in range(20)), *(f"b{index:02}" for index in range(10))} async def scenario() -> None: - async with open_builtin_runtime( - BuiltinConfig(database=database), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(BuiltinConfig(database=database)) as runtime: scope = await _scope(runtime) assert runtime.artifact_merge is not None records = runtime.records.for_scope(scope) diff --git a/tests/e2e/test_artifact_plugins.py b/tests/e2e/test_artifact_plugins.py index cf82978250..c8ddc03bee 100644 --- a/tests/e2e/test_artifact_plugins.py +++ b/tests/e2e/test_artifact_plugins.py @@ -30,11 +30,11 @@ import pytest import yaml +from powercontext.builtin.authz import AccessAction, AccessAuditContext, AccessDeniedError, PrincipalRef, ResourceRef +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.owner_recovery import OwnerRecovery +from powercontext.builtin.authz.profiles import register_custom_artifact_access_family from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.server.authz import AccessAction, AccessAuditContext, AccessDeniedError, PrincipalRef, ResourceRef -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.owner_recovery import OwnerRecovery -from powercontext.server.authz.profiles import register_custom_artifact_access_family EXAMPLE = Path(__file__).resolve().parents[2] / "examples/artifact_plugins/incident_report" SUMMARY_EXAMPLE = EXAMPLE.parent / "ticket_summary" diff --git a/tests/e2e/test_artifact_tags.py b/tests/e2e/test_artifact_tags.py index 1cd7c52d72..06806b3988 100644 --- a/tests/e2e/test_artifact_tags.py +++ b/tests/e2e/test_artifact_tags.py @@ -21,6 +21,7 @@ import pytest from powercontext.builtin.artifacts.memory import EmbeddingProfile +from powercontext.builtin.authz import PrincipalRef from powercontext.builtin.inference import EmbeddingResult from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.records import ArtifactWrite @@ -30,7 +31,6 @@ from powercontext.client import PowerContextClient from powercontext.http import QueryArtifactTagsRequest, ReplaceArtifactTagsRequest from powercontext.server.authentication import StaticBearerAuthenticationProvider -from powercontext.server.authz import PrincipalRef from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, ServerSettings diff --git a/tests/e2e/test_atomic_artifact_search_domain.py b/tests/e2e/test_atomic_artifact_search_domain.py index db53dc1904..991ad6f9e4 100644 --- a/tests/e2e/test_atomic_artifact_search_domain.py +++ b/tests/e2e/test_atomic_artifact_search_domain.py @@ -30,6 +30,7 @@ from powercontext.builtin.artifacts.atomic_memory import AtomicMemoryContent from powercontext.builtin.artifacts.memory import EmbeddingProfile from powercontext.builtin.artifacts.memory.reranking import MemoryRerankDecision +from powercontext.builtin.authz import AccessDeniedError, AccessIdentityRequiredError from powercontext.builtin.inference import ( EmbeddingResult, InferenceTimeoutError, @@ -44,7 +45,6 @@ from powercontext.builtin.runtime.artifact_search import ArtifactSearchService from powercontext.builtin.runtime.atomic_memory_search import AtomicArtifactSearcher from powercontext.builtin.tags import ArtifactTagTarget -from powercontext.server.authz import AccessDeniedError, AccessIdentityRequiredError class Embedding: diff --git a/tests/e2e/test_atomic_artifact_search_http.py b/tests/e2e/test_atomic_artifact_search_http.py index e503def882..74cbb191e7 100644 --- a/tests/e2e/test_atomic_artifact_search_http.py +++ b/tests/e2e/test_atomic_artifact_search_http.py @@ -26,6 +26,8 @@ from powercontext.builtin.artifacts.memory import EmbeddingProfile from powercontext.builtin.artifacts.search import AdmissionFloor +from powercontext.builtin.authz import AccessAction, GroupRef, PrincipalRef, ResourceRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.inference import EmbeddingResult from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import BuiltinConfig, open_builtin_contexts @@ -34,8 +36,6 @@ from powercontext.client import PowerContextClient from powercontext.http import CreateAccessBindingRequest, CreateScopeRequest, RememberMemoryRequest from powercontext.server.authentication import AuthenticationRejectedError, AuthenticationResult, ProviderReadiness -from powercontext.server.authz import AccessAction, GroupRef, PrincipalRef, ResourceRef -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings from tests.e2e.server_storage import prepare_server_database @@ -108,7 +108,6 @@ def test_supported_long_query_preserves_all_terms_in_both_http_searches( async def scenario(): app = create_server_app( settings=settings, - scheduler_path=migration_backend.directory / "scheduler.db", embedding_model=embedding, ) async with ( @@ -177,7 +176,6 @@ async def scenario() -> None: metrics=MetricsConfig(enabled=False), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), @@ -269,7 +267,6 @@ async def scenario() -> None: metrics=MetricsConfig(enabled=False), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", access_control=access, authentication_provider=Authentication(), ) diff --git a/tests/e2e/test_atomic_memory_artifact_search.py b/tests/e2e/test_atomic_memory_artifact_search.py index b7af15ae43..253bba0e89 100644 --- a/tests/e2e/test_atomic_memory_artifact_search.py +++ b/tests/e2e/test_atomic_memory_artifact_search.py @@ -22,8 +22,13 @@ import pytest from powercontext.artifacts.search import ArtifactSearchExecutionContext -from powercontext.server.authz import AccessControlService, AccessDeniedError, AccessIdentityRequiredError, PrincipalRef -from powercontext.server.authz.repository import RelationalAccessRepository +from powercontext.builtin.authz import ( + AccessControlService, + AccessDeniedError, + AccessIdentityRequiredError, + PrincipalRef, +) +from powercontext.builtin.authz.repository import RelationalAccessRepository from tests.e2e.test_access_control_regressions import AUDIT, _grant, _resource, _scope, _server diff --git a/tests/e2e/test_atomic_memory_evidence_neutral_recall.py b/tests/e2e/test_atomic_memory_evidence_neutral_recall.py index b03dbb6924..d47dfb6fd9 100644 --- a/tests/e2e/test_atomic_memory_evidence_neutral_recall.py +++ b/tests/e2e/test_atomic_memory_evidence_neutral_recall.py @@ -69,7 +69,6 @@ async def scenario() -> None: )) async with open_builtin_runtime( config, - scheduler_path=migration_backend.directory / "consumer-scheduler.db", source_registry=registry, handoff_pipeline=_EchoHandoffPipeline(), ) as runtime: diff --git a/tests/e2e/test_atomic_memory_grant_migration.py b/tests/e2e/test_atomic_memory_grant_migration.py index aa50ca4f3f..fb3b780b41 100644 --- a/tests/e2e/test_atomic_memory_grant_migration.py +++ b/tests/e2e/test_atomic_memory_grant_migration.py @@ -33,6 +33,19 @@ from sqlalchemy import insert, text from starlette.middleware import Middleware +from powercontext.builtin.authz import ( + AccessBinding, + AccessBindingState, + AccessConflictError, + AccessRole, + ArtifactOwnerRelation, + MemoryEntrySelector, + PrincipalRef, + ResourceRef, +) +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.repository import RelationalAccessRepository +from powercontext.builtin.authz.service import ReplaceBinding from powercontext.builtin.persistence.atomic_memory_identity import legacy_entry_artifact_id from powercontext.builtin.persistence.migrations.atomic_memory_v1 import ( apply_atomic_memory_migration, @@ -48,19 +61,6 @@ from powercontext.builtin.scope.application import ScopeApplication from powercontext.server.app import ServerApplication, create_app from powercontext.server.authentication import StaticBearerAuthenticationProvider -from powercontext.server.authz import ( - AccessBinding, - AccessBindingState, - AccessConflictError, - AccessRole, - ArtifactOwnerRelation, - MemoryEntrySelector, - PrincipalRef, - ResourceRef, -) -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.repository import RelationalAccessRepository -from powercontext.server.authz.service import ReplaceBinding from powercontext.server.factory import create_server_app from powercontext.server.middleware import AuthenticationMiddleware from powercontext.server.settings import AccessControlConfig, BearerAuthConfig, McpConfig, MetricsConfig, ServerSettings @@ -83,7 +83,6 @@ def _client(migration_backend: MigrationBackend) -> TestClient: mcp=McpConfig(enabled=False), metrics=MetricsConfig(enabled=False), ), - scheduler_path=migration_backend.directory / "scheduler.db", ), headers={"Authorization": "Bearer migration-test-token"}, ) @@ -475,7 +474,6 @@ async def scenario() -> None: BuiltinConfig( database=migration_backend.config, runtime=RuntimeConfig(artifact_processing_families=()) ), - scheduler_path=migration_backend.directory / "adapter-scheduler.db", ) ) authentication = StaticBearerAuthenticationProvider("migration-test-token", ACTOR) diff --git a/tests/e2e/test_atomic_memory_migration_evidence.py b/tests/e2e/test_atomic_memory_migration_evidence.py index d4fa1237c0..a96bec4f0c 100644 --- a/tests/e2e/test_atomic_memory_migration_evidence.py +++ b/tests/e2e/test_atomic_memory_migration_evidence.py @@ -53,6 +53,7 @@ HandoffSourceCitation, HandoffStatement, ) +from powercontext.builtin.authz.repository import RelationalAccessRepository from powercontext.builtin.dream.models import CreateDreamRunRequest, DreamError, DreamRecord, DreamRun from powercontext.builtin.evidence.models import EvidenceManifest, EvidenceNode, EvidenceResolutionError, content_digest from powercontext.builtin.evidence.resolver import EvidenceResolver, evidence_id @@ -96,7 +97,6 @@ from powercontext.builtin.runtime.config import DatabaseConfig from powercontext.builtin.sources.content import ContentSource, ContentSourceTarget from powercontext.builtin.work.models import HandoffReceipt, TaskOutcome -from powercontext.server.authz.repository import RelationalAccessRepository from powercontext.sources import SourceMaterialization, SourceRef from tests.e2e.atomic_memory_migration_backend import MigrationBackend, migration_index, migration_profile from tests.e2e.atomic_memory_migration_fixture import ( diff --git a/tests/e2e/test_atomic_memory_reconciliation_retry.py b/tests/e2e/test_atomic_memory_reconciliation_retry.py index 3fd9170924..d7fc46cc2e 100644 --- a/tests/e2e/test_atomic_memory_reconciliation_retry.py +++ b/tests/e2e/test_atomic_memory_reconciliation_retry.py @@ -115,7 +115,7 @@ async def _flush(provider: _Provider, monkeypatch, tmp_path): database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'retry.db'}"), inference=InferenceConfig(generation_model="provider:test-model"), ) - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.scopes is not None assert runtime.atomic_memory is not None scope = await runtime.scopes.create(ScopeDraft(title="Billing", summary="Decisions", idempotency_key="billing")) @@ -249,7 +249,7 @@ async def _flush_published_workflow(provider: _PublishedWorkflowProvider, monkey ), runtime=RuntimeConfig(atomic_memory_related_mode="vector"), ) - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.scopes is not None and runtime.atomic_memory is not None scope = await runtime.scopes.create( ScopeDraft(title="Project Larch", summary="Development workflow", idempotency_key="larch") @@ -323,7 +323,7 @@ def test_redundant_revision_recovery_preserves_facts_and_processes_later_sources ) async def scenario(): - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.scopes is not None and runtime.atomic_memory is not None scope = await runtime.scopes.create( ScopeDraft(title="Project Larch", summary="Development workflow", idempotency_key="larch") @@ -355,7 +355,7 @@ async def scenario(): assert (await memory.list()).items == entries # The consumed window and retained facts survive restart; later Sources must not hit the old rejection. - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.atomic_memory is not None memory = runtime.atomic_memory.for_scope(scope.scope_id) assert (await memory.list()).items == entries diff --git a/tests/e2e/test_atomic_memory_related_embedding.py b/tests/e2e/test_atomic_memory_related_embedding.py index 070a76b70d..c67645349c 100644 --- a/tests/e2e/test_atomic_memory_related_embedding.py +++ b/tests/e2e/test_atomic_memory_related_embedding.py @@ -39,18 +39,7 @@ AtomicMemoryReconciliationOutput, ) from powercontext.builtin.artifacts.memory import EmbeddingProfile -from powercontext.builtin.inference import ( - EmbeddingResult, - GenerationResult, - InferenceTimeoutError, - InferenceUnavailableError, - character_token_estimator, -) -from powercontext.builtin.inference.minimax import MiniMaxEmbeddingModel -from powercontext.builtin.persistence.sqlite import SQLiteConfig -from powercontext.builtin.records import ArtifactWrite -from powercontext.builtin.runtime import BuiltinConfig, RuntimeConfig, open_builtin_contexts -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAction, AccessAuditContext, AccessBinding, @@ -64,8 +53,19 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.casbin import CasbinAuthorizationProvider -from powercontext.server.authz.repository import RelationalAccessRepository +from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider +from powercontext.builtin.authz.repository import RelationalAccessRepository +from powercontext.builtin.inference import ( + EmbeddingResult, + GenerationResult, + InferenceTimeoutError, + InferenceUnavailableError, + character_token_estimator, +) +from powercontext.builtin.inference.minimax import MiniMaxEmbeddingModel +from powercontext.builtin.persistence.sqlite import SQLiteConfig +from powercontext.builtin.records import ArtifactWrite +from powercontext.builtin.runtime import BuiltinConfig, RuntimeConfig, open_builtin_contexts from tests.e2e.atomic_memory_migration_backend import MigrationBackend from tests.e2e.dream_support import memory_source_text diff --git a/tests/e2e/test_atomic_memory_search_authorization_snapshot.py b/tests/e2e/test_atomic_memory_search_authorization_snapshot.py index 8f5b00f19d..dc1400aeb2 100644 --- a/tests/e2e/test_atomic_memory_search_authorization_snapshot.py +++ b/tests/e2e/test_atomic_memory_search_authorization_snapshot.py @@ -32,6 +32,16 @@ from powercontext.artifacts import ArtifactSearchExecutionContext from powercontext.builtin.artifacts.memory import EmbeddingProfile +from powercontext.builtin.authz import ( + AccessAuditContext, + AccessDeniedError, + AccessRole, + CreateBinding, + PrincipalRef, + ResourceRef, +) +from powercontext.builtin.authz.composition import open_builtin_access_control, open_casbin_access_control +from powercontext.builtin.authz.service import AccessControlService from powercontext.builtin.inference import EmbeddingResult from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile from powercontext.builtin.persistence.seekdb import SeekDBConfig @@ -53,16 +63,6 @@ AuthenticationResult, ProviderReadiness, ) -from powercontext.server.authz import ( - AccessAuditContext, - AccessDeniedError, - AccessRole, - CreateBinding, - PrincipalRef, - ResourceRef, -) -from powercontext.server.authz.composition import open_builtin_access_control, open_casbin_access_control -from powercontext.server.authz.service import AccessControlService from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings from tests.e2e.server_storage import prepare_server_database @@ -165,7 +165,6 @@ async def _server(database: DatabaseConfig, provider: str, tmp_path: Path, embed async with open_access(database, bootstrap_administrators=(ADMIN,), deployment_id=DEPLOYMENT_ID) as access: app = create_server_app( settings=settings, - scheduler_path=tmp_path / "scheduler.db", access_control=access, authentication_provider=_Authentication(), embedding_model=embedding, diff --git a/tests/e2e/test_atomic_memory_source_evidence.py b/tests/e2e/test_atomic_memory_source_evidence.py index 728737e790..856b95e228 100644 --- a/tests/e2e/test_atomic_memory_source_evidence.py +++ b/tests/e2e/test_atomic_memory_source_evidence.py @@ -496,7 +496,6 @@ async def scenario() -> None: async with open_builtin_runtime( BuiltinConfig(database=migration_backend.config), source_registry=registry, - scheduler_path=tmp_path / "scheduler.db", ) as runtime: assert runtime.scopes is not None scope = await runtime.scopes.create( diff --git a/tests/e2e/test_atomic_memory_temporal_conflicts_live.py b/tests/e2e/test_atomic_memory_temporal_conflicts_live.py index 2731489d9a..41dd36dd8d 100644 --- a/tests/e2e/test_atomic_memory_temporal_conflicts_live.py +++ b/tests/e2e/test_atomic_memory_temporal_conflicts_live.py @@ -123,7 +123,7 @@ async def _run_live(backend: str, env_file: Path, tmp_path: Path) -> None: ), } ) - app = create_server_app(settings=configured, scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=configured) async with ( AsyncExitStack() as resources, app.router.lifespan_context(app), diff --git a/tests/e2e/test_atomic_memory_temporal_retention.py b/tests/e2e/test_atomic_memory_temporal_retention.py index 3953185ed8..953ed65f20 100644 --- a/tests/e2e/test_atomic_memory_temporal_retention.py +++ b/tests/e2e/test_atomic_memory_temporal_retention.py @@ -132,7 +132,7 @@ def test_extraction_corrects_an_omitted_effective_date_before_publication(monkey ) async def scenario() -> None: - async with open_builtin_runtime(_config(tmp_path), scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(_config(tmp_path)) as runtime: assert runtime.scopes is not None and runtime.atomic_memory is not None scope = await runtime.scopes.create( ScopeDraft(title="Port policy", summary="Effective database port", idempotency_key="policy") @@ -182,7 +182,7 @@ async def respond(messages: list[ModelMessage], _info: AgentInfo) -> ModelRespon ) async def scenario() -> None: - async with open_builtin_runtime(_config(tmp_path), scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(_config(tmp_path)) as runtime: assert runtime.scopes is not None and runtime.atomic_memory is not None scope = await runtime.scopes.create( ScopeDraft(title="星河项目", summary="生产数据库端口", idempotency_key="policy") @@ -207,7 +207,7 @@ def test_unrepaired_effective_date_loss_leaves_the_source_unprocessed(monkeypatc ) async def scenario() -> None: - async with open_builtin_runtime(_config(tmp_path), scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(_config(tmp_path)) as runtime: assert runtime.scopes is not None and runtime.atomic_memory is not None scope = await runtime.scopes.create( ScopeDraft(title="Port policy", summary="Effective database port", idempotency_key="policy") @@ -237,7 +237,7 @@ def test_temporal_reconciliation_keeps_dates_across_restart_then_accepts_newer_c config = _config(tmp_path, related_mode=related_mode) async def scenario() -> None: - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.scopes is not None and runtime.atomic_memory is not None scope = await runtime.scopes.create( ScopeDraft(title="Port policy", summary="Effective database port", idempotency_key="policy") @@ -257,7 +257,7 @@ async def scenario() -> None: assert originals[1].ref.artifact_id == originals[0].ref.artifact_id assert originals[1].ref.revision == 2 - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.atomic_memory is not None memory = runtime.atomic_memory.for_scope(scope.scope_id) assert (await memory.list()).items == (originals[-1],) @@ -294,7 +294,7 @@ def test_unrepaired_reconciliation_date_loss_preserves_published_revision_and_cu ) async def scenario() -> None: - async with open_builtin_runtime(_config(tmp_path), scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(_config(tmp_path)) as runtime: assert runtime.scopes is not None and runtime.atomic_memory is not None scope = await runtime.scopes.create( ScopeDraft(title="Port policy", summary="Effective database port", idempotency_key="policy") @@ -331,7 +331,7 @@ def test_newer_corrections_keep_current_content_compact_and_exact_history_readab ) async def scenario() -> None: - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.scopes is not None and runtime.atomic_memory is not None scope = await runtime.scopes.create( ScopeDraft(title="Port policy", summary="Effective database port", idempotency_key="policy") @@ -352,7 +352,7 @@ async def scenario() -> None: originals.append(published) assert (await memory.cursor()).sequence == 12 - async with open_builtin_runtime(config, scheduler_path=tmp_path / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.atomic_memory is not None memory = runtime.atomic_memory.for_scope(scope.scope_id) assert (await memory.list()).items == (originals[-1],) diff --git a/tests/e2e/test_atomic_memory_unrelated_reconciliation.py b/tests/e2e/test_atomic_memory_unrelated_reconciliation.py index bff939db3e..8b791d28a2 100644 --- a/tests/e2e/test_atomic_memory_unrelated_reconciliation.py +++ b/tests/e2e/test_atomic_memory_unrelated_reconciliation.py @@ -153,7 +153,6 @@ async def scenario(): database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'builtin.db'}"), inference=InferenceConfig(generation_model="test"), ), - scheduler_path=tmp_path / "scheduler.db", ) as runtime: assert runtime.scopes is not None assert runtime.atomic_memory is not None @@ -224,7 +223,6 @@ async def scenario(): database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'builtin.db'}"), inference=InferenceConfig(generation_model="test"), ), - scheduler_path=tmp_path / "scheduler.db", ) as runtime: assert runtime.scopes is not None assert runtime.atomic_memory is not None diff --git a/tests/e2e/test_background_startup_admission.py b/tests/e2e/test_background_startup_admission.py index fdbd6ff1d0..b17bfde296 100644 --- a/tests/e2e/test_background_startup_admission.py +++ b/tests/e2e/test_background_startup_admission.py @@ -78,7 +78,7 @@ def test_managed_storage_remains_usable_by_background_runner_and_api(tmp_path, m plan = runner.plan() assert runner.apply(plan_id=plan.plan_id, accepted=True, maintenance_confirmed=True).state == "ready" - with TestClient(create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db")) as client: + with TestClient(create_server_app(settings=settings)) as client: created = client.post( "/v1/scopes", json={ @@ -103,7 +103,7 @@ async def serve(app, configured, stopped): # to check its admitted lifecycle; the native OB test covers split-role CLI. asyncio.run(cli._run_background_async(settings, ServerTracing.context_only(role="background"))) - with TestClient(create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db")) as client: + with TestClient(create_server_app(settings=settings)) as client: response = client.get(f"/v1/scopes/{scope_id}") assert response.status_code == 200, response.text assert response.json()["title"] == "Preserved scope" diff --git a/tests/e2e/test_candidate_ownership_migration.py b/tests/e2e/test_candidate_ownership_migration.py index 1b26296977..239c52e05f 100644 --- a/tests/e2e/test_candidate_ownership_migration.py +++ b/tests/e2e/test_candidate_ownership_migration.py @@ -25,6 +25,7 @@ import pytest from powercontext.artifacts import ArtifactRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.records import ArtifactWrite from powercontext.builtin.runtime import ( @@ -37,7 +38,6 @@ RuntimeConfig, ) from powercontext.builtin.scope import ScopeDraft -from powercontext.server.authz.composition import open_builtin_access_control from tests.e2e.dream_support import open_dream_runtime, process_pending from tests.e2e.test_dream_skill_prompt import PromptGenerator from tests.e2e.test_owner_recovery_http import ALICE, _server diff --git a/tests/e2e/test_candidate_review_authority.py b/tests/e2e/test_candidate_review_authority.py index 5e4a03d225..aaa2a4e8db 100644 --- a/tests/e2e/test_candidate_review_authority.py +++ b/tests/e2e/test_candidate_review_authority.py @@ -28,6 +28,8 @@ from fastmcp import Client from fastmcp.client.transports import StreamableHttpTransport +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import RuntimeConfig from powercontext.server.authentication import ( @@ -36,8 +38,6 @@ AuthenticationResult, ProviderReadiness, ) -from powercontext.server.authz import PrincipalRef -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings from tests.e2e.server_storage import prepare_server_database @@ -106,7 +106,6 @@ async def _review_server(tmp_path: Path) -> AsyncIterator[tuple[FastAPI, str]]: settings=settings, authentication_provider=_Authentication(), access_control=access, - scheduler_path=tmp_path / "scheduler.db", ) async with app.router.lifespan_context(app), _http_client(app, "admin") as admin: scope = await admin.post( diff --git a/tests/e2e/test_cindy_mcp_chain.py b/tests/e2e/test_cindy_mcp_chain.py index 4515068e19..ac7ae66958 100644 --- a/tests/e2e/test_cindy_mcp_chain.py +++ b/tests/e2e/test_cindy_mcp_chain.py @@ -86,7 +86,6 @@ def cindy_server(tmp_path: Path, cindy_provider: Path) -> Iterator[tuple[str, st access=AccessControlConfig(mode="enforced"), database=SQLiteConfig(url=f"sqlite+aiosqlite:///{storage / 'cindy.db'}"), ), - scheduler_path=storage / "scheduler.db", ) listener = socket.socket() listener.bind(("127.0.0.1", 0)) diff --git a/tests/e2e/test_codex_host_service_chain.py b/tests/e2e/test_codex_host_service_chain.py index c9d0d55606..104d96b5e9 100644 --- a/tests/e2e/test_codex_host_service_chain.py +++ b/tests/e2e/test_codex_host_service_chain.py @@ -221,7 +221,7 @@ def codex_stack(tmp_path: Path) -> Iterator[CodexStack]: generation_headers={"Authorization": SecretStr("Bearer synthetic-generation-only")}, ), ) - app = create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler") + app = create_server_app(settings=settings) base_url = stack.enter_context(serve(ObserveServer(app, wire))) server = stack.enter_context( httpx.Client(base_url=base_url, headers={"Authorization": f"Bearer {TOKEN}"}, timeout=15) diff --git a/tests/e2e/test_codex_service_chain.py b/tests/e2e/test_codex_service_chain.py index 064f44bb1a..d8f22161b7 100644 --- a/tests/e2e/test_codex_service_chain.py +++ b/tests/e2e/test_codex_service_chain.py @@ -65,7 +65,6 @@ def test_execution_constraints_preserve_fts_facts_through_codex_hook(tmp_path, r runtime=RuntimeConfig(artifact_processing_families=(), recall_gate_enabled=recall_gate_enabled), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) listener = socket.socket() listener.bind(("127.0.0.1", 0)) @@ -520,7 +519,6 @@ def test_codex_workspace_cli_preserves_session_and_repository_boundaries(tmp_pat database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'workspace-flow.db'}"), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "workspace-scheduler.db", ) listener = socket.socket() listener.bind(("127.0.0.1", 0)) diff --git a/tests/e2e/test_context_external_executor.py b/tests/e2e/test_context_external_executor.py index 2796e4c1e8..b3cc0bd9c5 100644 --- a/tests/e2e/test_context_external_executor.py +++ b/tests/e2e/test_context_external_executor.py @@ -27,11 +27,11 @@ from pydantic import SecretStr from examples.context_protection.external_executor import ExecutionRefused, TrustedTarget, execute_checked_json +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.runtime import InferenceConfig from powercontext.builtin.runtime import context_check as context_check_runtime from powercontext.client import PowerContextClient from powercontext.http import ModelJsonPayload, PrepareContextRequest, PreparedContextLocation, PreparedContextWithReuse -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.factory import create_server_app from tests.e2e.server_storage import prepare_server_database from tests.e2e.test_access_control_regressions import _scope, _server @@ -128,7 +128,6 @@ async def scenario(server): app = create_server_app( settings=settings, authentication_provider=_Authentication(), - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), diff --git a/tests/e2e/test_context_protection_transports.py b/tests/e2e/test_context_protection_transports.py index c0cad8d5bb..1a0446800c 100644 --- a/tests/e2e/test_context_protection_transports.py +++ b/tests/e2e/test_context_protection_transports.py @@ -41,6 +41,8 @@ from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID from pydantic import SecretStr +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.inference.privacy import InferenceProtectionConfig, UpstreamProfile from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import InferenceConfig, RuntimeConfig @@ -51,8 +53,6 @@ AuthenticationResult, ProviderReadiness, ) -from powercontext.server.authz import PrincipalRef -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings from tests.e2e.server_storage import prepare_server_database @@ -106,7 +106,6 @@ def _app(directory: Path): return create_server_app( settings=_settings(directory), authentication_provider=_Authentication(), - scheduler_path=directory / "scheduler.db", ) diff --git a/tests/e2e/test_context_text_assembly.py b/tests/e2e/test_context_text_assembly.py index fdd54866ef..44877a9534 100644 --- a/tests/e2e/test_context_text_assembly.py +++ b/tests/e2e/test_context_text_assembly.py @@ -57,7 +57,6 @@ async def _server(tmp_path, *, database=None): mcp=McpConfig(enabled=False), metrics=MetricsConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), diff --git a/tests/e2e/test_dream_evidence_access.py b/tests/e2e/test_dream_evidence_access.py index cb9cce41f6..cb7c7d3e62 100644 --- a/tests/e2e/test_dream_evidence_access.py +++ b/tests/e2e/test_dream_evidence_access.py @@ -29,6 +29,9 @@ from powercontext.builtin.artifacts.profile.models import ProfileContent, ProfileGeneration from powercontext.builtin.artifacts.skill import SkillContent from powercontext.builtin.artifacts.topic_memory import TopicMemoryContent +from powercontext.builtin.authz import AccessRole, PrincipalRef, ResourceRef +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.service import AccessAuditContext, CreateBinding from powercontext.builtin.catalog_changes.models import TagChangeProposal, TagDreamTarget from powercontext.builtin.dream import provenance from powercontext.builtin.dream.models import CreateDreamRunRequest, DreamPlan, GetDreamRunRequest @@ -42,9 +45,6 @@ from powercontext.builtin.tags import ArtifactTagTarget from powercontext.server.app import ServerApplication, create_app from powercontext.server.authentication import StaticBearerAuthenticationProvider -from powercontext.server.authz import AccessRole, PrincipalRef, ResourceRef -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.service import AccessAuditContext, CreateBinding from powercontext.server.middleware import AuthenticationMiddleware from tests.e2e.dream_support import open_dream_runtime, process_pending from tests.e2e.test_artifact_dreaming import database as database diff --git a/tests/e2e/test_dream_memory_access.py b/tests/e2e/test_dream_memory_access.py index 1a3d9a4a68..587f736323 100644 --- a/tests/e2e/test_dream_memory_access.py +++ b/tests/e2e/test_dream_memory_access.py @@ -23,15 +23,15 @@ from powercontext.artifacts import ArtifactRef from powercontext.builtin.artifacts.atomic_memory import AtomicMemoryContent +from powercontext.builtin.authz import AccessRole, PrincipalRef, ResourceRef +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.errors import AccessDeniedError +from powercontext.builtin.authz.service import AccessAuditContext, CreateBinding from powercontext.builtin.dream.models import DreamPlan from powercontext.builtin.inference.models import GenerationResult, InferenceUsage from powercontext.builtin.runtime import ApproveCandidateRequest, BuiltinConfig from powercontext.server.app import ServerApplication, create_app from powercontext.server.authentication import StaticBearerAuthenticationProvider -from powercontext.server.authz import AccessRole, PrincipalRef, ResourceRef -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.errors import AccessDeniedError -from powercontext.server.authz.service import AccessAuditContext, CreateBinding from powercontext.server.context import bind_principal, reset_principal from powercontext.server.dream_access import DreamAccess from powercontext.server.middleware import AuthenticationMiddleware diff --git a/tests/e2e/test_extraction_diagnostics.py b/tests/e2e/test_extraction_diagnostics.py index 3de6275d62..a1119dfed9 100644 --- a/tests/e2e/test_extraction_diagnostics.py +++ b/tests/e2e/test_extraction_diagnostics.py @@ -103,9 +103,7 @@ async def scenario(): "memory", SpawnArtifactProcessingWorkerLauncher(partial(_memory_worker, config)), ) - async with open_builtin_runtime( - config, scheduler_path=tmp_path / "scheduler.db", artifact_processing_bindings=(binding,) - ) as runtime: + async with open_builtin_runtime(config, artifact_processing_bindings=(binding,)) as runtime: initial = runtime.extraction_status() assert initial is not None assert initial.background.location == "local" @@ -161,9 +159,7 @@ async def scenario(): binding = ArtifactProcessingBinding( f"custom-{family}", family, SpawnArtifactProcessingWorkerLauncher(partial(_memory_worker, config)) ) - async with open_builtin_runtime( - config, scheduler_path=tmp_path / "scheduler.db", artifact_processing_bindings=(binding,) - ) as runtime: + async with open_builtin_runtime(config, artifact_processing_bindings=(binding,)) as runtime: snapshot = runtime.extraction_status() assert snapshot is not None assert snapshot.configuration == "unconfigured" diff --git a/tests/e2e/test_gateway_target_binding.py b/tests/e2e/test_gateway_target_binding.py index 2287cfbbf2..5fac10631d 100644 --- a/tests/e2e/test_gateway_target_binding.py +++ b/tests/e2e/test_gateway_target_binding.py @@ -17,10 +17,10 @@ import httpx import pytest +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.inference.privacy import UpstreamProfile from powercontext.client import PowerContextClient from powercontext.http import CheckContextRequest -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.factory import create_server_app from tests.e2e.server_storage import prepare_server_database from tests.e2e.test_context_protection_transports import _ADMIN, _OTHER, _app, _Authentication, _create_scope, _settings @@ -176,9 +176,7 @@ async def test_rerank_target_resolution_is_consumable_via_http_and_sdk(tmp_path) settings.database, bootstrap_administrators=(_ADMIN,), deployment_id="context-transports" ): pass - app = create_server_app( - settings=settings, authentication_provider=_Authentication(), scheduler_path=tmp_path / "scheduler.db" - ) + app = create_server_app(settings=settings, authentication_provider=_Authentication()) async with ( app.router.lifespan_context(app), httpx.AsyncClient( diff --git a/tests/e2e/test_jev_memory_reranking.py b/tests/e2e/test_jev_memory_reranking.py index f5527ba53e..a603e2fef0 100644 --- a/tests/e2e/test_jev_memory_reranking.py +++ b/tests/e2e/test_jev_memory_reranking.py @@ -28,10 +28,10 @@ from starlette.middleware import Middleware from powercontext.builtin.artifacts.memory import JevMemoryReranker, JevRerankConfig +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.inference.errors import InferenceTimeoutError, InferenceUnavailableError from powercontext.builtin.runtime import BuiltinConfig, RuntimeConfig, open_builtin_runtime from powercontext.server.app import ServerApplication, create_app -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.middleware import AuthenticationMiddleware from tests.e2e.test_access_control_regressions import ADMIN, _Authentication, _grant from tests.e2e.test_atomic_memory_read_snapshot import database as jev_database @@ -87,7 +87,6 @@ async def scenario(): ), memory_reranker=reranker, recall_effort_sink=record_effort, - scheduler_path=tmp_path / "jev-scheduler.db", ) as runtime, ): assert runtime.atomic_memory is not None diff --git a/tests/e2e/test_kimi_code_host.py b/tests/e2e/test_kimi_code_host.py index 4ace6475f6..c942d03250 100644 --- a/tests/e2e/test_kimi_code_host.py +++ b/tests/e2e/test_kimi_code_host.py @@ -327,7 +327,6 @@ def test_real_kimi_memory_capture_recall_and_fail_open(tmp_path: Path, monkeypat generation_headers={"Authorization": SecretStr("Bearer synthetic-generation")}, ), ), - scheduler_path=tmp_path / "scheduler", ) with ( serving(app, startup_diagnostic=tmp_path / "server-startup.json") as (server, endpoint, server_thread), diff --git a/tests/e2e/test_lexical_admission.py b/tests/e2e/test_lexical_admission.py index bec4fe3ac0..087006f947 100644 --- a/tests/e2e/test_lexical_admission.py +++ b/tests/e2e/test_lexical_admission.py @@ -57,7 +57,7 @@ def _lexical_app(backend: MigrationBackend): mcp=McpConfig(enabled=False), ) prepare_server_database(settings, evidence_dir=backend.directory / "migration-evidence") - return create_server_app(settings=settings, scheduler_path=backend.directory / "lexical-scheduler.db") + return create_server_app(settings=settings) @pytest.mark.parametrize("family", ["experience", "skill"]) diff --git a/tests/e2e/test_lexical_projection_upgrade.py b/tests/e2e/test_lexical_projection_upgrade.py index 1bc6aebd83..563c32ec0e 100644 --- a/tests/e2e/test_lexical_projection_upgrade.py +++ b/tests/e2e/test_lexical_projection_upgrade.py @@ -112,9 +112,7 @@ def test_upgrade_preserves_search_exact_records_and_vectors(migration_backend): } async def scenario(): - async with open_builtin_runtime( - config, embedding_model=embedding, scheduler_path=migration_backend.directory / "scheduler" - ) as runtime: + async with open_builtin_runtime(config, embedding_model=embedding) as runtime: assert runtime.scopes is not None scope = ( await runtime.scopes.create( @@ -150,9 +148,7 @@ async def scenario(): .where(ARTIFACT_HEADS_TABLE.c.family.in_(("experience", "skill"))) .values(searchable_text="legacy stale terms") ) - async with open_builtin_runtime( - config, embedding_model=embedding, scheduler_path=migration_backend.directory / "scheduler" - ) as runtime: + async with open_builtin_runtime(config, embedding_model=embedding) as runtime: application = runtime.artifacts.for_scope(scope) for family, original in originals.items(): result = await application.search(family, {"query": "请告诉我部署地址是什么", "mode": "text"}) @@ -174,9 +170,7 @@ async def scenario(): ].artifact_ref.artifact_id == fresh.artifact_id current_vectors = await runtime.atomic_memory.for_scope(scope).search(marker, mode="vector") - async with open_builtin_runtime( - config, embedding_model=embedding, scheduler_path=migration_backend.directory / "scheduler" - ) as runtime: + async with open_builtin_runtime(config, embedding_model=embedding) as runtime: for family, original in originals.items(): result = await runtime.artifacts.for_scope(scope).search(family, {"query": marker, "mode": "text"}) assert [match.artifact_ref.artifact_id for match in result.matches] == [original.artifact_id] diff --git a/tests/e2e/test_local_dashboard_access.py b/tests/e2e/test_local_dashboard_access.py index 22be2acdfc..300bcf8cb3 100644 --- a/tests/e2e/test_local_dashboard_access.py +++ b/tests/e2e/test_local_dashboard_access.py @@ -27,7 +27,7 @@ from powercontext.builtin.runtime import RuntimeConfig from powercontext.cli.config import app as config_app -from powercontext.cli.env_file import parse_environment +from powercontext.env_file import parse_environment from powercontext.server.configuration import server_settings_context from powercontext.server.factory import create_server_app from powercontext.server.settings import ( @@ -65,7 +65,7 @@ def test_local_wizard_connects_dashboard_api_and_mcp(tmp_path: Path, require_aut base_url = values["POWERCONTEXT_CLIENT_SERVER_URL"] headers = {"Authorization": values["POWERCONTEXT_CODEX_AUTHORIZATION"]} if require_authentication else {} with server_settings_context(env_file=output) as settings: - app = create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=settings) def create_http_client( headers: dict[str, str] | None = None, @@ -121,7 +121,7 @@ def test_dashboard_selected_note_uses_one_policy_and_content_snapshot( ) -> None: from contextvars import Context - from powercontext.server.authz import AccessAction, BuiltinAuthorizationProvider + from powercontext.builtin.authz import AccessAction, BuiltinAuthorizationProvider from powercontext.server.dashboard.routes import LABELS settings = ServerSettings( @@ -133,7 +133,7 @@ def test_dashboard_selected_note_uses_one_policy_and_content_snapshot( mcp=McpConfig(enabled=False), ) prepare_server_database(settings, evidence_dir=migration_backend.directory / "migration-evidence") - app = create_server_app(settings=settings, scheduler_path=migration_backend.directory / "scheduler.db") + app = create_server_app(settings=settings) async def scenario() -> None: async with ( @@ -219,7 +219,7 @@ def test_review_disclosures_follow_current_read_and_decision_grants(migration_ba mcp=McpConfig(enabled=False), ) prepare_server_database(settings, evidence_dir=migration_backend.directory / "migration-evidence") - app = create_server_app(settings=settings, scheduler_path=migration_backend.directory / "scheduler.db") + app = create_server_app(settings=settings) async def scenario(): async with ( @@ -278,7 +278,7 @@ async def scenario(): artifact_id = artifact.json()["artifact_id"] tags = await client.get(f"/v1/scopes/{scope}/artifacts/experience/{artifact_id}/tags") assert tags.status_code == 200, tags.text - from powercontext.server.authz import PrincipalRef + from powercontext.builtin.authz import PrincipalRef from powercontext.server.context import bind_principal, reset_principal identity = bind_principal(PrincipalRef(type="service", id="server-token")) @@ -366,7 +366,7 @@ async def revoke(role): assert "Private Review evidence." not in forbidden.text assert "Review a delivery" not in forbidden.text - restarted = create_server_app(settings=settings, scheduler_path=migration_backend.directory / "scheduler.db") + restarted = create_server_app(settings=settings) async with ( restarted.router.lifespan_context(restarted), httpx.AsyncClient( diff --git a/tests/e2e/test_managed_startup_read_consistency.py b/tests/e2e/test_managed_startup_read_consistency.py index 36ab2f514d..3fa299972b 100644 --- a/tests/e2e/test_managed_startup_read_consistency.py +++ b/tests/e2e/test_managed_startup_read_consistency.py @@ -94,9 +94,7 @@ def test_concurrent_publication_does_not_reject_managed_startup(migration_backen prepare_server_database( settings, evidence_dir=evidence, embedding_profile=None if embedding is None else embedding.profile ) - app = create_server_app( - settings=settings, scheduler_path=migration_backend.directory / "scheduler.db", embedding_model=embedding - ) + app = create_server_app(settings=settings, embedding_model=embedding) with TestClient(app) as client: created = client.post( "/v1/scopes", @@ -166,7 +164,6 @@ async def serve_metrics(application, _settings, stopped): create_server_app( settings=settings, embedding_model=embedding, - scheduler_path=migration_backend.directory / "second-scheduler.db", ) ) as second: assert second.get("/health/ready").status_code == 200 diff --git a/tests/e2e/test_managed_startup_snapshot.py b/tests/e2e/test_managed_startup_snapshot.py index f3e4da2b19..fe11785019 100644 --- a/tests/e2e/test_managed_startup_snapshot.py +++ b/tests/e2e/test_managed_startup_snapshot.py @@ -38,7 +38,7 @@ def test_healthy_concurrent_update_does_not_block_managed_startup(tmp_path, monk access=AccessControlConfig(mode="disabled"), auth=BearerAuthConfig(enabled=False), ) - app = create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db", embedding_model=embedding) + app = create_server_app(settings=settings, embedding_model=embedding) with TestClient(app) as client: scope_response = client.post( "/v1/scopes", @@ -87,11 +87,7 @@ async def start(): if entry == "sdk": asyncio.run(start()) else: - with TestClient( - create_server_app( - settings=settings, embedding_model=embedding, scheduler_path=tmp_path / "second-scheduler.db" - ) - ): + with TestClient(create_server_app(settings=settings, embedding_model=embedding)): pass finally: monkeypatch.setattr(atomic_memory_rebuild, "_record", original) diff --git a/tests/e2e/test_mcp_request_authentication.py b/tests/e2e/test_mcp_request_authentication.py index 43efb020a5..5ab5b52b60 100644 --- a/tests/e2e/test_mcp_request_authentication.py +++ b/tests/e2e/test_mcp_request_authentication.py @@ -34,16 +34,7 @@ from starlette.middleware import Middleware from typing_extensions import override -from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.builtin.runtime.atomic_memory import AtomicMemoryAccess, AtomicMemoryPage -from powercontext.server.app import create_app -from powercontext.server.authentication import ( - AuthenticationRejectedError, - AuthenticationRequest, - AuthenticationResult, - ProviderReadiness, -) -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAuditContext, AccessBinding, AccessBindingState, @@ -55,8 +46,17 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.runtime.atomic_memory import AtomicMemoryAccess, AtomicMemoryPage +from powercontext.server.app import create_app +from powercontext.server.authentication import ( + AuthenticationRejectedError, + AuthenticationRequest, + AuthenticationResult, + ProviderReadiness, +) from powercontext.server.factory import create_server_app from powercontext.server.mcp import mount_mcp from powercontext.server.middleware import AuthenticationMiddleware @@ -368,7 +368,6 @@ async def scenario() -> None: def server_app() -> FastAPI: return create_server_app( settings=settings, - scheduler_path=tmp_path / "scheduler.db", access_control=access, authentication_provider=authentication, ) diff --git a/tests/e2e/test_memory_capacity.py b/tests/e2e/test_memory_capacity.py index 483ebc02db..44a3f81b27 100644 --- a/tests/e2e/test_memory_capacity.py +++ b/tests/e2e/test_memory_capacity.py @@ -19,14 +19,14 @@ import httpx import pytest +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime.config import RuntimeConfig from powercontext.builtin.scope import ScopeDraft from powercontext.client import PowerContextClient, ServerResponseError from powercontext.http import GetMemoryCapacityRequest, ListMemoryEntriesRequest, RememberMemoryRequest from powercontext.server.authentication import StaticBearerAuthenticationProvider -from powercontext.server.authz import PrincipalRef -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, BearerAuthConfig, McpConfig, ServerSettings from tests.e2e.server_storage import prepare_server_database diff --git a/tests/e2e/test_memory_write_gate_evaluation.py b/tests/e2e/test_memory_write_gate_evaluation.py index 701fe38bef..8ad89d8dc4 100644 --- a/tests/e2e/test_memory_write_gate_evaluation.py +++ b/tests/e2e/test_memory_write_gate_evaluation.py @@ -52,7 +52,6 @@ def test_exact_source_projection_and_memory_revision_re_evaluate_through_server( mcp=McpConfig(enabled=False), metrics=MetricsConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) async def scenario() -> None: diff --git a/tests/e2e/test_minimax_host.py b/tests/e2e/test_minimax_host.py index 91ad188e95..775bbf7f48 100644 --- a/tests/e2e/test_minimax_host.py +++ b/tests/e2e/test_minimax_host.py @@ -154,7 +154,6 @@ def host(tmp_path, monkeypatch, request, mcp_trace): enabled=authenticated, token=SecretStr("acceptance-only-token") if authenticated else None ), ), - scheduler_path=tmp_path / "scheduler", ) app.add_middleware(MCPTrace, events=mcp_trace) with socket.socket() as listener: diff --git a/tests/e2e/test_native_code_fixture.py b/tests/e2e/test_native_code_fixture.py index d0c0b221a0..7656e9ce15 100644 --- a/tests/e2e/test_native_code_fixture.py +++ b/tests/e2e/test_native_code_fixture.py @@ -56,7 +56,7 @@ def test_native_code_seed_can_be_served(migration_backend, monkeypatch): repositories={scope_id: CodeRepositoryConfig(root=repository)}, ) CodeService(code).index(scope_id) - server = _start_configured_server(settings.model_copy(update={"code": code}), root / "server-scheduler.db") + server = _start_configured_server(settings.model_copy(update={"code": code})) async def scenario(): async with PowerContextClient(server.base_url) as client: diff --git a/tests/e2e/test_native_code_history.py b/tests/e2e/test_native_code_history.py index 65f9a4ea2e..2542ccf1ee 100644 --- a/tests/e2e/test_native_code_history.py +++ b/tests/e2e/test_native_code_history.py @@ -62,14 +62,11 @@ async def exercise(): settings=ServerSettings( database=database, mcp=McpConfig(enabled=False), metrics=MetricsConfig(enabled=False) ), - scheduler_path=tmp_path / "bootstrap-scheduler.db", ) # Initialize Server-owned storage before seeding it through the SDK. async with bootstrap.router.lifespan_context(bootstrap): pass - async with open_builtin_runtime( - BuiltinConfig(database=database), scheduler_path=tmp_path / "runtime-scheduler.db" - ) as runtime: + async with open_builtin_runtime(BuiltinConfig(database=database)) as runtime: assert runtime.scopes is not None scope = await runtime.scopes.create( ScopeDraft(title="Budget history", summary="Mixed context evidence", idempotency_key="code-history") @@ -108,7 +105,6 @@ async def exercise(): settings=ServerSettings( database=database, code=code, mcp=McpConfig(enabled=False), metrics=MetricsConfig(enabled=False) ), - scheduler_path=tmp_path / "http-scheduler.db", ) async with ( app.router.lifespan_context(app), diff --git a/tests/e2e/test_native_code_multilanguage.py b/tests/e2e/test_native_code_multilanguage.py index a29dac15ba..bac6698a81 100644 --- a/tests/e2e/test_native_code_multilanguage.py +++ b/tests/e2e/test_native_code_multilanguage.py @@ -51,15 +51,11 @@ def test_prepare_uses_each_language_and_drops_stale_code(tmp_path): database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'database.db'}") async def exercise(): - bootstrap = create_server_app( - settings=ServerSettings(database=database), scheduler_path=tmp_path / "bootstrap-scheduler.db" - ) + bootstrap = create_server_app(settings=ServerSettings(database=database)) # Initialize Server-owned storage before seeding it through the SDK. async with bootstrap.router.lifespan_context(bootstrap): pass - async with open_builtin_runtime( - BuiltinConfig(database=database), scheduler_path=tmp_path / "scope.db" - ) as runtime: + async with open_builtin_runtime(BuiltinConfig(database=database)) as runtime: assert runtime.scopes is not None scope = await runtime.scopes.create( ScopeDraft(title="Mixed repository", summary="Current source evidence", idempotency_key="mixed-code") diff --git a/tests/e2e/test_native_code_seekdb.py b/tests/e2e/test_native_code_seekdb.py index 206cfd3c6f..426fc0c44d 100644 --- a/tests/e2e/test_native_code_seekdb.py +++ b/tests/e2e/test_native_code_seekdb.py @@ -540,9 +540,7 @@ async def exercise(): ) async with bootstrap.router.lifespan_context(bootstrap): pass - async with open_builtin_runtime( - BuiltinConfig(database=database), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(BuiltinConfig(database=database)) as runtime: assert runtime.scopes is not None scope = await runtime.scopes.create( ScopeDraft(title="Embedded code", summary="Code evidence", idempotency_key="seekdb-code") diff --git a/tests/e2e/test_observability.py b/tests/e2e/test_observability.py index 4fd5802096..84324e6f5a 100644 --- a/tests/e2e/test_observability.py +++ b/tests/e2e/test_observability.py @@ -49,6 +49,7 @@ from powercontext.builtin.artifacts.memory import ( EmbeddingProfile, ) +from powercontext.builtin.authz.worker import open_worker_security from powercontext.builtin.inference import GenerationResult from powercontext.builtin.inference.pydantic_ai import PydanticAIEmbeddingModel from powercontext.builtin.persistence.atomic_memory_evidence import AtomicMemoryEvidenceRepository @@ -77,7 +78,6 @@ from powercontext.errors import SourceConflictError from powercontext.server.factory import create_server_app from powercontext.server.logging import OperationalContextFilter -from powercontext.server.processing_security import open_worker_security from powercontext.server.settings import McpConfig, ServerSettings from powercontext.server.tracing import ServerTracing from tests.e2e.dream_support import atomic_memory_pipeline diff --git a/tests/e2e/test_opencode_service_chain.py b/tests/e2e/test_opencode_service_chain.py index 2e9b29d043..4bc962aa13 100644 --- a/tests/e2e/test_opencode_service_chain.py +++ b/tests/e2e/test_opencode_service_chain.py @@ -267,7 +267,7 @@ def opencode_stack(tmp_path: Path) -> Iterator[OpenCodeStack]: generation_headers={"Authorization": SecretStr("Bearer synthetic-generation-only")}, ), ) - app = create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler") + app = create_server_app(settings=settings) base_url = stack.enter_context(serve(ObserveServer(app, wire))) server = stack.enter_context( httpx.Client(base_url=base_url, headers={"Authorization": f"Bearer {TOKEN}"}, timeout=15) diff --git a/tests/e2e/test_owner_recovery_http.py b/tests/e2e/test_owner_recovery_http.py index fea3c2b1ed..8a832971dc 100644 --- a/tests/e2e/test_owner_recovery_http.py +++ b/tests/e2e/test_owner_recovery_http.py @@ -26,13 +26,13 @@ import pytest from typer.testing import CliRunner +from powercontext.builtin.authz import AccessUnavailableError, PrincipalRef, RelationshipStore, ResourceRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.records import ArtifactWrite from powercontext.builtin.runtime import RuntimeConfig from powercontext.cli.app import create_cli from powercontext.server.authentication import AuthenticationResult, ProviderReadiness -from powercontext.server.authz import AccessUnavailableError, PrincipalRef, RelationshipStore, ResourceRef -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings @@ -86,7 +86,6 @@ async def _server(tmp_path, *, interrupted=False): ), access_control=access, authentication_provider=_Authentication(), - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), diff --git a/tests/e2e/test_ownership_maintenance_dispatch.py b/tests/e2e/test_ownership_maintenance_dispatch.py index a26da0414f..fdc9f6fbf7 100644 --- a/tests/e2e/test_ownership_maintenance_dispatch.py +++ b/tests/e2e/test_ownership_maintenance_dispatch.py @@ -26,6 +26,8 @@ import pytest from typer.testing import CliRunner +from powercontext.builtin.authz import PrincipalRef, ResourceRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.persistence.supervision import ( ArtifactProcessingBindingStateRepository, @@ -35,8 +37,6 @@ from powercontext.builtin.runtime.family_processing import FAMILY_BINDINGS from powercontext.builtin.scope import ScopeDraft from powercontext.cli.app import create_cli -from powercontext.server.authz import PrincipalRef, ResourceRef -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.cli import app as server_cli diff --git a/tests/e2e/test_pi_service_chain.py b/tests/e2e/test_pi_service_chain.py index 5ca5c2f374..24dd1d094e 100644 --- a/tests/e2e/test_pi_service_chain.py +++ b/tests/e2e/test_pi_service_chain.py @@ -149,7 +149,7 @@ def pi_stack(tmp_path: Path) -> Iterator[PiStack]: generation_headers={"Authorization": SecretStr("Bearer synthetic-generation-only")}, ), ) - outage = FlushOutage(create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler")) + outage = FlushOutage(create_server_app(settings=settings)) base_url = stack.enter_context(serve(ObserveServer(outage, wire))) # Let a held flush answer before the Server stops. stack.callback(outage.released.set) diff --git a/tests/e2e/test_profile_assembly_seed.py b/tests/e2e/test_profile_assembly_seed.py index 748d77d36f..8b4e2c0644 100644 --- a/tests/e2e/test_profile_assembly_seed.py +++ b/tests/e2e/test_profile_assembly_seed.py @@ -108,7 +108,7 @@ async def scenario() -> None: pytest.fail("An incompatible default processing profile must remain rejected") await _seed_topics(config, [shared.scope_id, current.scope_id], embedding) - async with open_builtin_runtime(config, scheduler_path=migration_backend.directory / "scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: prepared = await runtime.context.for_scope(current.scope_id).prepare( PrepareContextRequest.model_validate({ "query": "OpenAPI client", diff --git a/tests/e2e/test_prompt_management_api.py b/tests/e2e/test_prompt_management_api.py index 2c53f2999d..e0dd27da2a 100644 --- a/tests/e2e/test_prompt_management_api.py +++ b/tests/e2e/test_prompt_management_api.py @@ -72,7 +72,6 @@ def test_prompt_configuration_previews_defaults_without_inference( runtime=RuntimeConfig(memory_extraction_profile=profile), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) async def scenario() -> None: @@ -116,7 +115,6 @@ def test_prompt_publication_is_rejected_without_target_state(tmp_path: Path, acc access=AccessControlConfig.model_validate({"mode": access_mode}), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) async def scenario() -> None: diff --git a/tests/e2e/test_prompt_management_live.py b/tests/e2e/test_prompt_management_live.py index 6b547df219..622756fc3e 100644 --- a/tests/e2e/test_prompt_management_live.py +++ b/tests/e2e/test_prompt_management_live.py @@ -136,7 +136,7 @@ async def _run_live(backend: str, env_file: Path, tmp_path: Path) -> None: ), } ) - app = create_server_app(settings=configured, scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=configured) async with ( app.router.lifespan_context(app), httpx.AsyncClient( diff --git a/tests/e2e/test_real_experience_skill_baseline.py b/tests/e2e/test_real_experience_skill_baseline.py index cf1794acc9..f5c450c626 100644 --- a/tests/e2e/test_real_experience_skill_baseline.py +++ b/tests/e2e/test_real_experience_skill_baseline.py @@ -36,7 +36,7 @@ def test_baseline_server_incubates_task_outcomes_before_review(tmp_path, monkeyp for key in tuple(os.environ): if key.startswith("POWERCONTEXT_SERVER_"): monkeypatch.delenv(key) - server = _start_server(tmp_path / "runtime.db", tmp_path / "scheduler.db") + server = _start_server(tmp_path / "runtime.db") async def scenario(): proposal = ExperienceProposal( diff --git a/tests/e2e/test_real_experience_skill_harness.py b/tests/e2e/test_real_experience_skill_harness.py index 6da8b4c5f5..f3d64e8e8c 100644 --- a/tests/e2e/test_real_experience_skill_harness.py +++ b/tests/e2e/test_real_experience_skill_harness.py @@ -197,10 +197,10 @@ def wait_for_threads(threads_before: set[threading.Thread]) -> bool: @pytest.mark.parametrize( ("deadline", "start"), [ - ("_SERVER_STARTUP_SECONDS", lambda root: harness._start_server(root / "runtime.db", root / "scheduler.db")), + ("_SERVER_STARTUP_SECONDS", lambda root: harness._start_server(root / "runtime.db")), ( "_CONFIGURED_SERVER_STARTUP_SECONDS", - lambda root: harness._start_configured_server(ServerSettings(), root / "scheduler.db"), + lambda root: harness._start_configured_server(ServerSettings()), ), ], ids=["baseline", "configured"], diff --git a/tests/e2e/test_recall_embedding_timeout.py b/tests/e2e/test_recall_embedding_timeout.py index d7b4d69724..6369dc5bd6 100644 --- a/tests/e2e/test_recall_embedding_timeout.py +++ b/tests/e2e/test_recall_embedding_timeout.py @@ -104,9 +104,7 @@ async def _runtime(database: Path, budget: float, embedding: Any) -> AsyncIterat database=SQLiteConfig(url=f"sqlite+aiosqlite:///{database}"), runtime=RuntimeConfig(recall_embedding_timeout_seconds=budget), ) - async with open_builtin_runtime( - config, scheduler_path=database.with_suffix(".scheduler.db"), embedding_model=embedding - ) as runtime: + async with open_builtin_runtime(config, embedding_model=embedding) as runtime: yield runtime @@ -327,9 +325,7 @@ def test_a_deployment_without_an_embedding_model_is_not_reported_as_degraded(tmp async def scenario() -> Any: config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'lexical.db'}")) - async with open_builtin_runtime( - config, scheduler_path=tmp_path.with_suffix(".scheduler.db"), embedding_model=None - ) as runtime: + async with open_builtin_runtime(config, embedding_model=None) as runtime: scope_id = await _scope_with_memory(runtime, "lexical") return await runtime.context.for_scope(scope_id).prepare(_request()) diff --git a/tests/e2e/test_recall_sufficiency_gate.py b/tests/e2e/test_recall_sufficiency_gate.py index 13ca92ce2b..09fe4737ba 100644 --- a/tests/e2e/test_recall_sufficiency_gate.py +++ b/tests/e2e/test_recall_sufficiency_gate.py @@ -175,9 +175,7 @@ async def _runtime( database=SQLiteConfig() if in_memory else SQLiteConfig(url=f"sqlite+aiosqlite:///{database}"), runtime=runtime if runtime is not None else RuntimeConfig(), ) - async with open_builtin_runtime( - config, scheduler_path=database.with_suffix(".scheduler.db"), embedding_model=embedding_model - ) as opened: + async with open_builtin_runtime(config, embedding_model=embedding_model) as opened: yield opened @@ -1417,7 +1415,6 @@ async def sink(effort) -> None: ) async with open_builtin_runtime( config, - scheduler_path=database.with_suffix(".scheduler.db"), recall_effort_sink=sink, ) as runtime: scope_id = await _create_scope(runtime, "sink") @@ -1480,7 +1477,6 @@ async def sink(_effort) -> None: ) async with open_builtin_runtime( config, - scheduler_path=database.with_suffix(".scheduler.db"), recall_effort_sink=sink, ) as runtime: scope_id = await _create_scope(runtime, "sink-failure") @@ -1510,7 +1506,6 @@ async def sink(_effort) -> None: ) async with open_builtin_runtime( config, - scheduler_path=database.with_suffix(".scheduler.db"), recall_effort_sink=sink, ) as runtime: scope_id = await _create_scope(runtime, "sink-disabled") diff --git a/tests/e2e/test_scheduled_experience_incubation.py b/tests/e2e/test_scheduled_experience_incubation.py index 4da9adafc3..11810ec558 100644 --- a/tests/e2e/test_scheduled_experience_incubation.py +++ b/tests/e2e/test_scheduled_experience_incubation.py @@ -26,6 +26,7 @@ ExperienceCandidateInput, ExperienceContent, ) +from powercontext.builtin.authz.worker import open_worker_security from powercontext.builtin.persistence.processing_intents import ArtifactProcessingIntentRepository from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import ( @@ -54,7 +55,6 @@ ) from powercontext.http._generated.models import PreparedContext from powercontext.server.factory import create_server_app -from powercontext.server.processing_security import open_worker_security from powercontext.server.settings import McpConfig, ServerSettings from powercontext.sources import Source, SourceRef from tests.e2e.atomic_memory_migration_backend import MigrationBackend @@ -142,7 +142,7 @@ async def run(): return asyncio.run(run()) -def _app(database: Path, scheduler: Path): +def _app(database: Path): return create_server_app( settings=ServerSettings( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{database}"), @@ -150,7 +150,6 @@ def _app(database: Path, scheduler: Path): inference=InferenceConfig(generation_model="test"), mcp=McpConfig(enabled=False), ), - scheduler_path=scheduler, ) @@ -197,8 +196,7 @@ def test_scheduler_incubates_task_outcome_once_and_preserves_review_gating( async def scenario() -> None: database = tmp_path / "powercontext.db" - scheduler = tmp_path / "scheduler.db" - app = _app(database, scheduler) + app = _app(database) async with ( app.router.lifespan_context(app), httpx.AsyncClient( @@ -231,7 +229,7 @@ async def scenario() -> None: assert candidates[0].result_artifact is None assert prepared.status == "empty" - restored = _app(database, scheduler) + restored = _app(database) async with ( restored.router.lifespan_context(restored), httpx.AsyncClient( @@ -250,6 +248,5 @@ async def scenario() -> None: await _wait_for_handled(restored, scope_id, handled_generation + 1) candidates = await _pending_experience(client, scope_id) assert len(candidates) == 1 - assert not scheduler.exists() asyncio.run(scenario()) diff --git a/tests/e2e/test_tag_schema_upgrade.py b/tests/e2e/test_tag_schema_upgrade.py index 1ba735dcad..bf95d6ea39 100644 --- a/tests/e2e/test_tag_schema_upgrade.py +++ b/tests/e2e/test_tag_schema_upgrade.py @@ -81,7 +81,7 @@ async def scenario(): @asynccontextmanager async def client(): - app = create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db") + app = create_server_app(settings=settings) async with ( app.router.lifespan_context(app), httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as http, diff --git a/tests/e2e/test_topic_memory_content_admission.py b/tests/e2e/test_topic_memory_content_admission.py index 27a56ac8d8..71264b734f 100644 --- a/tests/e2e/test_topic_memory_content_admission.py +++ b/tests/e2e/test_topic_memory_content_admission.py @@ -119,7 +119,7 @@ async def generate(request: Request): mcp=McpConfig(enabled=False), ) try: - with TestClient(create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db")) as client: + with TestClient(create_server_app(settings=settings)) as client: created = client.post( "/v1/scopes", json={"title": "Admission", "summary": "Admission", "idempotency_key": "admission"} ) diff --git a/tests/e2e/test_topic_memory_generic_api.py b/tests/e2e/test_topic_memory_generic_api.py index a3ead3491b..f52e2d1548 100644 --- a/tests/e2e/test_topic_memory_generic_api.py +++ b/tests/e2e/test_topic_memory_generic_api.py @@ -74,7 +74,6 @@ def _app( mcp=McpConfig(enabled=False), ), embedding_model=embedding, - scheduler_path=tmp_path / "scheduler.db", ) diff --git a/tests/e2e/test_topic_memory_head_conflict.py b/tests/e2e/test_topic_memory_head_conflict.py index 1421ecbd32..f084a587e8 100644 --- a/tests/e2e/test_topic_memory_head_conflict.py +++ b/tests/e2e/test_topic_memory_head_conflict.py @@ -124,7 +124,6 @@ async def scenario(): runtime=RuntimeConfig(artifact_processing_families=("topic-memory",)), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), diff --git a/tests/e2e/test_topic_memory_qwen_settings.py b/tests/e2e/test_topic_memory_qwen_settings.py index 283406b1a2..a2188e216f 100644 --- a/tests/e2e/test_topic_memory_qwen_settings.py +++ b/tests/e2e/test_topic_memory_qwen_settings.py @@ -61,7 +61,7 @@ async def record(request: Request, call_next): ), mcp=McpConfig(enabled=False), ) - with TestClient(create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db")) as client: + with TestClient(create_server_app(settings=settings)) as client: created = client.post( "/v1/scopes", json={"title": "Qwen", "summary": "Qwen settings", "idempotency_key": "qwen"} ) diff --git a/tests/e2e/test_topic_memory_recovery_access.py b/tests/e2e/test_topic_memory_recovery_access.py index 2ae619c8f3..7ffcea19f4 100644 --- a/tests/e2e/test_topic_memory_recovery_access.py +++ b/tests/e2e/test_topic_memory_recovery_access.py @@ -20,9 +20,9 @@ import pytest from pydantic import AnyHttpUrl +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import InferenceConfig, RuntimeConfig -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings from tests.builtin.runtime.test_topic_memory_terminal_frontier import _budget, _seed @@ -53,7 +53,6 @@ async def _recovery_server(tmp_path, backend, inference): app = create_server_app( settings=settings, authentication_provider=_Authentication(), - scheduler_path=tmp_path / "scheduler.db", ) async with ( app.router.lifespan_context(app), diff --git a/tests/e2e/test_topic_memory_terminal_frontier.py b/tests/e2e/test_topic_memory_terminal_frontier.py index e9ebd094e6..751419d15d 100644 --- a/tests/e2e/test_topic_memory_terminal_frontier.py +++ b/tests/e2e/test_topic_memory_terminal_frontier.py @@ -162,7 +162,6 @@ async def scenario(): await _disable_processing(database_config) app = create_server_app( settings=settings, - scheduler_path=tmp_path / "scheduler.db", ) warnings_before = len([ r for r in caplog.records if getattr(r, "event", None) == "artifact_processing.blocked" diff --git a/tests/e2e/test_topic_search_authorization_snapshot.py b/tests/e2e/test_topic_search_authorization_snapshot.py index c62800850a..ac5efc02ed 100644 --- a/tests/e2e/test_topic_search_authorization_snapshot.py +++ b/tests/e2e/test_topic_search_authorization_snapshot.py @@ -33,6 +33,15 @@ from sqlalchemy.engine import make_url from powercontext.builtin.artifacts.memory import EmbeddingProfile +from powercontext.builtin.authz import AccessAction, AccessDecision, PrincipalRef +from powercontext.builtin.authz.authzen import AuthZenAuthorizationProvider +from powercontext.builtin.authz.composition import open_builtin_access_control, open_casbin_access_control +from powercontext.builtin.authz.repository import RelationalAccessRepository +from powercontext.builtin.authz.service import ( + AccessControlService, + AccessProviderCapabilities, + BuiltinAuthorizationProvider, +) from powercontext.builtin.inference import EmbeddingResult, InferenceUnavailableError from powercontext.builtin.persistence.oceanbase import OceanBaseConfig, OceanBaseProfile from powercontext.builtin.persistence.seekdb import SeekDBConfig @@ -40,15 +49,6 @@ from powercontext.builtin.persistence.topic_memory import TopicMemoryRepository from powercontext.builtin.runtime.config import DatabaseConfig, RuntimeConfig from powercontext.server.authentication import AuthenticationRejectedError, AuthenticationResult, ProviderReadiness -from powercontext.server.authz import AccessAction, AccessDecision, PrincipalRef -from powercontext.server.authz.authzen import AuthZenAuthorizationProvider -from powercontext.server.authz.composition import open_builtin_access_control, open_casbin_access_control -from powercontext.server.authz.repository import RelationalAccessRepository -from powercontext.server.authz.service import ( - AccessControlService, - AccessProviderCapabilities, - BuiltinAuthorizationProvider, -) from powercontext.server.factory import create_server_app from powercontext.server.settings import AccessControlConfig, McpConfig, MetricsConfig, ServerSettings from tests.e2e.server_storage import prepare_server_database @@ -215,7 +215,6 @@ def allowed(evaluation): access = await access_factory(access) app = create_server_app( settings=settings, - scheduler_path=tmp_path / "scheduler.db", authentication_provider=_Authentication(), access_control=access, embedding_model=embedding, diff --git a/tests/e2e/test_unified_lexical_search.py b/tests/e2e/test_unified_lexical_search.py index c2d1abeb15..fb5c6973cf 100644 --- a/tests/e2e/test_unified_lexical_search.py +++ b/tests/e2e/test_unified_lexical_search.py @@ -54,7 +54,7 @@ async def scenario(): config = BuiltinConfig( database=migration_backend.config, runtime=RuntimeConfig(artifact_processing_families=()) ) - async with open_builtin_runtime(config, scheduler_path=migration_backend.directory / "scheduler") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.scopes is not None scope = ( await runtime.scopes.create( @@ -96,7 +96,6 @@ def test_public_word_recall_identifiers_and_prepare(migration_backend): async def scenario(): app = create_server_app( settings=settings, - scheduler_path=migration_backend.directory / "scheduler", ) async with ( app.router.lifespan_context(app), diff --git a/tests/e2e/test_worker_logging.py b/tests/e2e/test_worker_logging.py index b4e96f5ce5..fa9d573b61 100644 --- a/tests/e2e/test_worker_logging.py +++ b/tests/e2e/test_worker_logging.py @@ -37,6 +37,7 @@ from opentelemetry.trace import StatusCode from prometheus_client import CollectorRegistry +from powercontext.builtin.authz.errors import AccessDeniedError from powercontext.builtin.code.telemetry import stage from powercontext.builtin.inference import ( InferenceConfigurationError, @@ -68,7 +69,6 @@ ArtifactProcessingWorkerFailure, WorkerInitializerPreparation, ) -from powercontext.server.authz.errors import AccessDeniedError from powercontext.server.context import bind_request_id, current_request_id, reset_request_id from powercontext.server.factory import create_server_app from powercontext.server.logging import JsonFormatter, OperationalContextFilter, WorkerLogging, worker_logging diff --git a/tests/e2e/topic_memory_product/common.py b/tests/e2e/topic_memory_product/common.py index cb8003f44d..b4a9aeb629 100644 --- a/tests/e2e/topic_memory_product/common.py +++ b/tests/e2e/topic_memory_product/common.py @@ -672,7 +672,6 @@ def run_e0(directory: Path) -> dict[str, object]: ) app = create_server_app( settings=settings, - scheduler_path=runtime_directory / "scheduler.db", middleware=(Middleware(AccessTimelineMiddleware, timeline=timeline),), ) powercontext_server = start_loopback_server(app, startup_timeout=60) diff --git a/tests/e2e/topic_memory_product/harness.py b/tests/e2e/topic_memory_product/harness.py index 0e0f807d6f..3bfb5007a9 100644 --- a/tests/e2e/topic_memory_product/harness.py +++ b/tests/e2e/topic_memory_product/harness.py @@ -861,7 +861,6 @@ def run_e1( # noqa: C901 ) app = create_server_app( settings=settings, - scheduler_path=temp_root / "scheduler.db", middleware=( Middleware(AccessTimelineMiddleware, timeline=timeline), Middleware(PreparedContextAuditMiddleware, audit=prepared_audit), @@ -1128,7 +1127,6 @@ def run_e2( # noqa: C901 ) app = create_server_app( settings=settings, - scheduler_path=runtime_directory / "scheduler.db", middleware=(Middleware(AccessTimelineMiddleware, timeline=timeline),), ) server = start_loopback_server(app, startup_timeout=60) @@ -1658,7 +1656,6 @@ def run_e4(directory: Path, *, generation_timeout: float) -> dict[str, object]: server = start_loopback_server( create_server_app( settings=settings, - scheduler_path=runtime_directory / "scheduler.db", middleware=(Middleware(AccessTimelineMiddleware, timeline=timeline),), ), startup_timeout=90, diff --git a/tests/e2e/zcode_acceptance/runner.py b/tests/e2e/zcode_acceptance/runner.py index a6f990aa7d..b58033ef70 100644 --- a/tests/e2e/zcode_acceptance/runner.py +++ b/tests/e2e/zcode_acceptance/runner.py @@ -486,7 +486,7 @@ def setup(self, stack: ExitStack) -> None: ) def create_observed_server(): - app = create_server_app(settings=server_settings, scheduler_path=self.root / "scheduler") + app = create_server_app(settings=server_settings) self.observer = ObserveServer(app, self.wire) return self.observer diff --git a/tests/evaluation/input_encoding/test_baseline.py b/tests/evaluation/input_encoding/test_baseline.py index 31b4e2ba34..275c80dda5 100644 --- a/tests/evaluation/input_encoding/test_baseline.py +++ b/tests/evaluation/input_encoding/test_baseline.py @@ -205,7 +205,7 @@ def test_run_cli_uses_existing_sqlite_override_with_optional_kind(tmp_path, monk }) async def seed(): - async with open_builtin_runtime(config, scheduler_path=tmp_path / "seed-scheduler.db") as runtime: + async with open_builtin_runtime(config) as runtime: assert runtime.scopes is not None return await runtime.scopes.create( ScopeDraft(title="Existing database", summary="Keep this Scope", idempotency_key="existing") diff --git a/tests/evaluation/input_encoding/test_harness.py b/tests/evaluation/input_encoding/test_harness.py index 10c2ffe07c..f1b43accd1 100644 --- a/tests/evaluation/input_encoding/test_harness.py +++ b/tests/evaluation/input_encoding/test_harness.py @@ -226,9 +226,7 @@ async def generate(self, value): async def scenario(): config = BuiltinConfig(database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'local.db'}")) - async with open_builtin_runtime( - config, experience_generator=Generator(), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(config, experience_generator=Generator()) as runtime: await _attempt( runtime, _instance(), @@ -243,9 +241,7 @@ async def scenario(): assert record["status"] == "succeeded" assert record["lineage_equal"] is True assert record["usage"]["requests"] is None - async with open_builtin_runtime( - config, experience_generator=Generator(), scheduler_path=tmp_path / "scheduler.db" - ) as runtime: + async with open_builtin_runtime(config, experience_generator=Generator()) as runtime: saved = await runtime.experience.for_scope(record["scope_id"]).get( GetExperienceRequest.model_validate({"artifact": record["artifact_ref"]}) ) diff --git a/tests/integration_conformance/hermes/support.py b/tests/integration_conformance/hermes/support.py index 03c82d2fa5..5aa6c47376 100644 --- a/tests/integration_conformance/hermes/support.py +++ b/tests/integration_conformance/hermes/support.py @@ -132,7 +132,6 @@ def server(directory: Path, boundary: Boundary): access=AccessControlConfig(mode="enforced"), mcp=McpConfig(enabled=False), ), - scheduler_path=directory / "scheduler.db", candidate_pipeline=atomic_memory_pipeline(EmptyExtractor()), ) app.middleware("http")(boundary.dispatch) diff --git a/tests/pydantic_ai_adapter/test_capture.py b/tests/pydantic_ai_adapter/test_capture.py index 24e17ff5fe..7f13f89af8 100644 --- a/tests/pydantic_ai_adapter/test_capture.py +++ b/tests/pydantic_ai_adapter/test_capture.py @@ -32,7 +32,8 @@ from pydantic_ai.models.function import FunctionModel from powercontext.client import TransportError -from powercontext.client.capture import redact_known_secrets, render_capture_event +from powercontext.client.capture import render_capture_event +from powercontext.redaction import redact_known_secrets from tests.pydantic_ai_adapter.fakes import RecordingClient, prepared_response diff --git a/tests/release_upgrades/authorization_fixture.py b/tests/release_upgrades/authorization_fixture.py index 6330623a35..9bf34e2c59 100644 --- a/tests/release_upgrades/authorization_fixture.py +++ b/tests/release_upgrades/authorization_fixture.py @@ -19,6 +19,8 @@ """ import asyncio +import importlib +import importlib.util import json import sys from pathlib import Path @@ -26,10 +28,19 @@ import httpx from powercontext.server.authentication import StaticBearerAuthenticationProvider -from powercontext.server.authz import PrincipalRef from powercontext.server.factory import create_server_app from powercontext.server.settings import ServerSettings +# Releases up to 1.4.0 keep access control in the Server package; later releases moved it into the built-in +# runtime. This script runs under each installed release's own interpreter, so choose by what is installed. +# find_spec rather than try/except: a broken built-in package must fail loudly, not fall back to the old path. +_AUTHZ = ( + "powercontext.builtin.authz" + if importlib.util.find_spec("powercontext.builtin.authz") + else "powercontext.server.authz" +) +PrincipalRef = importlib.import_module(_AUTHZ).PrincipalRef + async def verify(historical): token = "isolated-viewer-token" # noqa: S105 -- disposable fixture credential diff --git a/tests/test_access_adapters.py b/tests/test_access_adapters.py index 4fdc236c60..a53a8362a5 100644 --- a/tests/test_access_adapters.py +++ b/tests/test_access_adapters.py @@ -24,8 +24,7 @@ import pytest from pydantic import SecretStr -from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAction, AccessAuditContext, AccessBinding, @@ -48,9 +47,10 @@ ResourceRef, ResourceSearchRequest, ) -from powercontext.server.authz.composition import open_casbin_access_control -from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository -from powercontext.server.authz.service import DecisionState +from powercontext.builtin.authz.composition import open_casbin_access_control +from powercontext.builtin.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.authz.service import DecisionState +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile ADMIN = PrincipalRef(type="service", id="admin") ALICE = PrincipalRef(type="user", id="alice", description="Alice") diff --git a/tests/test_access_control.py b/tests/test_access_control.py index 0e26c2968e..fb113d65ee 100644 --- a/tests/test_access_control.py +++ b/tests/test_access_control.py @@ -21,8 +21,7 @@ import pytest -from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( ROLE_CARDINALITIES, AccessAction, AccessAuditContext, @@ -46,11 +45,12 @@ ReplaceBinding, ResourceRef, ) -from powercontext.server.authz.composition import open_builtin_access_control, open_casbin_access_control -from powercontext.server.authz.repository import ( +from powercontext.builtin.authz.composition import open_builtin_access_control, open_casbin_access_control +from powercontext.builtin.authz.repository import ( ACCESS_TABLES, RelationalAccessRepository, ) +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile ADMIN = PrincipalRef(type="service", id="admin", description="deployment administrator") ALICE = PrincipalRef(type="user", id="alice", description="artifact owner") diff --git a/tests/test_access_http.py b/tests/test_access_http.py index 013f3dd47a..829d989307 100644 --- a/tests/test_access_http.py +++ b/tests/test_access_http.py @@ -27,16 +27,7 @@ from starlette.middleware import Middleware from powercontext.artifacts import ArtifactAddress, ArtifactRef, ArtifactSearchExecutionContext -from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.builtin.publication import ArtifactPublication, ArtifactPublicationRequest -from powercontext.builtin.runtime.config import RuntimeConfig -from powercontext.server.app import create_app -from powercontext.server.authentication import ( - AuthenticationResult, - ProviderReadiness, - StaticBearerAuthenticationProvider, -) -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAction, AccessAuditContext, AccessBinding, @@ -49,8 +40,18 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository -from powercontext.server.authz.service import BindingSearchRequest +from powercontext.builtin.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.authz.service import BindingSearchRequest +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.publication import ArtifactPublication, ArtifactPublicationRequest +from powercontext.builtin.runtime.composition import BuiltinConfigurationError +from powercontext.builtin.runtime.config import InferenceConfig, RuntimeConfig +from powercontext.server.app import create_app +from powercontext.server.authentication import ( + AuthenticationResult, + ProviderReadiness, + StaticBearerAuthenticationProvider, +) from powercontext.server.factory import create_server_app from powercontext.server.middleware import AuthenticationMiddleware from powercontext.server.settings import AccessControlConfig, BearerAuthConfig, ServerSettings @@ -88,12 +89,25 @@ def test_enforced_mode_cannot_silently_start_without_authentication_or_provider( database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'scheduled.db'}"), access=AccessControlConfig(mode="enforced"), runtime=RuntimeConfig(schedule_seconds=60), + inference=InferenceConfig(generation_model="test"), ), authentication_provider=_ActingAuthenticationProvider(), ) with pytest.raises(ValueError, match="BACKGROUND_PRINCIPAL_ID"), TestClient(scheduled): pass + # A schedule with no runnable family is rejected at startup as well. + unrunnable = create_server_app( + settings=ServerSettings( + database=SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path / 'unrunnable.db'}"), + access=AccessControlConfig(mode="enforced"), + runtime=RuntimeConfig(schedule_seconds=60), + ), + authentication_provider=_ActingAuthenticationProvider(), + ) + with pytest.raises(BuiltinConfigurationError), TestClient(unrunnable): + pass + def test_enforced_mode_uses_injected_authentication_and_builtin_access(tmp_path: Path) -> None: app = create_server_app( @@ -135,11 +149,11 @@ def test_declared_background_processing_requires_identity_even_without_automatic @pytest.mark.parametrize("background", [False, True]) def test_profile_flush_authorizes_the_actual_snapshot(tmp_path: Path, monkeypatch, background) -> None: + from powercontext.builtin.authz import AccessDeniedError from powercontext.builtin.persistence.tables import BUILTIN_TABLES from powercontext.builtin.records import ArtifactWrite from powercontext.builtin.runtime.relational import RelationalContexts from powercontext.builtin.scope import ScopeDraft - from powercontext.server.authz import AccessDeniedError from powercontext.server.factory import _scheduled_profile_runner class Generator: diff --git a/tests/test_access_mcp.py b/tests/test_access_mcp.py index 282c21b2ea..b0b0e44308 100644 --- a/tests/test_access_mcp.py +++ b/tests/test_access_mcp.py @@ -24,11 +24,7 @@ from fastmcp.client.transports import StreamableHttpTransport from starlette.middleware import Middleware -from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.builtin.runtime.atomic_memory import AtomicMemoryAccess, AtomicMemoryPage -from powercontext.server.app import create_app -from powercontext.server.authentication import StaticBearerAuthenticationProvider -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAuditContext, AccessBinding, AccessBindingState, @@ -39,7 +35,11 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile +from powercontext.builtin.runtime.atomic_memory import AtomicMemoryAccess, AtomicMemoryPage +from powercontext.server.app import create_app +from powercontext.server.authentication import StaticBearerAuthenticationProvider from powercontext.server.mcp import mount_mcp from powercontext.server.middleware import AuthenticationMiddleware diff --git a/tests/test_access_snapshot_boundary.py b/tests/test_access_snapshot_boundary.py index 7c1e02b52f..5be13b0758 100644 --- a/tests/test_access_snapshot_boundary.py +++ b/tests/test_access_snapshot_boundary.py @@ -22,9 +22,7 @@ import pytest from sqlalchemy import event -from powercontext.builtin.persistence.database import AsyncDatabase -from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAction, AccessAuditContext, AccessBinding, @@ -41,8 +39,10 @@ ResourceRef, ResourceSearchRequest, ) -from powercontext.server.authz.models import ArtifactOwnerRelation -from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.authz.models import ArtifactOwnerRelation +from powercontext.builtin.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.persistence.database import AsyncDatabase +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile ADMIN = PrincipalRef(type="service", id="admin") ALICE = PrincipalRef(type="user", id="alice") diff --git a/tests/test_atomic_memory_migration_cli.py b/tests/test_atomic_memory_migration_cli.py index 748581ebb0..a5f00a6e62 100644 --- a/tests/test_atomic_memory_migration_cli.py +++ b/tests/test_atomic_memory_migration_cli.py @@ -24,14 +24,14 @@ from click import unstyle from typer.testing import CliRunner +from powercontext.builtin.authz import PrincipalRef +from powercontext.builtin.authz.composition import open_builtin_access_control from powercontext.builtin.persistence.bootstrap import MissingDatabaseError from powercontext.builtin.persistence.seekdb import LegacySeekDBDatabaseError from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.persistence.tables import BUILTIN_TABLES from powercontext.cli.app import create_cli from powercontext.server import cli as server_cli -from powercontext.server.authz import PrincipalRef -from powercontext.server.authz.composition import open_builtin_access_control from powercontext.server.cli import app diff --git a/tests/test_background_metrics.py b/tests/test_background_metrics.py index aec06f5e33..b0e5265663 100644 --- a/tests/test_background_metrics.py +++ b/tests/test_background_metrics.py @@ -24,11 +24,11 @@ from fastapi.testclient import TestClient from pydantic import SecretStr, ValidationError +from powercontext.builtin.authz import AccessAction +from powercontext.builtin.authz.errors import AccessDeniedError, AccessUnavailableError from powercontext.builtin.persistence.oceanbase import OceanBaseConfig from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime.config import RuntimeConfig -from powercontext.server.authz import AccessAction -from powercontext.server.authz.errors import AccessDeniedError, AccessUnavailableError from powercontext.server.background_metrics import create_background_metrics_app, serve_background_metrics from powercontext.server.metrics import ServerMetrics from powercontext.server.settings import ( diff --git a/tests/test_ci_changes.py b/tests/test_ci_changes.py index b0490669e9..1c9e7b3af7 100644 --- a/tests/test_ci_changes.py +++ b/tests/test_ci_changes.py @@ -174,7 +174,7 @@ def test_shared_or_unclassified_changes_run_every_suite(path: str) -> None: @pytest.mark.parametrize( "path", [ - "src/powercontext/server/authz/owner_recovery.py", + "src/powercontext/builtin/authz/owner_recovery.py", "src/powercontext/builtin/persistence/mysql.py", "uv.lock", "pyproject.toml", @@ -198,7 +198,7 @@ def test_shared_runtime_inputs_keep_backend_upgrade_and_consumer_coverage(path: "oceanbase_acceptance", } <= {suite for suite, enabled in selected.items() if enabled} assert not selected["release_schema"] - assert selected["seekdb_lock"] is (path != "src/powercontext/server/authz/owner_recovery.py") + assert selected["seekdb_lock"] is (path != "src/powercontext/builtin/authz/owner_recovery.py") def git(repository: Path, *arguments: str) -> str: diff --git a/tests/test_cli.py b/tests/test_cli.py index f58a93be65..06ffd7dfe7 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -29,11 +29,11 @@ from typer.testing import CliRunner import powercontext.client.cli as client_cli -from powercontext.builtin.code.cli import app as code_app from powercontext.builtin.persistence.bootstrap import DatabaseAccessError, DatabaseCreationError, creation_statement from powercontext.builtin.persistence.seekdb import LegacySeekDBDatabaseError from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.cli.app import create_cli +from powercontext.cli.code import app as code_app from powercontext.client import ServerResponseError from powercontext.client.receiver_service import ReceiverServiceInstallation from powercontext.client.settings import ClientSettings @@ -641,7 +641,7 @@ def test_code_cli_reports_explicit_legacy_database_required(tmp_path, monkeypatc def refuse_implicit_database(_config, _database): raise LegacySeekDBDatabaseError(tmp_path / "seekdb") - monkeypatch.setattr("powercontext.builtin.code.cli.open_code_service", refuse_implicit_database) + monkeypatch.setattr("powercontext.cli.code.open_code_service", refuse_implicit_database) arguments = ["code", command, "--scope", "configured-scope"] if command == "query": arguments.extend(["--request-file", str(tmp_path / "request.json")]) diff --git a/tests/test_config_wizard.py b/tests/test_config_wizard.py index 4f5ca0abe7..2ec9779e67 100644 --- a/tests/test_config_wizard.py +++ b/tests/test_config_wizard.py @@ -28,7 +28,7 @@ from powercontext.cli.config_wizard_agents import AGENT_SPEC_BY_ID from powercontext.cli.config_wizard_seekdb import SeekDBDependency, SeekDBInstallPlan, SeekDBInstallResult from powercontext.cli.config_wizard_ui import WizardUI -from powercontext.cli.env_file import parse_environment +from powercontext.env_file import parse_environment from powercontext.server.configuration import server_settings_context diff --git a/tests/test_config_wizard_document.py b/tests/test_config_wizard_document.py index a8385ac797..2bae374d00 100644 --- a/tests/test_config_wizard_document.py +++ b/tests/test_config_wizard_document.py @@ -21,7 +21,7 @@ import pytest from powercontext.cli.config_wizard_document import read_sqlite_summary, update_document -from powercontext.cli.env_file import EnvironmentFileError, parse_environment +from powercontext.env_file import EnvironmentFileError, parse_environment def test_update_preserves_managed_and_unmanaged_unknown_assignments_and_comments() -> None: diff --git a/tests/test_config_wizard_next_steps.py b/tests/test_config_wizard_next_steps.py index fe8b9eb2e7..c7667c3a93 100644 --- a/tests/test_config_wizard_next_steps.py +++ b/tests/test_config_wizard_next_steps.py @@ -28,7 +28,7 @@ import powercontext.cli.config_wizard as wizard from powercontext.cli.config import app from powercontext.cli.config_wizard_ui import WizardUI -from powercontext.cli.env_file import parse_environment +from powercontext.env_file import parse_environment @pytest.fixture(autouse=True) diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 944513ff2b..ce7ae693aa 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -56,7 +56,6 @@ def dashboard(tmp_path: Path): access=AccessControlConfig(mode="enforced"), auth=BearerAuthConfig(token=SecretStr(token)), ), - scheduler_path=tmp_path / "scheduler.db", ) with TestClient(app) as client: client.headers["Authorization"] = f"Bearer {token}" @@ -200,9 +199,9 @@ async def damage_usage(): def test_dashboard_preserves_injected_atomic_read_rules(dashboard: TestClient, monkeypatch) -> None: + from powercontext.builtin.authz import AccessDeniedError from powercontext.builtin.runtime.application import BuiltinRuntime from powercontext.builtin.runtime.atomic_memory import AtomicMemoryAccess, AtomicMemoryApplication - from powercontext.server.authz import AccessDeniedError class DenyRead(AtomicMemoryAccess): async def authorize(self, connection, scope_id, context, action, ref=None): @@ -556,7 +555,6 @@ async def embed(self, texts: tuple[str, ...], /) -> EmbeddingResult: dashboard=DashboardConfig(enabled=True), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", embedding_model=CoffeeEmbedding(), ) with TestClient(app) as client: @@ -1287,7 +1285,6 @@ def test_authentication_recovers_without_exposing_credentials(tmp_path: Path) -> auth=BearerAuthConfig(enabled=True, token=SecretStr(token)), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) with TestClient(app) as client: assert client.get("/dashboard/home").status_code == 401 @@ -1326,7 +1323,6 @@ def test_sign_in_returns_to_selected_scope(tmp_path: Path) -> None: auth=BearerAuthConfig(enabled=True, token=SecretStr(token)), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) with TestClient(app) as client: client.headers["Authorization"] = f"Bearer {token}" @@ -1396,13 +1392,13 @@ def test_committed_handoff_json_and_its_sources_are_readable(dashboard: TestClie def test_dashboard_is_opt_in_and_enforced_access_requires_the_static_token_profile(tmp_path: Path, monkeypatch) -> None: + from powercontext.builtin.authz import PrincipalRef from powercontext.server.authentication import StaticBearerAuthenticationProvider - from powercontext.server.authz import PrincipalRef monkeypatch.setenv("POWERCONTEXT_SERVER_DASHBOARD_ENABLED", "false") database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path}/disabled.db") settings = ServerSettings(database=database, mcp=McpConfig(enabled=False)) - with TestClient(create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db")) as client: + with TestClient(create_server_app(settings=settings)) as client: assert client.get("/health/ready").status_code == 200 assert client.get("/v1/scopes/default").status_code == 200 for path in ("/", "/dashboard/home", "/dashboard/static/layout.css"): @@ -1435,7 +1431,7 @@ def test_disabled_dashboard_does_not_offer_token_login(tmp_path: Path) -> None: auth=BearerAuthConfig(token=SecretStr(token)), mcp=McpConfig(enabled=False), ) - with TestClient(create_server_app(settings=settings, scheduler_path=tmp_path / "scheduler.db")) as client: + with TestClient(create_server_app(settings=settings)) as client: response = client.get("/dashboard/home") assert response.status_code == 401 assert response.headers["content-type"].startswith("application/json") diff --git a/tests/test_dashboard_dream_actions.py b/tests/test_dashboard_dream_actions.py index 6f0378e64c..7f1a3bc6b2 100644 --- a/tests/test_dashboard_dream_actions.py +++ b/tests/test_dashboard_dream_actions.py @@ -20,10 +20,10 @@ import httpx import pytest +from powercontext.builtin.authz import PrincipalRef from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime import BuiltinConfig from powercontext.server.app import create_app -from powercontext.server.authz import PrincipalRef from powercontext.server.dashboard.routes import router from tests.builtin.runtime.test_topic_memory_terminal_frontier import _seed from tests.e2e.dream_support import atomic_memory_pipeline, open_dream_runtime, process_pending diff --git a/tests/test_dashboard_generation.py b/tests/test_dashboard_generation.py index 4848a6b516..509b0a4694 100644 --- a/tests/test_dashboard_generation.py +++ b/tests/test_dashboard_generation.py @@ -20,7 +20,7 @@ from powercontext.builtin.artifacts.experience import ExperienceContent from powercontext.builtin.artifacts.skill import SkillContent -from powercontext.server.authz import PrincipalRef +from powercontext.builtin.authz import PrincipalRef from tests.test_dashboard import create_scope from tests.test_dashboard import dashboard as dashboard from tests.test_dashboard_scope_selection import _grant diff --git a/tests/test_dashboard_profile_handoff.py b/tests/test_dashboard_profile_handoff.py index 09e20a3883..5c212bd4f0 100644 --- a/tests/test_dashboard_profile_handoff.py +++ b/tests/test_dashboard_profile_handoff.py @@ -182,7 +182,6 @@ def test_rollback_is_offered_when_access_control_is_disabled(tmp_path: Path) -> dashboard=DashboardConfig(enabled=True), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) with TestClient(app) as client: scope = create_scope(client, "Open rollback")["scope_id"] @@ -212,7 +211,6 @@ def test_existing_database_without_revision_metadata_columns_keeps_working(tmp_p def open_app(): return create_server_app( settings=settings, - scheduler_path=tmp_path / "scheduler.db", ) # Use the registered release layout, then migrate before normal admission. diff --git a/tests/test_dashboard_review_reading.py b/tests/test_dashboard_review_reading.py index 3c83d7e0e1..c0630c1c0a 100644 --- a/tests/test_dashboard_review_reading.py +++ b/tests/test_dashboard_review_reading.py @@ -231,7 +231,6 @@ def test_tag_review_records_tags_without_creating_content_revision(tmp_path, pro dashboard=DashboardConfig(enabled=True), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) with TestClient(app) as client: scope = create_scope(client, "Tag review")["scope_id"] diff --git a/tests/test_dashboard_runtime_configuration.py b/tests/test_dashboard_runtime_configuration.py index 45ad99b551..52d3a36ead 100644 --- a/tests/test_dashboard_runtime_configuration.py +++ b/tests/test_dashboard_runtime_configuration.py @@ -50,7 +50,6 @@ def test_runtime_page_reports_loaded_settings_and_ignores_later_environment_chan artifact_processing_worker_timeout_seconds=150, ), ), - scheduler_path=tmp_path / "scheduler.db", ) with TestClient(app) as client: monkeypatch.setenv("POWERCONTEXT_SERVER_RUNTIME_PROFILE_CRON", "0 9 * * *") diff --git a/tests/test_dashboard_scope_selection.py b/tests/test_dashboard_scope_selection.py index c2fdf14436..b409b32f36 100644 --- a/tests/test_dashboard_scope_selection.py +++ b/tests/test_dashboard_scope_selection.py @@ -22,9 +22,9 @@ from fastapi.testclient import TestClient from sqlalchemy import delete +from powercontext.builtin.authz import AccessAction, PrincipalRef +from powercontext.builtin.authz.casbin import CasbinAuthorizationProvider from powercontext.builtin.persistence.tables import SCOPE_SETTINGS_TABLE -from powercontext.server.authz import AccessAction, PrincipalRef -from powercontext.server.authz.casbin import CasbinAuthorizationProvider from tests.test_dashboard import create_scope from tests.test_dashboard import dashboard as dashboard diff --git a/tests/test_dream_review_transport.py b/tests/test_dream_review_transport.py index 45a0c8d947..71cee3a315 100644 --- a/tests/test_dream_review_transport.py +++ b/tests/test_dream_review_transport.py @@ -336,14 +336,15 @@ def test_enforced_dream_writes_use_scope_config_and_entry_permissions(tmp_path): import pytest from powercontext.artifacts import ArtifactRef + from powercontext.builtin.authz import AccessRole, PrincipalRef, ResourceRef + from powercontext.builtin.authz.composition import open_builtin_access_control + from powercontext.builtin.authz.dream import principal_identity + from powercontext.builtin.authz.service import AccessAuditContext, CreateBinding from powercontext.builtin.catalog_changes.models import TagDreamTarget from powercontext.builtin.dream.models import DreamError from powercontext.builtin.tags import ArtifactTagTarget - from powercontext.server.authz import AccessRole, PrincipalRef, ResourceRef - from powercontext.server.authz.composition import open_builtin_access_control - from powercontext.server.authz.service import AccessAuditContext, CreateBinding from powercontext.server.context import bind_principal, reset_principal - from powercontext.server.dream_access import DreamAccess, principal_identity + from powercontext.server.dream_access import DreamAccess async def scenario(): database = SQLiteConfig(url=f"sqlite+aiosqlite:///{tmp_path}/permissions.db") @@ -485,7 +486,6 @@ def test_legacy_prompt_publication_preserves_business_json_that_resembles_protoc inference=InferenceConfig(generation_model="test"), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "prompt-compat-scheduler.db", ) async def scenario(): diff --git a/tests/test_env_file.py b/tests/test_env_file.py index 69a2a60dff..23b46ee4ca 100644 --- a/tests/test_env_file.py +++ b/tests/test_env_file.py @@ -20,7 +20,7 @@ import pytest -from powercontext.cli.env_file import ( +from powercontext.env_file import ( EnvironmentFileError, environment_context, parse_environment, diff --git a/tests/test_inference_notice.py b/tests/test_inference_notice.py index bc1c88bbcd..aec799facb 100644 --- a/tests/test_inference_notice.py +++ b/tests/test_inference_notice.py @@ -14,7 +14,7 @@ import pytest -from powercontext.cli.inference_notice import write_inference_capability_notice +from powercontext.server.inference_notice import write_inference_capability_notice @pytest.mark.parametrize("generation_model,embedding_model", [(None, None), ("test", None), (None, "test")]) diff --git a/tests/test_managed_atomic_projection.py b/tests/test_managed_atomic_projection.py index 547eda8cbf..75a4ca7dcd 100644 --- a/tests/test_managed_atomic_projection.py +++ b/tests/test_managed_atomic_projection.py @@ -117,7 +117,7 @@ async def reject_runtime(): pytest.fail("Incomplete projections must block runtime admission") asyncio.run(reject_runtime()) - server = create_server_app(settings=settings, scheduler_path=path.parent / "scheduler.db") + server = create_server_app(settings=settings) with pytest.raises(MigrationError, match="projection_verification_failed"), TestClient(server): pytest.fail("Incomplete projections must block Server startup") assert path.read_bytes() == original diff --git a/tests/test_observability_cli.py b/tests/test_observability_cli.py index 4714797cfc..556d65da38 100644 --- a/tests/test_observability_cli.py +++ b/tests/test_observability_cli.py @@ -104,7 +104,7 @@ def test_private_profile_preserves_business_configuration(deployment, monkeypatc def test_split_profile_matches_api_and_background_scrape_targets(deployment): - from powercontext.cli.env_file import read_environment_file + from powercontext.env_file import read_environment_file initialize( deployment, @@ -159,7 +159,7 @@ def test_repeat_up_preserves_credentials_targets_and_template_edits(deployment, assert "powercontext server run --observability" in result.output assert "observability check --exercise" in result.output assert "phoenix:" in (deployment / "compose.yaml").read_text() - from powercontext.cli.env_file import read_environment_file + from powercontext.env_file import read_environment_file headers = read_environment_file(deployment / "server.env")["OTEL_EXPORTER_OTLP_HEADERS"] assert headers not in result.output diff --git a/tests/test_observability_demo.py b/tests/test_observability_demo.py index 6917adfec1..405c25d3cc 100644 --- a/tests/test_observability_demo.py +++ b/tests/test_observability_demo.py @@ -22,7 +22,7 @@ import pytest -from powercontext.cli.env_file import environment_context, read_environment_file +from powercontext.env_file import environment_context, read_environment_file from powercontext.server.settings import ServerSettings diff --git a/tests/test_observability_notice.py b/tests/test_observability_notice.py index fbe53d678e..f1368c2382 100644 --- a/tests/test_observability_notice.py +++ b/tests/test_observability_notice.py @@ -19,7 +19,7 @@ import pytest from typer.testing import CliRunner -from powercontext.cli.observability_notice import write_observability_notice +from powercontext.server.observability_notice import write_observability_notice def test_notice_lists_the_opt_in_commands(capsys: pytest.CaptureFixture[str]) -> None: diff --git a/tests/test_ops_local_policy.py b/tests/test_ops_local_policy.py index 9650d6bf58..810bb9c3b6 100644 --- a/tests/test_ops_local_policy.py +++ b/tests/test_ops_local_policy.py @@ -22,7 +22,7 @@ import pytest -from powercontext.cli.env_file import parse_environment +from powercontext.env_file import parse_environment from powercontext.ops.local_policy import ( classify_database, default_data_dir, diff --git a/tests/test_owner_recovery.py b/tests/test_owner_recovery.py index c9b8cb2687..0281551059 100644 --- a/tests/test_owner_recovery.py +++ b/tests/test_owner_recovery.py @@ -23,8 +23,7 @@ import pytest from sqlalchemy import Column, MetaData, String, Table, event, insert, select, update -from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile -from powercontext.server.authz import ( +from powercontext.builtin.authz import ( AccessAuditContext, AccessConflictError, AccessUnavailableError, @@ -32,8 +31,9 @@ PrincipalRef, ResourceRef, ) -from powercontext.server.authz.composition import open_builtin_access_control -from powercontext.server.authz.owner_recovery import OWNER_RECOVERY_TABLE, OwnerRecovery +from powercontext.builtin.authz.composition import open_builtin_access_control +from powercontext.builtin.authz.owner_recovery import OWNER_RECOVERY_TABLE, OwnerRecovery +from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile ALICE = PrincipalRef(type="user", id="alice") BOB = PrincipalRef(type="user", id="bob") diff --git a/tests/test_processing_security.py b/tests/test_processing_security.py index 905e30f5cb..6d8cf05c25 100644 --- a/tests/test_processing_security.py +++ b/tests/test_processing_security.py @@ -21,16 +21,17 @@ import pytest from pydantic import SecretStr +from powercontext.builtin.authz import AccessControlService, PrincipalRef +from powercontext.builtin.authz.repository import ACCESS_TABLES, RelationalAccessRepository +from powercontext.builtin.authz.service import BuiltinAuthorizationProvider +from powercontext.builtin.authz.worker import WorkerSecuritySpec from powercontext.builtin.persistence.migrations.deployment import deployment_runner from powercontext.builtin.persistence.sqlite import SQLiteConfig, SQLiteProfile from powercontext.builtin.runtime.composition import BuiltinConfigurationError from powercontext.builtin.runtime.config import InferenceConfig -from powercontext.server.authz import AccessControlService, PrincipalRef -from powercontext.server.authz.repository import ACCESS_TABLES, RelationalAccessRepository -from powercontext.server.authz.service import BuiltinAuthorizationProvider from powercontext.server.cli import _run_background_async from powercontext.server.factory import create_server_app -from powercontext.server.processing_security import WorkerSecuritySpec, build_worker_security +from powercontext.server.processing_security import build_worker_security from powercontext.server.settings import AccessControlConfig, BearerAuthConfig, ServerSettings from powercontext.server.tracing import ServerTracing diff --git a/tests/test_provider_observability.py b/tests/test_provider_observability.py index ba6dfe2f08..0f043d8c8f 100644 --- a/tests/test_provider_observability.py +++ b/tests/test_provider_observability.py @@ -221,7 +221,6 @@ def test_sdk_retries_have_three_http_attempts_and_one_final_success(tmp_path, mo async def scenario(): async with open_builtin_runtime( _config(tmp_path, endpoint), - scheduler_path=tmp_path / "scheduler.db", provider_observer=metrics.observe_provider, ) as runtime: result = await _create(runtime) @@ -252,7 +251,6 @@ def test_minimax_http_success_and_business_failure_are_separate(tmp_path): async def scenario(): async with open_builtin_runtime( _config(tmp_path, endpoint, "minimax"), - scheduler_path=tmp_path / "scheduler.db", provider_observer=metrics.observe_provider, ) as runtime: with pytest.raises(InferenceUnavailableError): @@ -274,7 +272,6 @@ def test_readiness_traffic_is_excluded_from_model_operations(tmp_path, monkeypat async def scenario(): async with open_builtin_runtime( _config(tmp_path, endpoint), - scheduler_path=tmp_path / "scheduler.db", provider_observer=metrics.observe_provider, ) as runtime: await runtime.readiness() @@ -298,7 +295,6 @@ def failed_observer(_observation): async def scenario(): async with open_builtin_runtime( _config(tmp_path, endpoint), - scheduler_path=tmp_path / "scheduler.db", provider_observer=failed_observer, ) as runtime: assert (await _create(runtime)).changed @@ -437,7 +433,6 @@ def failed_bootstrap(_client): async def scenario(): async with open_builtin_runtime( _config(tmp_path, endpoint, "minimax"), - scheduler_path=tmp_path / "scheduler.db", provider_observer=metrics.observe_provider, ) as runtime: assert (await _create(runtime)).changed diff --git a/tests/test_server.py b/tests/test_server.py index 44b184346c..36e9a3f182 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -33,6 +33,7 @@ import powercontext.builtin.runtime.composition as runtime_composition from powercontext.builtin.artifacts.experience import ExperienceCandidateInput from powercontext.builtin.artifacts.memory import EmbeddingProfile +from powercontext.builtin.authz import AccessControlService from powercontext.builtin.inference import EmbeddingResult, InferenceConfigurationError from powercontext.builtin.inference.pydantic_ai import PydanticAIConfigurationError from powercontext.builtin.persistence.database import AsyncDatabase @@ -51,7 +52,6 @@ ReadinessStatus, ) from powercontext.server.app import create_app -from powercontext.server.authz import AccessControlService from powercontext.server.factory import create_server_app from powercontext.server.settings import ( AccessControlConfig, @@ -546,6 +546,18 @@ def test_supervisor_uses_primary_database_without_scheduler_sidecar(tmp_path, mo assert not (data_dir / "scheduler.db").exists() +def test_server_app_ignores_deprecated_scheduler_path(tmp_path, monkeypatch) -> None: + monkeypatch.setenv("POWERCONTEXT_HOME", str(tmp_path / "powercontext-data")) + sidecar = tmp_path / "scheduler.db" + + with pytest.warns(DeprecationWarning, match="scheduler_path is ignored"): + app = create_server_app(settings=ServerSettings(mcp=McpConfig(enabled=False)), scheduler_path=sidecar) + with TestClient(app): + pass + + assert not sidecar.exists() + + def test_settings_load_bearer_authentication_without_exposing_token(monkeypatch) -> None: monkeypatch.setenv("POWERCONTEXT_SERVER_ACCESS_MODE", "enforced") monkeypatch.setenv("POWERCONTEXT_SERVER_AUTH_TOKEN", "server-secret") diff --git a/tests/test_server_logging.py b/tests/test_server_logging.py index 14c3b7873f..ade14a5f40 100644 --- a/tests/test_server_logging.py +++ b/tests/test_server_logging.py @@ -693,7 +693,6 @@ def test_server_warns_when_using_an_in_memory_database(caplog, tmp_path) -> None database=SQLiteConfig(), mcp=McpConfig(enabled=False), ), - scheduler_path=tmp_path / "scheduler.db", ) with caplog.at_level(logging.WARNING, logger="powercontext.server.factory"), TestClient(app) as client: diff --git a/tests/test_server_tracing.py b/tests/test_server_tracing.py index b2f9a0d517..c45c079895 100644 --- a/tests/test_server_tracing.py +++ b/tests/test_server_tracing.py @@ -541,7 +541,6 @@ def test_readiness_ignores_tracing_setup_failure(monkeypatch, tmp_path) -> None: metrics=MetricsConfig(enabled=False), logging=ServerLoggingConfig(access=False), ), - scheduler_path=tmp_path / "scheduler.db", tracing=tracing, ) diff --git a/tests/test_service_flow_observability.py b/tests/test_service_flow_observability.py index f388a78e78..787b863156 100644 --- a/tests/test_service_flow_observability.py +++ b/tests/test_service_flow_observability.py @@ -26,6 +26,7 @@ from fastapi.testclient import TestClient from prometheus_client.parser import text_string_to_metric_families +from powercontext.builtin.authz.errors import AccessDeniedError from powercontext.builtin.inference import InferenceTimeoutError from powercontext.builtin.persistence.sqlite import SQLiteConfig from powercontext.builtin.runtime.artifact_processing import ( @@ -38,7 +39,6 @@ ) from powercontext.builtin.runtime.processing_contracts import ArtifactProcessingBlock from powercontext.builtin.runtime.processing_observation import observe_processing -from powercontext.server.authz.errors import AccessDeniedError from powercontext.server.factory import create_server_app from powercontext.server.logging import JsonFormatter, OperationalContextFilter, _HumanContextFilter from powercontext.server.settings import McpConfig, ServerSettings diff --git a/tests/test_source_management.py b/tests/test_source_management.py index 6b37e64a62..1c6db150e8 100644 --- a/tests/test_source_management.py +++ b/tests/test_source_management.py @@ -122,7 +122,6 @@ async def source_server(tmp_path, *, management=True): request_seconds=2, ), ), - scheduler_path=tmp_path / "scheduler.db", ) async with ( listen(app) as url, diff --git a/tests/test_system_cli.py b/tests/test_system_cli.py index 02d4fb1c99..493fe7e44d 100644 --- a/tests/test_system_cli.py +++ b/tests/test_system_cli.py @@ -37,7 +37,6 @@ from powercontext.cli.installation import PluginSource from powercontext.cli.installation import setup as install_plugin from powercontext.cli.system import Diagnostic, DiagnosticStatus, SetupError, doctor_app, setup_app -from powercontext.paths import default_scheduler_path from powercontext.server.settings import ServerSettings from powercontext.service.model import ( DefinitionState, @@ -114,7 +113,6 @@ def test_server_defaults_to_persistent_user_storage( assert settings.database.kind == "sqlite" database_path = (data_dir / "powercontext.db").as_posix() assert settings.database.url == f"sqlite+aiosqlite:///{database_path}" - assert default_scheduler_path() == data_dir / "scheduler.db" @pytest.mark.parametrize("already_disabled", [False, True]) diff --git a/tests/test_upgrade_release_gate.py b/tests/test_upgrade_release_gate.py index 715d4f4cc8..c1f19facb8 100644 --- a/tests/test_upgrade_release_gate.py +++ b/tests/test_upgrade_release_gate.py @@ -150,7 +150,7 @@ def test_supported_mode_cannot_succeed_with_an_empty_matrix(release): "relative", [ "src/powercontext/server/identity.py", - "src/powercontext/server/authz/repository.py", + "src/powercontext/builtin/authz/repository.py", "src/powercontext/builtin/code/seekdb.py", "src/powercontext/limits.py", ], @@ -792,7 +792,7 @@ def test_seekdb_diagnostics_share_one_budget_with_maintenance_evidence(tmp_path) "src/powercontext/builtin/persistence/tables.py", "src/powercontext/builtin/persistence/revision.sql", "src/powercontext/builtin/code/layout.json", - "src/powercontext/server/authz/repository.py", + "src/powercontext/builtin/authz/repository.py", "src/powercontext/server/identity.py", "src/powercontext/limits.py", ],