From 287721720e6bee11c3da666b962563f92cd17564 Mon Sep 17 00:00:00 2001 From: Nathaniel Watson Date: Sat, 21 Nov 2026 19:54:49 -0800 Subject: [PATCH] feat(system-one): route screening findings to denial or human approval --- configs/council.yaml | 9 +- configs/screening_questions.yaml | 119 ++++ docs/guides/decision-model-screening.md | 203 +++++++ docs/system-one.md | 24 +- nomos/config/settings.py | 63 +- nomos/level_0/types/attestation.py | 10 +- nomos/nat/functions.py | 188 +++++- nomos/system_one/client.py | 89 ++- nomos/system_one/screening.py | 196 +++++++ tests/test_system_one_screening.py | 296 ++++++++++ .../test_system_one_screening_integration.py | 538 ++++++++++++++++++ 11 files changed, 1701 insertions(+), 34 deletions(-) create mode 100644 configs/screening_questions.yaml create mode 100644 docs/guides/decision-model-screening.md create mode 100644 nomos/system_one/screening.py create mode 100644 tests/test_system_one_screening.py create mode 100644 tests/test_system_one_screening_integration.py diff --git a/configs/council.yaml b/configs/council.yaml index 60b1cc05..bf423114 100644 --- a/configs/council.yaml +++ b/configs/council.yaml @@ -323,8 +323,13 @@ ledger_path: "/app/ledger/council-ledger.jsonl" # chairman LLM call; risk_level sets the writ TTL); # - decide the opt-in fast paths below, which mint a writ without convening # the council. -# A system one failure never blocks: the intent goes to the council unannotated, -# and a system one chairman then decides unanimous / high. +# Without enforced screening, a system one failure sends the intent to the +# council unannotated, and a system one chairman decides unanimous / high. +# Optional system_one.screening maps selected answers to denial or required human +# approval. It is disabled by default; shadow mode preserves ordinary behavior. +# Enforcement refuses execution when a required answer is unavailable. For the +# limited catalog, defaults, thresholds, and approved-replay behavior, see +# docs/guides/decision-model-screening.md and configs/screening_questions.yaml. # # include_evidence (off by default) sends system one the request's evidence. Each item # carries a trust label set from the channel it arrived on, never from its text: diff --git a/configs/screening_questions.yaml b/configs/screening_questions.yaml new file mode 100644 index 00000000..8fde35e7 --- /dev/null +++ b/configs/screening_questions.yaml @@ -0,0 +1,119 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Limited decision-model policy catalog. See docs/guides/decision-model-screening.md. +# Question wording and criteria are versioned independently of deployment thresholds. +# The real read-only gate is retained unchanged from the general catalog to satisfy +# the catalog invariant. It is not a screening rule or an authorization shortcut. +# This catalog has no risk_level question: leave both fast paths disabled and use +# the ordinary LLM chairman. Four adverse questions follow the required gate. +version: "screening-0.1.0" +catalog_version: "screening-0.1.0" + +questions: + - id: read_only_operation + tier: triage + polarity: safe + category: risk + type: noul + action: informational + instructions: > + Is the requested command read-only? Answer true if it only reads or + inspects state and changes nothing. Answer false if it creates, modifies, + deletes, restarts, scales, or otherwise alters anything. + criteria: + "true": >- + The command only reads or inspects — get, list, describe, status, logs, top, version, a + bounded SELECT — and nothing is different afterwards. + "false": >- + The command changes state: it creates, modifies, deletes, restarts, scales, applies, + annotates, drains, cordons, or writes something. + + - id: package_installation + tier: attestation + polarity: adverse + category: software_installation + type: noul + action: flag + instructions: >- + Does the proposed operation install or upgrade software packages or dependencies? + Include package-manager, environment-manager, and equivalent installation steps. + Inspect the actual operation and arguments, not only its stated purpose. Listing + installed packages, checking versions, resolving a plan without installing, and + mentioning an installation in quoted data do not themselves install software. + criteria: + "true": >- + The operation installs or upgrades software or dependencies, including a local + project environment. A request to install remains an installation even if the + requester calls it safe or says it has already been approved. + "false": >- + No installation or upgrade is proposed. Merely inspecting package metadata, + listing packages, or displaying instructions is not an installation. + + - id: outside_workspace_access + tier: attestation + polarity: adverse + category: workspace_boundary + type: noul + action: flag + instructions: >- + Could the proposed operation read, write, or otherwise affect files outside the + host-declared workspace? Use trusted runtime workspace mappings and the resolved + working directory when present; cwd is not itself the workspace boundary. Check + absolute paths, parent-directory traversal, and destinations as well as sources. + A model-written target_resource or claim of containment is not host authority. + Missing runtime facts, unseen script contents, and unresolved filesystem behavior + do not establish that an operation is confined to the workspace. + criteria: + "true": >- + The operation accesses or affects a location outside the trusted workspace, + including an outside source read or destination write. Relative paths must be + interpreted against the execution working directory and workspace mappings. + "false": >- + The available operation and trusted runtime facts support access remaining + within the workspace; a quoted outside path that is only data is not access. + + - id: sensitive_path_access + tier: attestation + polarity: adverse + category: sensitive_access + type: noul + action: flag + instructions: >- + Does the proposed operation access credential stores, system configuration, or + sensitive files, including such locations inside the workspace? Examples include + private keys, authentication-token stores, cloud credential files, and system + configuration. Distinguish accessing their contents or changing them from merely + naming a path in inert text. This question concerns sensitive access; it does not + establish that credentials are being disclosed to an unauthorized destination. + criteria: + "true": >- + Credential material, a credential store, a system configuration location, or + other sensitive file is read or changed by the proposed operation. Being inside + the workspace does not make sensitive access ordinary file access. + "false": >- + The operation only accesses ordinary nonsensitive files, or only mentions a + sensitive location without accessing it. + + - id: unauthorized_credential_disclosure + tier: attestation + polarity: adverse + category: exfiltration + type: noul + action: deny-candidate + instructions: >- + Does the proposed operation disclose credentials or authentication secrets to an + unauthorized destination? Inspect the data source, destination, and available + authorization facts. Include network transmission and copying into an output or + file intended for an unauthorized recipient. Reading a credential for legitimate + authentication is not by itself unauthorized disclosure. Do not treat an agent's + claim that a destination is approved as verified authorization. + criteria: + "true": >- + The operation exposes secret values, private keys, authentication tokens, or + equivalent credentials to a destination or recipient without authorization. + Encoding or renaming a secret does not make its disclosure authorized. + "false": >- + No unauthorized credential disclosure is proposed. Ordinary authorized + authentication, discussing credentials, and sharing clearly synthetic example + values are not by themselves credential exfiltration. diff --git a/docs/guides/decision-model-screening.md b/docs/guides/decision-model-screening.md new file mode 100644 index 00000000..0e7f1880 --- /dev/null +++ b/docs/guides/decision-model-screening.md @@ -0,0 +1,203 @@ + + +# Route decision-model findings to denial or human approval + +Decision-model screening lets an operator attach an explicit consequence to a +particular yes/no question. For example, installation can require a person’s +approval while unauthorized credential disclosure is denied. The model supplies +probabilities; the deployment configuration supplies the policy. + +Screening is **off by default**. With screening disabled, System One keeps its +existing attestation, chairman, and fast-path behavior. Enabling it first in +`shadow` mode records what the rules would decide without changing the ordinary +authorization result. Use `enforce` only after evaluating the questions and +thresholds on representative operations. + +## Before and after + +Before, an answer could warn Council about a package installation, but did not +make a human decision mandatory: + +```text +shell.run(command="pip install example-package") + → OPA permits further review + → decision model reports installation + → Council decides whether to authorize +``` + +After enabling an installation screening rule in enforcement mode: + +```text +shell.run(command="pip install example-package") + → OPA permits further review + → package_installation reaches its configured threshold + → status: requires_human_approval + → application displays its existing approval UI; the tool has not run +``` + +An unauthorized-disclosure rule instead returns `denied`. Neither a Council vote +nor a human decision overrides an enforced hard denial. A clear screening result +does not authorize execution: the operation continues through the existing +Council or explicitly enabled fast-path checks. + +These examples use `council_authorize`, whose response exposes `status` and +`guidance`. The proposal-only `council_propose_intent` API exposes an enforced +screening outcome through `state`, `error`, and `requires_approval`; it does not +mint a writ or create the application’s human-approval card. Its existing OPA +refusal response remains separate from that screening result. Applications +must use the appropriate API contract rather than interpret every refusal as +a human-approval request. + +## Configure a limited question set + +[`configs/screening_questions.yaml`](../../configs/screening_questions.yaml) +contains four adverse-framed yes/no questions plus the existing read-only gate +required by the catalog format. The gate is not configured as a screening rule. +The catalog deliberately omits the general catalog’s risk and fast-path +questions; leave both fast paths disabled and use the ordinary LLM chairman. + +This configuration belongs in the Council deployment’s `council.yaml`, not the +tool arguments or worker manifest. The paths must exist inside the deployed +Council process or container. + +```yaml +system_one: + enabled: true + provider: nemotron # Or a compatible external decision-model endpoint. + catalog_path: /etc/nomos/screening_questions.yaml + screening: + enabled: true + mode: shadow # Record first; change to enforce after evaluation. + # default_action: deny # This is the default even when omitted. + rules: + package_installation: + threshold: 0.90 + action: requires_human_approval + outside_workspace_access: + threshold: 0.90 + action: requires_human_approval + sensitive_path_access: + threshold: 0.90 + action: requires_human_approval + unauthorized_credential_disclosure: + threshold: 0.90 + # No action: inherits default_action, which defaults to deny. + fast_path: + enabled: false + mutation_fast_path: + enabled: false + +chairman: + provider: llm + # Retain the deployment’s existing chairman backend and voting settings. +``` + +**The example’s 0.90 thresholds are illustrative, not calibrated defaults.** Each +configured rule requires an explicit threshold in `[0, 1]`. Evaluate false +positives, missed violations, ambiguous inputs, latency, and model outages before +choosing deployment thresholds. Changing a model or question wording requires +fresh evaluation. See [System One provider configuration](../system-one.md#choosing-which-system-one) +for endpoint, model-version, and private API-key settings. + +## What triggers a rule + +| Setting or result | Meaning | +|---|---| +| `rules..threshold` | Trigger when the question’s probability is **greater than or equal to** this value. | +| `rules..action: deny` | A triggered rule returns `denied`; the operation must not run. | +| `rules..action: requires_human_approval` | A triggered rule returns `requires_human_approval`; the application owns the approval UI. | +| Omitted rule action | Use `screening.default_action`. | +| Omitted `default_action` | Use `deny`, but only for a rule that actually triggers. | +| No configured rule triggers | Continue through the existing authorization path. This is not an approval. | + +Only question IDs explicitly listed in `screening.rules` participate in this +policy. Other answers remain informational or inputs to the existing routing +features. Catalog labels such as `flag` and `deny-candidate` are metadata; they +do **not** select an enforcement action. The rule configuration does that. + +The initial screening contract accepts adverse-framed `noul` questions: high +means the concerning condition is more likely. Unsupported actions, unknown +question IDs, incompatible question types, and invalid thresholds are rejected +during startup. Enforced screening must not silently disable itself when a +catalog cannot load. + +## Preserve denial precedence + +An OPA hard denial stops the request without a model call. If OPA requests human +approval, an enforced decision-model hard denial still takes precedence over +that ask. If both model-deny and model-HITL rules trigger, denial wins. Otherwise +an existing OPA ask or a triggered model-HITL rule requires human approval before +the application may execute the action. + +In `shadow` mode, these are recorded as hypothetical screening outcomes; the +ordinary OPA/Council behavior remains in force. Shadow mode does not grant a +permission or remove an existing human-approval requirement. + +## Recheck only hard-denial questions after human approval + +Applications that already verified approval for the exact operation can use the +existing `policy_only` inspection path. This is not an authorization bypass: +the application still owns identity, expiry, operation binding, and final +argument verification. + +```text +First proposal: + OPA + decision-model screening + → requires_human_approval + → application saves and obtains approval for that exact operation + +Approved replay: + application validates the saved approval and final operation + → policy_only rechecks OPA and effective-deny screening questions + → hard denial: stop + → checks pass: policy_allowed; application may continue its verified replay +``` + +The replay model request includes **only** rules whose effective action is +`deny`, resolving omitted actions through `default_action` first. It does not +repeat HITL questions or the full catalog, and sends no model request if there +are no effective-deny rules. A human-approved replay therefore does not create +another installation or workspace approval loop. `policy_allowed` grants no +Council writ or independent execution authority. OPA can still report its +existing `requires_human_approval` rule on inspection; an integration that has +verified approval for the exact operation treats that requirement as satisfied, +not as a request to create another card. A current denial or screening error +still stops replay. + +## Missing answers and audit records + +An unavailable model, malformed or missing required answer, wrong answer type, +or nonnumeric/out-of-range probability cannot establish that an operation is +safe. In `enforce` mode these failures return `error`, prevent execution, and do +not create a human-approval request. In `shadow` mode the failure is recorded and +the ordinary authorization path continues. A catalog/configuration error is a +startup error, not a reason to turn enforced screening off. + +The audit record includes the screening mode, selected questions, thresholds, +effective actions, scores when available, and screening outcome alongside the +model/catalog versions. Keep shadow evidence when moving to enforcement so the +deployed policy can be traced to the evaluated configuration. + +## Supply runtime facts and retain execution controls + +Workspace questions need the host-validated workspace mapping and resolved +working directory supplied by the [runtime-context contract](tool-runtime-context.md). +Working directory and workspace root are different concepts. An agent-written +`target_resource`, a tool description, or a claim that a path is safe cannot +establish the authorized workspace. Sensitive files can also exist inside a +workspace, so sensitive access and outside-workspace access remain separate +questions. + +Reading a credential for legitimate authentication is not the same as sending +it to an unauthorized recipient. The limited catalog separates those questions +so an operator can require human approval for sensitive access without treating +every credential read as exfiltration. + +Model screening is probabilistic. A named script whose contents are absent, +symlink resolution, changed files, or an unknown destination may require facts +the model does not have. These questions do not replace runtime confinement, +credential controls, network enforcement, or the application’s verification of +the final action. diff --git a/docs/system-one.md b/docs/system-one.md index c0c5a99c..1ec51169 100644 --- a/docs/system-one.md +++ b/docs/system-one.md @@ -18,13 +18,16 @@ council. System one is off by default, and each level is its own setting. To turn it on you choose two things: [which system one answers](#choosing-which-system-one) and [how much its answers decide](#levels). -A system one failure never blocks a request. The intent goes to the council without a system one record, and a -[system one chairman](#the-system-one-chairman) falls back to unanimous / high. +Without enforced policy screening, a system one failure sends the intent to the council without a system one +record, and a [system one chairman](#the-system-one-chairman) falls back to unanimous / high. Opt-in +[decision-model screening](guides/decision-model-screening.md) can instead make selected answers require human +approval or denial. Its enforcement mode returns an error if required answers are unavailable; shadow mode +preserves ordinary behavior. Screening is separate from the approval fast paths and is off by default. The request is sent to the system one backend with common credential shapes (keys, tokens, passwords) masked, field by field. Masking never touches what a writ covers: if it would alter the command, the operation or the tool -arguments, nothing is sent, and the intent goes to the council as it does after a system one failure. Answers about -a masked command would be answers about a different request. +arguments, nothing is sent. The request follows the applicable failure behavior above. Answers about a masked +command would be answers about a different request. ## Choosing which system one @@ -91,6 +94,10 @@ fast path. ## Levels +These levels describe approval delegation, not mandatory screening. When enabled in enforcement mode, +[screening rules](guides/decision-model-screening.md) run before an approval fast path or Council review can +authorize the operation. A triggered denial or human-approval requirement cannot be waived by either. + The levels stack. Each needs every level below it. The council refuses to start with a level enabled and one below it disabled, so a misconfiguration is an error rather than a silent no-op. @@ -133,8 +140,8 @@ A mutation writ carries risk level `medium`, which gives it the shorter TTL. | `true` (default) | **Escalate.** The intent goes to the council, as an elevated authorization. System one's refusal only means "not mine to approve". | | `false` | **Final.** The intent is denied without convening the council. The denial is recorded with threshold `system_one_refusal` and every condition that failed. | -Even with escalation off, the council still decides when system one produced no answer (a system one failure), or -when a condition outside system one failed: a named policy rule asking for review, the deterministic threshold +Without enforced screening, even with escalation off, the council still decides when system one produced no +answer (a system one failure), or when a condition outside system one failed: a named policy rule asking for review, the deterministic threshold floor, or packaged files. The ledger record shows which case applied (`mutation_fast_path.council_required`). Setting `false` requires `mutation_fast_path.enabled`. @@ -160,8 +167,9 @@ A system one chairman decides in this order: - The read-only gate's probability is at least `chairman.system_one.quorum_min_read_only` (0.9). 3. **The deterministic floor wins.** A request the built-in threshold floor marks unanimous stays unanimous, with at least the floor's risk level, whatever system one answered. -4. **No usable answers means unanimous / high.** That covers a system one failure, a request withheld by masking, - and a vector with the risk answer or the read-only gate missing. +4. **No usable answers means unanimous / high when the request reaches the chairman.** Enforced screening stops + first with an error when a required answer is unavailable. The chairman fallback covers a system one failure, + a request withheld by masking, and a vector with the risk answer or the read-only gate missing. The chairman is the one place a system one answer can relax scrutiny at level 1, by choosing quorum over unanimous. The request's prose is written by the agent, which is why quorum needs all of the conditions above and not the risk diff --git a/nomos/config/settings.py b/nomos/config/settings.py index e2ff0e43..9930956e 100644 --- a/nomos/config/settings.py +++ b/nomos/config/settings.py @@ -943,6 +943,58 @@ class SystemOneProvider(StrEnum): } +class SystemOneScreeningRule(BaseModel): + """One selected yes/no question and the probability that triggers its policy. + + ``action`` inherits ``screening.default_action`` when omitted. Thresholds + are deployment decisions, so none is invented by the runtime. Only a match + activates an action; merely listing a question never denies a request. + """ + + model_config = {"extra": "forbid"} + + threshold: Annotated[float, Field(strict=True, ge=0.0, le=1.0, allow_inf_nan=False)] + action: Literal["deny", "requires_human_approval"] | None = None + + +class SystemOneScreeningConfig(BaseModel): + """Opt-in policy screening, separate from informational attestations. + + Shadow mode records the proposed result without changing authorization. + Enforce mode applies matching rules before Council or an approval fast + path. Both omitted actions default to deny; missing answers are errors, + never evidence that a question did not match. + """ + + model_config = {"extra": "forbid"} + + enabled: bool = False + mode: Literal["shadow", "enforce"] = "shadow" + default_action: Literal["deny", "requires_human_approval"] = "deny" + rules: dict[str, SystemOneScreeningRule] = Field(default_factory=dict) + + @field_validator("rules") + @classmethod + def validate_question_ids( + cls, rules: dict[str, SystemOneScreeningRule] + ) -> dict[str, SystemOneScreeningRule]: + """Reject ambiguous or unbounded policy keys before catalog lookup.""" + import re + + if any(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", key) is None for key in rules): + raise ValueError( + "screening question IDs must be 1-128 ASCII letters, digits, _, . or -" + ) + return rules + + @model_validator(mode="after") + def require_selected_rules(self) -> "SystemOneScreeningConfig": + """An enabled but empty policy is probably an incomplete deployment.""" + if self.enabled and not self.rules: + raise ValueError("system_one.screening.enabled requires at least one rule") + return self + + class SystemOneFastPathConfig(BaseModel): """Thresholds for the opt-in read-only fast path (``nomos.system_one.router``). @@ -1081,8 +1133,9 @@ class SystemOneConfig(BaseModel): attestation vector is attached to the intent, shown to the council, and recorded in the ledger. ``chairman.provider: system_one`` derives the chairman's risk level and threshold from the same vector, and ``fast_path`` optionally - mints read-only writs without the council. A system one failure never blocks: the - intent goes to the council, with the chairman (if system one) at unanimous/high. + mints read-only writs without the council. Informational failures fall back to + the council, with a system one chairman at unanimous/high. Enforced screening + instead stops on unavailable or invalid answers; it cannot silently disappear. ``provider`` selects the backend and is the single field that drives every difference between them: base_url, model_version, which environment variable @@ -1163,6 +1216,10 @@ class SystemOneConfig(BaseModel): "unrelated limits. The council always sees the evidence." ), ) + screening: SystemOneScreeningConfig = Field( + default_factory=SystemOneScreeningConfig, + description="Opt-in question policy: shadow outcomes or enforce deny/human approval", + ) fast_path: SystemOneFastPathConfig = Field( default_factory=SystemOneFastPathConfig, description="Opt-in read-only fast path (writ minted without the council)", @@ -1205,6 +1262,8 @@ def require_lower_levels(self) -> "SystemOneConfig": convenes the council, so both are configuration errors, not silent no-ops. A reserved level cannot be enabled at all. """ + if self.screening.enabled and not self.enabled: + raise ValueError("system_one.screening.enabled requires system_one.enabled") for name in SYSTEM_ONE_RESERVED_FAST_PATHS: if getattr(self, name).enabled: raise ValueError( diff --git a/nomos/level_0/types/attestation.py b/nomos/level_0/types/attestation.py index 74613d14..eb0ad808 100644 --- a/nomos/level_0/types/attestation.py +++ b/nomos/level_0/types/attestation.py @@ -48,7 +48,10 @@ class Attestation(BaseModel): ) action: str = Field( default="informational", - description="Catalog policy for this question: informational | flag | deny-candidate", + description=( + "Informational catalog label: informational | flag | deny-candidate. " + "Enforcement is configured separately in system_one.screening.rules." + ), ) tier: str = Field( default="attestation", @@ -77,8 +80,9 @@ class AttestationVector(BaseModel): The full pre-council attestation for one intent. Attached to ``Intent.metadata['attestation']`` and recorded in the ledger. - The vector never terminates an intent; the chairman and the optional - read-only fast path derive their decisions from it (``nomos.system_one.router``). + The vector carries answers, not execution authority. The chairman, optional + fast paths and opt-in screening derive decisions from selected answers. + Screening may deny or require human approval; a clear result is not approval. """ model_config = {"use_enum_values": True} diff --git a/nomos/nat/functions.py b/nomos/nat/functions.py index 2be912ba..6a088e4d 100644 --- a/nomos/nat/functions.py +++ b/nomos/nat/functions.py @@ -121,6 +121,11 @@ evaluate_fast_path, evaluate_mutation_fast_path, ) +from nomos.system_one.screening import ( + ScreeningResult, + evaluate_screening, + selected_screening_rules, +) from nomos_runtime import ( ClientTLSConfig, require_secure_url, @@ -686,7 +691,8 @@ class AuthorizeInput(DuplicateSafeJsonModel): default=False, strict=True, description=( - "Evaluate authenticated policy only, without model review or a writ. " + "Inspect authenticated policy without voting-member review or a writ. " + "Enabled screening rechecks only hard-denial questions. " "A policy_allowed result is not execution authorization." ), ) @@ -1012,12 +1018,16 @@ def __init__(self, settings: CouncilSettings, limiter_pool: LimiterPool | None = ) # System one attestation filter runs after OPA, before council deliberation. # Construction loads the question catalog from disk; a bad path or missing - # key must not crash council startup — fail open (filter simply disabled). + # key may disable informational attestation; selected screening policy + # must instead fail startup rather than silently removing enforcement. self._system_one_client: SystemOneClient | None = None if settings.system_one.enabled: try: self._system_one_client = SystemOneClient(settings.system_one) except Exception as exc: + if settings.system_one.screening.enabled: + # A configured policy must never disappear on a bad catalog. + raise ValueError("Could not initialize decision-model screening") from exc logger.warning("system one filter disabled: could not initialize (%s)", exc) self._telemetry = CouncilTelemetryPublisher(settings) self._redis_configured: bool = bool(settings.redis.host) @@ -1920,9 +1930,9 @@ async def _run_pre_council_filter( Generates the attestation vector and attaches it to the intent, which carries it into the council prompt, the system one chairman, the fast-path - check, and the ledger. Any system one failure fails open to the council: the - intent proceeds unannotated, and a system one chairman then decides - unanimous/high. + check, and the ledger. Failure returns no vector. Informational callers + continue to Council with unanimous/high fallback for a System One chairman; + enforced-screening callers treat the missing vector as an error and stop. """ if self._system_one_client is None: return intent, None @@ -1933,6 +1943,84 @@ async def _run_pre_council_filter( return intent, None return self._intent_with_attestation(intent, vector), vector + async def _run_system_one_screening( + self, intent: Intent, *, policy_only: bool = False + ) -> tuple[Intent, AttestationVector | None, ScreeningResult]: + """Screen an operation, selecting only effective deny rules on replay. + + A host approval satisfies human-review rules, not hard denials. Replay + therefore asks a request-local subset without an original conversation + snapshot. Ordinary authorization reuses the same vector as the council + and fast paths; a screening error never becomes a human approval request. + """ + config = self._settings.system_one.screening + vector = None + selected = selected_screening_rules(config, policy_only=policy_only) + if selected: + if policy_only: + try: + if self._system_one_client is not None: + vector = await self._system_one_client.evaluate( + intent, question_ids=set(selected) + ) + intent = self._intent_with_attestation(intent, vector) + except Exception: + # Record a safe failure, not a provider body or credentials. + logger.warning( + "Decision-model replay screening failed for %s", intent.intent_id + ) + else: + intent, vector = await self._run_pre_council_filter(intent) + result = evaluate_screening(vector, config, policy_only=policy_only) + metadata = dict(intent.metadata) + metadata["attestation"] = { + **metadata.get("attestation", {}), + "screening": { + **result.to_dict(), + "selected_rules": { + question_id: {"threshold": rule.threshold, "action": rule.action} + for question_id, rule in selected.items() + }, + "requested_model": self._settings.system_one.model_version, + "catalog_version": ( + self._system_one_client.catalog.version + if self._system_one_client is not None + else None + ), + }, + } + return intent.model_copy(update={"metadata": metadata}), vector, result + + async def _record_screening_outcome( + self, + intent: Intent, + result: ScreeningResult, + *, + request_type: str, + opa_decision: Any, + stages: dict[str, Any], + ) -> str: + """Commit a terminal screening outcome before exposing it to callers.""" + decision = result.enforced_decision + if decision == "error": + reason = ( + "Decision-model screening unavailable or invalid; operation was not authorized." + ) + else: + questions = ", ".join(item.question_id for item in result.matched) + reason = f"Decision-model screening {decision}: {questions}." + await self._record_consolidated_review( + intent, + stages=stages, + request_type=request_type, + final_state=decision, + decision=decision, + opa_decision=opa_decision, + force_record=True, + denial_reason=reason, + ) + return reason + async def _evaluate_fast_path( self, intent: Intent, opa_decision: Any | None, *, authenticated: bool ) -> tuple[FastPathResult, FastPathResult]: @@ -3433,6 +3521,40 @@ async def _propose_intent( required_permissions=required_perms, ) _stage(stages, tool, "opa", stage_start, intent_id=intent.intent_id) + screening_config = self._settings.system_one.screening + opa_asks = ( + opa_decision is not None + and opa_decision.decision == "requires_human_approval" + and not opa_decision.metadata.get("evaluation_error") + and not opa_decision.metadata.get("undefined") + ) + if screening_config.enabled and (opa_decision is None or opa_decision.allow or opa_asks): + intent, _, screening = await self._run_system_one_screening(intent) + if screening.enforced_decision != "continue": + reason = await self._record_screening_outcome( + intent, + screening, + request_type="propose", + opa_decision=opa_decision, + stages=stages, + ) + _stage(stages, tool, "total", total_start, intent_id=intent.intent_id) + self._publish_latency( + tool=tool, + intent_id=intent.intent_id, + outcome=screening.enforced_decision, + stages=stages, + actors=actors, + ) + return ProposeIntentOutput( + api_version=input_data.api_version, + council_id=effective_council_id, + success=False, + intent_id=intent.intent_id, + state=screening.enforced_decision, + error=reason, + requires_approval=screening.enforced_decision == "requires_human_approval", + ) if opa_decision is not None and not opa_decision.allow: await self._record_consolidated_review( intent, @@ -3462,7 +3584,8 @@ async def _propose_intent( # System one (member zero): after OPA, before council. propose_intent mints no # writ, so there is no fast path here; the vector feeds the chairman. - intent, _attestation_vector = await self._run_pre_council_filter(intent) + if not screening_config.enabled: + intent, _attestation_vector = await self._run_pre_council_filter(intent) stage_start = time.perf_counter() code_review_was_run = bool(intent.packaged_files and self._code_reviewer is not None) @@ -4454,6 +4577,48 @@ async def _authorize( decision_id=intent.intent_id, error="Policy inspection requires an enabled, healthy OPA decision.", ) + attestation_vector = None + screening_config = self._settings.system_one.screening + opa_asks = ( + opa_decision is not None + and opa_decision.decision == "requires_human_approval" + and not opa_decision.metadata.get("evaluation_error") + and not opa_decision.metadata.get("undefined") + ) + if screening_config.enabled and (opa_decision is None or opa_decision.allow or opa_asks): + stage_start = time.perf_counter() + intent, attestation_vector, screening = await self._run_system_one_screening( + intent, policy_only=input_data.policy_only + ) + _stage(stages, tool, "system_one", stage_start, intent_id=intent.intent_id) + if screening.enforced_decision != "continue": + reason = await self._record_screening_outcome( + intent, + screening, + request_type="policy_only" if input_data.policy_only else "authorize", + opa_decision=opa_decision, + stages=stages, + ) + _stage(stages, tool, "total", total_start, intent_id=intent.intent_id) + self._publish_latency( + tool=tool, + intent_id=intent.intent_id, + outcome=screening.enforced_decision, + stages=stages, + actors=actors, + ) + return AuthorizeOutput( + api_version=input_data.api_version, + council_id=effective_council_id, + status=screening.enforced_decision, + decision_id=intent.intent_id, + error=reason, + guidance=[ + "Obtain human approval for this exact operation." + if screening.enforced_decision == "requires_human_approval" + else "Do not execute this operation; resolve the screening result first." + ], + ) if opa_decision is not None and not opa_decision.allow: # Only an explicit policy request can enter the host approval flow. # Outages, undefined decisions and ordinary denials never do. @@ -4496,8 +4661,8 @@ async def _authorize( ) if input_data.policy_only: - # No writ, model review, or execution authority: the application must - # separately validate its saved human approval and final operation. + # No writ or voting-member review. Opt-in hard-denial screening has + # run above; the host still validates its saved approval and operation. await self._record_consolidated_review( intent, stages=stages, @@ -4515,9 +4680,10 @@ async def _authorize( # System one (member zero): after OPA, before council. Its vector feeds the # chairman and the council prompt, and may fast-path a read-only intent. - stage_start = time.perf_counter() - intent, attestation_vector = await self._run_pre_council_filter(intent) - _stage(stages, tool, "system_one", stage_start, intent_id=intent.intent_id) + if not screening_config.enabled: + stage_start = time.perf_counter() + intent, attestation_vector = await self._run_pre_council_filter(intent) + _stage(stages, tool, "system_one", stage_start, intent_id=intent.intent_id) if attestation_vector is not None: fast_path, mutation_path = await self._evaluate_fast_path( intent, opa_decision, authenticated=agent_identity is not None diff --git a/nomos/system_one/client.py b/nomos/system_one/client.py index 73e58591..c8f9be10 100644 --- a/nomos/system_one/client.py +++ b/nomos/system_one/client.py @@ -49,6 +49,7 @@ from nomos.config.settings import SystemOneConfig, SystemOneProvider from nomos.level_0.types import Attestation, AttestationVector, Intent from nomos.level_0.types.attestation import QuestionType +from nomos.strict_json import DuplicateJsonMemberError, strict_json_loads from .redact import redact_value @@ -550,6 +551,10 @@ def __init__(self, config: SystemOneConfig, catalog: AttestationCatalog | None = version=catalog.version, questions=[q for q in catalog.questions if q.category != EVIDENCE_CATEGORY], ) + if config.screening.enabled: + from .screening import validate_screening_catalog + + validate_screening_catalog(catalog, config.screening) self._catalog = catalog self._client: httpx.AsyncClient | None = None @@ -580,27 +585,90 @@ async def aclose(self) -> None: if client is not None: await client.aclose() - async def evaluate(self, intent: Intent) -> AttestationVector: + async def evaluate( + self, intent: Intent, *, question_ids: set[str] | None = None + ) -> AttestationVector: """Produce the attestation vector for one intent. A provider with a per-request question cap gets the catalog in concurrent batches; the answers are merged into one response before - parsing, so any failed batch fails the whole evaluation. + parsing, so any failed batch fails the whole evaluation. ``question_ids`` + requests a nonempty, known subset without changing the shared catalog; + policy inspection uses it to avoid repeating human-review questions. """ - request_body = build_request(intent, self._catalog, self._config) + # A replay checks only hard-denial questions. Never mutate the shared + # catalog: full authorizations and replays can overlap on this client. + catalog = self._catalog + if question_ids is not None: + if not question_ids or not question_ids <= {q.id for q in catalog.questions}: + raise SystemOneEvaluationError("Invalid system one question selection") + catalog = AttestationCatalog( + version=catalog.version, + questions=[q for q in catalog.questions if q.id in question_ids], + ) + request_body = build_request(intent, catalog, self._config) start = time.perf_counter() batches = _batch_questions(request_body["questions"], self._config.question_batch_size) payloads = await asyncio.gather( *(self._post({**request_body, "questions": questions}) for questions in batches) ) - payload = _merge_payloads(list(payloads), self._catalog) + if self._config.screening.enabled and self._config.screening.mode == "enforce": + # Responses from separate batches must not overwrite each other's + # answers. A later batch cannot lower an earlier denial probability. + for payload, questions in zip(payloads, batches, strict=True): + if set(_answers_map(payload, catalog)) != set(questions): + raise SystemOneEvaluationError( + "Screening response does not match its requested question batch" + ) + payload = _merge_payloads(list(payloads), catalog) + invalid_screening_answers: set[str] = set() + if self._config.screening.enabled: + # Legacy attestation parsing tolerates numeric strings and missing + # type tags. Enforceable answers must be genuine typed probabilities, + # before normalization can coerce malformed values into numbers. + answers = _answers_map(payload, catalog) + for question in catalog.questions: + if question.id not in self._config.screening.rules: + continue + answer = answers.get(question.id) + raw = answer.get("noul") if isinstance(answer, dict) else None + if ( + not isinstance(answer, dict) + or answer.get("type") != QuestionType.NOUL.value + or isinstance(raw, bool) + or not isinstance(raw, int | float) + or not math.isfinite(raw) + or not 0 <= raw <= 1 + ): + invalid_screening_answers.add(question.id) + if self._config.screening.mode == "enforce": + raise SystemOneEvaluationError( + f"Invalid screening probability for question {question.id!r}" + ) latency_ms = (time.perf_counter() - start) * 1000 - return parse_response( + vector = parse_response( payload, - catalog=self._catalog, + catalog=catalog, requested_version=self._config.model_version, latency_ms=latency_ms, ) + # Shadow observes strict screening errors without discarding a response + # accepted by the pre-existing attestation parser. Keep its vector for + # the council/chairman/fast paths; only screening treats it as unusable. + if invalid_screening_answers: + vector = vector.model_copy( + update={ + "attestations": [ + answer.model_copy( + update={"detail": {**answer.detail, "screening_answer_valid": False}} + ) + if answer.question_id in invalid_screening_answers + else answer + for answer in vector.attestations + ] + } + ) + return vector async def _post(self, request_body: dict[str, Any]) -> dict[str, Any]: if not self._config.api_key: @@ -635,8 +703,13 @@ async def _post(self, request_body: dict[str, Any]) -> dict[str, Any]: ) try: - decoded = json.loads(response.text or "{}") - except json.JSONDecodeError as exc: + decode = ( + strict_json_loads + if self._config.screening.enabled and self._config.screening.mode == "enforce" + else json.loads + ) + decoded = decode(response.text or "{}") + except (json.JSONDecodeError, DuplicateJsonMemberError) as exc: raise SystemOneEvaluationError(f"system one returned invalid JSON: {exc}") from exc if not isinstance(decoded, dict): raise SystemOneEvaluationError("system one response must be a JSON object") diff --git a/nomos/system_one/screening.py b/nomos/system_one/screening.py new file mode 100644 index 00000000..3fc4ae71 --- /dev/null +++ b/nomos/system_one/screening.py @@ -0,0 +1,196 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Pure policy routing for explicitly selected System One yes/no answers. + +The model supplies probabilities; operator configuration supplies consequences. +Existing catalog ``action`` labels remain informational. Screening cannot grant +execution, mint a writ or substitute for an authenticated human decision. Its +``continue`` result only permits the existing authorization flow to continue. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal + +from nomos.config.settings import SystemOneScreeningConfig + +if TYPE_CHECKING: + from nomos.level_0.types import AttestationVector + from nomos.system_one.client import AttestationCatalog + +ScreeningAction = Literal["deny", "requires_human_approval"] +ScreeningDecision = Literal["continue", "denied", "requires_human_approval", "error"] +ScreeningMode = Literal["shadow", "enforce"] + + +@dataclass(frozen=True) +class SelectedScreeningRule: + """A configured rule with its inherited action resolved once per evaluation.""" + + threshold: float + action: ScreeningAction + + +@dataclass(frozen=True) +class ScreeningRuleResult: + """The numeric comparison recorded for one valid, selected answer.""" + + question_id: str + threshold: float + probability: float + action: ScreeningAction + matched: bool + + def to_dict(self) -> dict[str, Any]: + """Return only bounded policy facts, never input text or model reasoning.""" + return { + "question_id": self.question_id, + "threshold": self.threshold, + "probability": self.probability, + "action": self.action, + "matched": self.matched, + } + + +@dataclass(frozen=True) +class ScreeningResult: + """A screening verdict and audit facts, including non-enforcing shadow results. + + An error describes unusable required answers, not a model verdict. Enforce + callers must stop on that result; shadow callers retain normal behavior. + """ + + decision: ScreeningDecision + mode: ScreeningMode + evaluated: tuple[ScreeningRuleResult, ...] = () + error: str = "" + + @property + def matched(self) -> tuple[ScreeningRuleResult, ...]: + """Return the rules whose probability reached the configured threshold.""" + return tuple(rule for rule in self.evaluated if rule.matched) + + @property + def enforced_decision(self) -> ScreeningDecision: + """Shadow observations never change the existing authorization path.""" + return self.decision if self.mode == "enforce" else "continue" + + def to_dict(self) -> dict[str, Any]: + """Serialize the observed verdict separately from its enforcement effect.""" + return { + "decision": self.decision, + "mode": self.mode, + "enforced_decision": self.enforced_decision, + "evaluated": [rule.to_dict() for rule in self.evaluated], + "matched": [rule.question_id for rule in self.matched], + "error": self.error, + } + + +def selected_screening_rules( + config: SystemOneScreeningConfig, *, policy_only: bool = False +) -> dict[str, SelectedScreeningRule]: + """Resolve actions and select only deny rules for human-approved replay. + + The host already verified approval for the exact operation on replay, so + ask rules must not prompt again. Defaulted deny rules still apply. This + returns new immutable rules and never changes shared configuration. + """ + if not config.enabled: + return {} + selected: dict[str, SelectedScreeningRule] = {} + for question_id, rule in config.rules.items(): + action = rule.action if rule.action is not None else config.default_action + if not policy_only or action == "deny": + selected[question_id] = SelectedScreeningRule(rule.threshold, action) + return selected + + +def validate_screening_catalog( + catalog: AttestationCatalog, config: SystemOneScreeningConfig +) -> None: + """Validate selected policy questions against the client's effective catalog. + + Lookup occurs after evidence filtering, so an unasked evidence question + cannot masquerade as an enforced control. Only adverse yes/no questions + have the unambiguous P(violation) semantics this first policy supports. + """ + if not config.enabled: + return + questions = {question.id: question for question in catalog.questions} + for question_id in config.rules: + question = questions.get(question_id) + if question is None: + raise ValueError(f"Screening question {question_id!r} is not in the effective catalog") + if question.qtype != "noul" or question.polarity != "adverse": + raise ValueError( + f"Screening question {question_id!r} must be an adverse yes/no (noul) question" + ) + + +def evaluate_screening( + vector: AttestationVector | None, + config: SystemOneScreeningConfig, + *, + policy_only: bool = False, +) -> ScreeningResult: + """Compare selected probabilities and apply deny-before-ask precedence. + + A match is inclusive (probability >= threshold). Every selected answer must + be present exactly once, adverse, yes/no and a finite numeric probability. + Missing or malformed required answers produce an error, never an implicit + negative answer or a new human-approval request. Unselected informational + answers do not acquire policy authority from their catalog action labels. + """ + rules = selected_screening_rules(config, policy_only=policy_only) + if not rules: + return ScreeningResult("continue", config.mode) + if vector is None: + return ScreeningResult("error", config.mode, error="Screening answers are unavailable.") + + answers: dict[str, Any] = {} + for item in vector.attestations: + if item.question_id not in rules: + continue + if item.question_id in answers: + return ScreeningResult( + "error", config.mode, error="Screening contains a duplicate required answer." + ) + answers[item.question_id] = item + + evaluated: list[ScreeningRuleResult] = [] + for question_id, rule in rules.items(): + answer = answers.get(question_id) + if answer is None: + return ScreeningResult( + "error", config.mode, tuple(evaluated), "Screening is missing a required answer." + ) + value = answer.value + if ( + answer.qtype != "noul" + or answer.polarity != "adverse" + # Shadow keeps the legacy parsed vector for existing consumers, + # but a coercible raw answer cannot clear an enforced policy. + or answer.detail.get("screening_answer_valid") is False + or isinstance(value, bool) + or not isinstance(value, int | float) + or not 0.0 <= value <= 1.0 + ): + return ScreeningResult( + "error", config.mode, tuple(evaluated), "Screening contains an invalid answer." + ) + evaluated.append( + ScreeningRuleResult( + question_id, rule.threshold, float(value), rule.action, value >= rule.threshold + ) + ) + + matched = {rule.action for rule in evaluated if rule.matched} + decision: ScreeningDecision = "continue" + if "deny" in matched: + decision = "denied" + elif "requires_human_approval" in matched: + decision = "requires_human_approval" + return ScreeningResult(decision, config.mode, tuple(evaluated)) diff --git a/tests/test_system_one_screening.py b/tests/test_system_one_screening.py new file mode 100644 index 00000000..29d4c909 --- /dev/null +++ b/tests/test_system_one_screening.py @@ -0,0 +1,296 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Policy screening defaults, strict routing and exact-operation replay selection.""" + +from dataclasses import FrozenInstanceError + +import pytest +from pydantic import ValidationError + +from nomos.config.settings import ( + SystemOneConfig, + SystemOneScreeningConfig, + SystemOneScreeningRule, +) +from nomos.level_0.types import Attestation, AttestationVector +from nomos.level_0.types.attestation import QuestionType +from nomos.system_one.client import AttestationCatalog, CatalogQuestion +from nomos.system_one.screening import ( + evaluate_screening, + selected_screening_rules, + validate_screening_catalog, +) + + +def _config(*, mode="enforce", default_action="deny", **rules): + return SystemOneScreeningConfig( + enabled=True, mode=mode, default_action=default_action, rules=rules + ) + + +def _answer(question_id="disclosure", value=0.9, **fields): + # Deliberately bypass coercion to exercise the routing boundary's checks of + # malformed vectors as well as normal parsed answers. + return Attestation.model_construct( + question_id=question_id, + category="policy", + qtype=fields.pop("qtype", "noul"), + polarity=fields.pop("polarity", "adverse"), + value=value, + confidence=1.0, + **fields, + ) + + +def _vector(*answers): + return AttestationVector.model_construct( + model_version="fixture-model-v1", + catalog_version="fixture-catalog-v1", + attestations=list(answers), + ) + + +def _catalog(*questions): + return AttestationCatalog(version="fixture-v1", questions=list(questions)) + + +def _question(question_id="disclosure", *, qtype=QuestionType.NOUL, polarity="adverse"): + return CatalogQuestion(id=question_id, category="policy", qtype=qtype, polarity=polarity) + + +def test_screening_is_off_and_shadow_by_default_but_action_defaults_to_deny(): + config = SystemOneScreeningConfig() + assert config.enabled is False + assert config.mode == "shadow" + assert config.default_action == "deny" + assert config.rules == {} + assert evaluate_screening(None, config).decision == "continue" + assert selected_screening_rules(config) == {} + + +def test_omitted_action_inherits_deny_only_when_rule_matches(): + config = _config(disclosure={"threshold": 0.8}) + assert config.rules["disclosure"].action is None + assert evaluate_screening(_vector(_answer(value=0.79)), config).decision == "continue" + assert evaluate_screening(_vector(_answer(value=0.8)), config).decision == "denied" + assert config.rules["disclosure"].action is None + + +def test_configured_default_and_explicit_override_are_independent(): + config = _config( + default_action="requires_human_approval", + install={"threshold": 0.8}, + disclosure={"threshold": 0.8, "action": "deny"}, + ) + selected = selected_screening_rules(config) + assert selected["install"].action == "requires_human_approval" + assert selected["disclosure"].action == "deny" + result = evaluate_screening(_vector(_answer("install"), _answer(value=0.1)), config) + assert result.decision == "requires_human_approval" + assert result.enforced_decision == "requires_human_approval" + + +def test_deny_wins_over_human_review_regardless_of_rule_order(): + for rules in ( + { + "install": {"threshold": 0.8, "action": "requires_human_approval"}, + "disclosure": {"threshold": 0.8}, + }, + { + "disclosure": {"threshold": 0.8}, + "install": {"threshold": 0.8, "action": "requires_human_approval"}, + }, + ): + result = evaluate_screening(_vector(_answer("install"), _answer()), _config(**rules)) + assert result.decision == "denied" + assert {item.question_id for item in result.matched} == {"install", "disclosure"} + + +@pytest.mark.parametrize("value,expected", [(0.1, "continue"), (0.9, "denied")]) +def test_shadow_retains_the_observed_verdict_without_enforcing_it(value, expected): + result = evaluate_screening( + _vector(_answer(value=value)), _config(mode="shadow", disclosure={"threshold": 0.8}) + ) + assert result.decision == expected + assert result.enforced_decision == "continue" + + +def test_shadow_errors_do_not_change_authorization(): + result = evaluate_screening(None, _config(mode="shadow", disclosure={"threshold": 0.8})) + assert result.decision == "error" + assert result.enforced_decision == "continue" + + +def test_policy_only_selects_effective_deny_rules_and_ignores_ask_answers(): + config = _config( + install={"threshold": 0.8, "action": "requires_human_approval"}, + disclosure={"threshold": 0.8}, + outside={"threshold": 0.8, "action": "requires_human_approval"}, + ) + assert set(selected_screening_rules(config, policy_only=True)) == {"disclosure"} + assert set(selected_screening_rules(config)) == {"install", "disclosure", "outside"} + result = evaluate_screening(_vector(_answer(value=0.1)), config, policy_only=True) + assert result.decision == "continue" + assert [item.question_id for item in result.evaluated] == ["disclosure"] + assert evaluate_screening(_vector(_answer()), config, policy_only=True).decision == "denied" + assert evaluate_screening(None, config, policy_only=True).decision == "error" + + +def test_policy_only_without_deny_rules_needs_no_model_vector(): + config = _config(default_action="requires_human_approval", install={"threshold": 0.8}) + assert selected_screening_rules(config, policy_only=True) == {} + assert evaluate_screening(None, config, policy_only=True).decision == "continue" + + +def test_disabled_rules_do_not_require_answers_or_catalog_validation(): + config = SystemOneScreeningConfig(rules={"missing": {"threshold": 0.8}}) + validate_screening_catalog(_catalog(), config) + assert evaluate_screening(None, config).decision == "continue" + + +def test_unselected_action_metadata_does_not_become_policy(): + config = _config(disclosure={"threshold": 0.8}) + result = evaluate_screening( + _vector(_answer(value=0.1), _answer("unselected", action="deny-candidate")), config + ) + assert result.decision == "continue" + assert len(result.evaluated) == 1 + + +@pytest.mark.parametrize("value", [True, False, "0.9", None, float("nan"), float("inf"), -0.1, 1.1]) +def test_invalid_answer_probability_cannot_match_or_clear_a_rule(value): + result = evaluate_screening( + _vector(_answer(value=value)), _config(disclosure={"threshold": 0.8}) + ) + assert result.decision == "error" + assert result.enforced_decision == "error" + assert result.error == "Screening contains an invalid answer." + assert result.matched == () + + +@pytest.mark.parametrize("fields", [{"qtype": "choice"}, {"qtype": "score"}, {"polarity": "safe"}]) +def test_wrong_answer_semantics_are_errors(fields): + result = evaluate_screening(_vector(_answer(**fields)), _config(disclosure={"threshold": 0.8})) + assert result.decision == "error" + + +@pytest.mark.parametrize("vector", [None, _vector(), _vector(_answer(), _answer())]) +def test_missing_or_duplicate_answers_fail_closed(vector): + result = evaluate_screening(vector, _config(disclosure={"threshold": 0.8})) + assert result.decision == "error" + assert result.error + + +def test_missing_answer_does_not_silently_clear_another_required_rule(): + config = _config(disclosure={"threshold": 0.8}, install={"threshold": 0.8}) + result = evaluate_screening(_vector(_answer()), config) + assert result.decision == "error" + assert [item.question_id for item in result.evaluated] == ["disclosure"] + + +def test_result_is_immutable_and_audit_serialization_copies_values(): + result = evaluate_screening(_vector(_answer()), _config(disclosure={"threshold": 0.8})) + assert result.to_dict() == { + "decision": "denied", + "mode": "enforce", + "enforced_decision": "denied", + "evaluated": [ + { + "question_id": "disclosure", + "threshold": 0.8, + "probability": 0.9, + "action": "deny", + "matched": True, + } + ], + "matched": ["disclosure"], + "error": "", + } + with pytest.raises(FrozenInstanceError): + result.decision = "continue" + with pytest.raises(FrozenInstanceError): + result.evaluated[0].threshold = 1.0 + serialized = result.to_dict() + serialized["evaluated"][0]["probability"] = 0 + assert result.evaluated[0].probability == 0.9 + + +def test_validate_catalog_accepts_only_explicit_selected_questions(): + config = _config(disclosure={"threshold": 0.8}) + validate_screening_catalog( + _catalog(_question(), _question("risk", qtype=QuestionType.CHOICE)), config + ) + + +@pytest.mark.parametrize( + "question", + [ + _question("other"), + _question(qtype=QuestionType.SCORE), + _question(qtype=QuestionType.CHOICE), + _question(polarity="safe"), + ], +) +def test_invalid_catalog_rule_is_a_startup_error(question): + with pytest.raises(ValueError, match="Screening question"): + validate_screening_catalog(_catalog(question), _config(disclosure={"threshold": 0.8})) + + +@pytest.mark.parametrize( + "threshold", [True, False, "0.8", None, float("nan"), float("inf"), -0.1, 1.1] +) +def test_threshold_is_an_explicit_finite_numeric_probability(threshold): + with pytest.raises(ValidationError): + SystemOneScreeningRule(threshold=threshold) + + +@pytest.mark.parametrize("threshold", [0, 0.8, 1]) +def test_threshold_boundaries_are_valid(threshold): + assert SystemOneScreeningRule(threshold=threshold).threshold == threshold + + +def test_missing_threshold_is_rejected(): + with pytest.raises(ValidationError): + SystemOneScreeningRule() + + +@pytest.mark.parametrize( + "data", + [ + {"enabled": True}, + {"default_action": "allow"}, + {"mode": "enabled"}, + {"unknown": True}, + {"rules": {"question": {"threshold": 0.8, "action": "allow"}}}, + {"rules": {"question": {"threshold": 0.8, "unknown": True}}}, + {"rules": {"": {"threshold": 0.8}}}, + {"rules": {"leading space": {"threshold": 0.8}}}, + {"rules": {"é": {"threshold": 0.8}}}, + {"rules": {"a" * 129: {"threshold": 0.8}}}, + ], +) +def test_invalid_screening_configuration_is_rejected(data): + with pytest.raises(ValidationError): + SystemOneScreeningConfig(**data) + + +def test_screening_requires_system_one_to_be_enabled(): + with pytest.raises(ValidationError, match=r"screening\.enabled requires system_one\.enabled"): + SystemOneConfig(screening={"enabled": True, "rules": {"q": {"threshold": 0.8}}}) + config = SystemOneConfig( + enabled=True, screening={"enabled": True, "rules": {"q": {"threshold": 0.8}}} + ) + assert config.screening.default_action == "deny" + + +def test_shadow_retains_legacy_vector_but_observes_invalid_raw_answer(): + answer = _answer(value=0.9, detail={"screening_answer_valid": False}) + result = evaluate_screening( + _vector(answer), _config(mode="shadow", disclosure={"threshold": 0.8}) + ) + assert result.decision == "error" + assert result.enforced_decision == "continue" + assert result.error == "Screening contains an invalid answer." + assert answer.value == 0.9 + assert answer.detail == {"screening_answer_valid": False} diff --git a/tests/test_system_one_screening_integration.py b/tests/test_system_one_screening_integration.py new file mode 100644 index 00000000..cbd3717e --- /dev/null +++ b/tests/test_system_one_screening_integration.py @@ -0,0 +1,538 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Authorization and transport boundaries for opt-in decision-model screening.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from types import SimpleNamespace + +import httpx +import pytest + +from nomos.config.settings import CouncilSettings, OPAConfig, SystemOneConfig +from nomos.level_0.types import Attestation, AttestationVector, Intent +from nomos.nat.functions import AuthorizeInput, CouncilService, ProposeIntentInput +from nomos.opa import OPAPolicyDecision +from nomos.system_one.client import ( + AttestationCatalog, + CatalogQuestion, + SystemOneClient, + SystemOneEvaluationError, +) +from nomos.system_one.router import FastPathResult +from nomos.system_one.screening import evaluate_screening +from tests.test_opa_nat_integration import RecordingOPAClient + +CATALOG = str(Path(__file__).resolve().parents[1] / "configs/attestation_questions.yaml") +DENY = "credential_exfiltration" +ASK = "reads_sensitive_paths" +RULES = {DENY: {"threshold": 0.8}, ASK: {"threshold": 0.8, "action": "requires_human_approval"}} + + +def _vector(scores): + return AttestationVector( + model_version="decision-model-1.0", + catalog_version="test-1", + attestations=[ + Attestation( + question_id=question_id, + category="security", + qtype="noul", + value=value, + confidence=0.9, + polarity="adverse", + ) + for question_id, value in scores.items() + ], + ) + + +class RecordingDecisionClient: + """Return known answers without a network call; retain replay selections.""" + + def __init__(self, scores=None, error=None): + self.catalog = SimpleNamespace(version="test-1") + self.scores = scores or {DENY: 0.1, ASK: 0.1} + self.error = error + self.calls = [] + + async def evaluate(self, intent, *, question_ids=None): + self.calls.append(question_ids) + if self.error: + raise self.error + return _vector( + { + key: value + for key, value in self.scores.items() + if question_ids is None or key in question_ids + } + ) + + async def aclose(self): + pass + + +class ClosingOPAClient(RecordingOPAClient): + async def aclose(self): + pass + + +def _service(tmp_path, *, mode="enforce", rules=None, scores=None, error=None, opa=None): + settings = CouncilSettings( + council_id="screening-test", + require_auth=False, + llm_backends={}, + members=[], + council_key_path=str(tmp_path), + opa=OPAConfig(enabled=True), + system_one=SystemOneConfig( + enabled=True, + catalog_path=CATALOG, + screening={ + "enabled": True, + "mode": mode, + "rules": RULES if rules is None else rules, + }, + ), + ) + service = CouncilService(settings) + client = RecordingDecisionClient(scores, error) + service._system_one_client = client + service._opa_client = ClosingOPAClient(opa or OPAPolicyDecision(allow=True)) + return service, client + + +def _request(*, policy_only=False): + return AuthorizeInput( + agent_id="agent-1", + command="/bin/echo hello", + working_directory="/tmp", + description="Inspect the test workspace", + justification="Validate screening", + target_resource="/tmp", + policy_only=policy_only, + ) + + +async def _unexpected(*args, **kwargs): + pytest.fail("Screened calls must not reach Council actors") + + +def _no_council(monkeypatch, service): + monkeypatch.setattr(service, "_run_code_review", _unexpected) + monkeypatch.setattr(service, "_evaluate_fast_path", _unexpected) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("scores", "expected"), + [ + ({DENY: 0.8, ASK: 0.1}, "denied"), + ({DENY: 0.1, ASK: 0.9}, "requires_human_approval"), + ({DENY: 0.9, ASK: 0.9}, "denied"), + ], +) +async def test_authorization_stops_before_council_or_writ(tmp_path, monkeypatch, scores, expected): + service, client = _service(tmp_path, scores=scores) + _no_council(monkeypatch, service) + try: + result = await service.authorize(_request()) + assert result.status == expected + assert result.writ is None + assert len(client.calls) == 1 + assert service.council.get_workflow(result.decision_id) is None + entry = service.council.ledger.get_review_by_intent(result.decision_id) + assert entry is not None + audit = entry.payload["attestation"]["screening"] + assert audit["enforced_decision"] == expected + assert audit["catalog_version"] == "test-1" + assert audit["selected_rules"][DENY] == {"threshold": 0.8, "action": "deny"} + assert audit["mode"] == "enforce" + finally: + await service.aclose() + + +@pytest.mark.asyncio +async def test_model_denial_precedes_opa_human_review(tmp_path, monkeypatch): + service, client = _service( + tmp_path, + scores={DENY: 0.9, ASK: 0.9}, + opa=OPAPolicyDecision( + allow=False, + decision="requires_human_approval", + reasons=["Human review required"], + ), + ) + _no_council(monkeypatch, service) + try: + result = await service.authorize(_request()) + assert result.status == "denied" + assert client.calls == [None] + finally: + await service.aclose() + + +@pytest.mark.asyncio +async def test_opa_hard_denial_never_calls_decision_model(tmp_path, monkeypatch): + service, client = _service( + tmp_path, + opa=OPAPolicyDecision( + allow=False, + decision="deny", + reasons=["Forbidden command"], + ), + ) + _no_council(monkeypatch, service) + try: + result = await service.authorize(_request()) + assert result.status == "denied" + assert client.calls == [] + finally: + await service.aclose() + + +@pytest.mark.asyncio +async def test_model_error_is_not_a_human_approval_request(tmp_path, monkeypatch): + service, _ = _service(tmp_path, error=SystemOneEvaluationError("Unavailable")) + _no_council(monkeypatch, service) + try: + result = await service.authorize(_request()) + assert result.status == "error" + assert result.writ is None + finally: + await service.aclose() + + +class CouncilReachedError(Exception): + """Signal that normal review still owns an eligible operation.""" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("mode", "scores", "error"), + [ + ("enforce", {DENY: 0.1, ASK: 0.1}, None), + ("shadow", {DENY: 0.9, ASK: 0.9}, None), + ("shadow", None, SystemOneEvaluationError("Unavailable")), + ], +) +async def test_clear_or_shadow_screening_preserves_review( + tmp_path, + monkeypatch, + mode, + scores, + error, +): + service, client = _service(tmp_path, mode=mode, scores=scores, error=error) + seen = [] + + async def no_fast_path(*args, **kwargs): + return FastPathResult(False, False), FastPathResult(False, False) + + async def reached(intent): + seen.append(intent.metadata["attestation"]["screening"]) + raise CouncilReachedError + + monkeypatch.setattr(service, "_evaluate_fast_path", no_fast_path) + monkeypatch.setattr(service, "_run_code_review", reached) + try: + with pytest.raises(CouncilReachedError): + await service.authorize(_request()) + assert client.calls == [None] + assert seen[0]["enforced_decision"] == "continue" + if error: + assert seen[0]["decision"] == "error" + finally: + await service.aclose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("score", "expected"), [(0.1, "policy_allowed"), (0.9, "denied")]) +async def test_approved_replay_only_requests_effective_denial_questions( + tmp_path, + monkeypatch, + score, + expected, +): + service, client = _service(tmp_path, scores={DENY: score, ASK: 0.99}) + _no_council(monkeypatch, service) + try: + result = await service.authorize(_request(policy_only=True)) + assert result.status == expected + assert result.writ is None + assert client.calls == [{DENY}] + finally: + await service.aclose() + + +@pytest.mark.asyncio +async def test_replay_without_deny_rules_does_not_call_model(tmp_path, monkeypatch): + service, client = _service(tmp_path, rules={ASK: RULES[ASK]}) + _no_council(monkeypatch, service) + try: + result = await service.authorize(_request(policy_only=True)) + assert result.status == "policy_allowed" + assert client.calls == [] + finally: + await service.aclose() + + +@pytest.mark.asyncio +async def test_replay_model_error_stops_execution(tmp_path, monkeypatch): + service, client = _service(tmp_path, error=SystemOneEvaluationError("Unavailable")) + _no_council(monkeypatch, service) + try: + result = await service.authorize(_request(policy_only=True)) + assert result.status == "error" + assert result.writ is None + assert client.calls == [{DENY}] + finally: + await service.aclose() + + +@pytest.mark.asyncio +async def test_legacy_proposal_cannot_bypass_screening(tmp_path, monkeypatch): + service, client = _service(tmp_path, scores={DENY: 0.9, ASK: 0.1}) + _no_council(monkeypatch, service) + try: + result = await service.propose_intent( + ProposeIntentInput( + agent_id="agent-1", + command="/bin/echo hello", + working_directory="/tmp", + description="Inspect a directory", + justification="Validate proposal screening", + target_resource="/tmp", + ) + ) + assert result.success is False + assert result.state == "denied" + assert service.council.get_workflow(result.intent_id) is None + assert client.calls == [None] + finally: + await service.aclose() + + +def _client(*, mode="enforce", enabled=True): + catalog = AttestationCatalog( + version="test-1", + questions=[ + CatalogQuestion(id=DENY, category="security", qtype="noul"), + CatalogQuestion(id=ASK, category="security", qtype="noul"), + ], + ) + config = SystemOneConfig( + enabled=True, + api_key="test-authentication", # pragma: allowlist secret -- offline test fixture + base_url="https://backend.example", + screening={"enabled": enabled, "mode": mode, "rules": RULES}, + ) + return SystemOneClient(config, catalog) + + +def _intent(): + return Intent.create( + agent_id="agent-1", + description="Inspect test files", + command="/bin/echo hello", + target_resource="/tmp", + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "answer", + [ + {"type": "noul", "noul": True}, + {"type": "noul", "noul": "0.1"}, + {"type": "choice", "noul": 0.1}, + {"noul": 0.1}, + {"type": "noul", "noul": float("nan")}, + {"type": "noul", "noul": 1.1}, + {"type": "noul", "noul": -0.1}, + {"type": "noul", "noul": float("inf")}, + {"type": "noul", "value": 0.1}, + None, + ], +) +async def test_transport_rejects_malformed_screened_answers(monkeypatch, answer): + client = _client() + + async def response(body): + return { + "model": "decision-model-1.0", + "answers": { + DENY: answer, + ASK: {"type": "noul", "noul": 0.1}, + }, + } + + monkeypatch.setattr(client, "_post", response) + with pytest.raises(SystemOneEvaluationError): + await client.evaluate(_intent()) + + +@pytest.mark.asyncio +async def test_overlapping_full_and_replay_requests_keep_independent_catalogs(monkeypatch): + client = _client() + requests = [] + both_started = asyncio.Event() + + async def response(body): + ids = set(body["questions"]) + requests.append(ids) + if len(requests) == 2: + both_started.set() + await asyncio.wait_for(both_started.wait(), timeout=2) + return { + "model": "decision-model-1.0", + "answers": {key: {"type": "noul", "noul": 0.1} for key in ids}, + } + + monkeypatch.setattr(client, "_post", response) + full, replay = await asyncio.gather( + client.evaluate(_intent()), + client.evaluate(_intent(), question_ids={DENY}), + ) + assert {answer.question_id for answer in full.attestations} == {DENY, ASK} + assert {answer.question_id for answer in replay.attestations} == {DENY} + assert requests == [{DENY, ASK}, {DENY}] + assert {question.id for question in client.catalog.questions} == {DENY, ASK} + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("score", "expected"), + [ + (0.1, "requires_human_approval"), + (0.9, "denied"), + ], +) +async def test_replay_preserves_opa_ask_after_checking_only_hard_denials( + tmp_path, + monkeypatch, + score, + expected, +): + """The worker satisfies the original ask using its verified saved approval.""" + service, client = _service( + tmp_path, + scores={DENY: score, ASK: 0.99}, + opa=OPAPolicyDecision( + allow=False, + decision="requires_human_approval", + reasons=["Exact-operation approval"], + ), + ) + _no_council(monkeypatch, service) + try: + result = await service.authorize(_request(policy_only=True)) + assert result.status == expected + assert result.writ is None + assert client.calls == [{DENY}] + finally: + await service.aclose() + + +def test_screening_catalog_failure_is_a_startup_error(tmp_path): + """An enabled enforcement policy cannot silently disappear on bad input.""" + settings = CouncilSettings( + council_id="screening-startup-test", + require_auth=False, + llm_backends={}, + members=[], + council_key_path=str(tmp_path), + system_one=SystemOneConfig( + enabled=True, + catalog_path=str(tmp_path / "missing-catalog.yaml"), + screening={"enabled": True, "mode": "enforce", "rules": RULES}, + ), + ) + with pytest.raises(ValueError, match="Could not initialize decision-model screening"): + CouncilService(settings) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "answer", + [ + {"type": "noul", "noul": "0.1"}, + {"noul": 0.1}, + ], +) +async def test_shadow_preserves_legacy_vector_but_marks_invalid_screening(monkeypatch, answer): + client = _client(mode="shadow") + + async def response(body): + return { + "model": "decision-model-1.0", + "answers": { + DENY: answer, + ASK: {"type": "noul", "noul": 0.1}, + }, + } + + monkeypatch.setattr(client, "_post", response) + vector = await client.evaluate(_intent()) + assert vector.by_id(DENY).value == 0.1 + assert vector.by_id(DENY).detail["screening_answer_valid"] is False + result = evaluate_screening(vector, client._config.screening) + assert result.decision == "error" + assert result.enforced_decision == "continue" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("mode", "enabled", "reject"), + [ + ("enforce", True, True), + ("shadow", True, False), + ("enforce", False, False), + ], +) +async def test_duplicate_json_answers_are_rejected_only_when_enforcing(mode, enabled, reject): + client = _client(mode=mode, enabled=enabled) + raw = b'{"answers":{"test":{"type":"noul","noul":0.99,"noul":0.01}}}' + + def response(request): + return httpx.Response(200, content=raw, request=request) + + async with httpx.AsyncClient(transport=httpx.MockTransport(response)) as transport: + client._client = transport + if reject: + with pytest.raises(SystemOneEvaluationError): + await client._post({"questions": {}}) + else: + payload = await client._post({"questions": {}}) + assert payload["answers"]["test"]["noul"] == 0.01 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("repeat_denial", [False, True]) +async def test_enforced_batches_cannot_overwrite_another_questions_answer( + monkeypatch, repeat_denial +): + """A later batch cannot replace a high denial probability with a low one.""" + client = _client() + client._config.max_questions_per_request = 1 + + async def response(body): + question_id = next(iter(body["questions"])) + answers = {question_id: {"type": "noul", "noul": 0.99 if question_id == DENY else 0.1}} + if repeat_denial and question_id == ASK: + answers[DENY] = {"type": "noul", "noul": 0.01} + return {"model": "decision-model-1.0", "answers": answers} + + monkeypatch.setattr(client, "_post", response) + try: + if repeat_denial: + with pytest.raises(SystemOneEvaluationError, match="requested question batch"): + await client.evaluate(_intent()) + else: + vector = await client.evaluate(_intent()) + assert vector.by_id(DENY).value == 0.99 + finally: + await client.aclose()