Files
Open_Ultra_SAST/src/openultrasast/config.py
T
Marius Ciepluch 312c09bdbf fix(scan): a scan in the image prunes the wrapper's runs directory too (item 5b)
The maintainer's answer 7 of 2026-11-27 (the ninth session's menu). The label is in
.kiro/specs/contributor-scan/spec.json (80abac5). The record, .kiro/handover.md:1335-1337
(not tracked), in full:

    7. The wrapper's runs are never pruned by a scan in the image. Answer: "Image scan
    prunes too": a scan in the image prunes its runs directory when the wrapper's
    override is set; a change in the scan path, a test first. Not chosen: "Document:
    never pruned" (the session's recommendation); "Queue in step 8"; "Leave it".

The option as offered (handover.md:1435-1436): "the scan path prunes its runs
directory when the wrapper's override is set; a code change, a test first."

A second decision, taken on this change. The reviewer found that the wrapper passes no
OPENULTRASAST_RUNS_RETENTION_DAYS into the image, so with this change alone a scan
through the wrapper would remove runs older than 30 days from
~/.cache/openultrasast/runs, native runs included, even for a user who keeps every run
natively with 0. Asked, the maintainer chose "Pass it through (Recommended)": the
wrappers pass OPENULTRASAST_RUNS_RETENTION_DAYS into the container, one more -e in
ops/shell/ousast.sh and ops/shell/ousast.ps1, a test first. That is the next commit.
This one is the scan path alone, as answer 7 says. The wrapper builds its image only
when it is missing (ops/shell/ousast.sh:64-67), so until the image is rebuilt the
wrapper's scans run the code shipped in it and remove nothing (measured below).

The fault. The shell wrapper mounts ~/.cache/openultrasast/runs at /reports and passes
-e OPENULTRASAST_RUNS_DIR=/reports (d1f61fb). prune_scan_runs returned nothing whenever
OPENULTRASAST_RUNS_DIR was set, so a scan in the image never removed an expired run:
the wrapper's runs were removed only by a later native scan on the default location.

What changed.
- src/openultrasast/config.py: WRAPPER_RUNS_MOUNT = "/reports" and
  runs_dir_is_the_wrappers(), true when OPENULTRASAST_RUNS_DIR is that path.
- src/openultrasast/run.py: prune_scan_runs prunes config.runs_dir when the override
  is unset (as before) or is the wrapper's. Any other override still removes nothing.
- README.md, docs/examples.md and .agents/skills/openultrasast-scan/SKILL.md said that
  nothing is removed from a location chosen with OPENULTRASAST_RUNS_DIR; each says now
  that the shell wrapper is the one exception. The decision says "a change in the scan
  path"; these three sentences state the rule the change alters, and would be false
  without them.
- tests/test_run_pruning.py: its module docstring, and three tests (below).

The session's readings of the decision, to be confirmed by the maintainer.
1. "The wrapper's override" is recognised by its value. Both wrappers pass exactly
   /reports (ops/shell/ousast.sh:91, ops/shell/ousast.ps1:50), and nothing in the
   container's environment tells the wrapper's run from a compose run started by hand.
   Two consequences, by reading: a native scan with OPENULTRASAST_RUNS_DIR=/reports is
   pruned as well; and a compose run started by hand with the same -e and the default
   ./reports mounted prunes run-shaped directories older than 30 days under the
   checkout's reports/ (docker-compose.yml:33-34).
2. The compose file's own value, /reports/runs (docker-compose.yml:47), is a chosen
   location and is not pruned: there ./reports on the host is mounted, which may hold
   more than runs.

This amends the run retention decided on 2026-11-24 (spec.json, approval_history entry
six: "after each scan, with no OPENULTRASAST_RUNS_DIR set, runs in the default location
older than 30 days are removed"): the wrapper's mount is pruned as well.

Measured, in an image. The script is /tmp/opencode/s10_c7_probe.sh and its files are
under /tmp/opencode/s10_c7_probe/, one per measurement; the files of the four scans
and of the listings after them start with the command they ran. The four scans' stamps
run from 17:57:27Z to 17:57:32Z; the listings carry none. The probe image is
openultrasast:dev (3f959b31f2f2, uid 1000) with the working tree's package copied
over it: 295 files, equal to the tree by
sha256 (03_probe_sources.out is a bare list of digests; the comparison is
/tmp/opencode/s10_c7_sources_cmp.out, which starts with its command). Every runs
directory is a scratch directory mounted at /reports; the real ~/.cache/openultrasast/
runs was not mounted. Network off, no key. The subject is a fresh copy of the four C
files and their README (04_subject.out). Each scratch runs directory held a run of 40
days ago, a run of 5 days ago and a directory called notes.
- With the wrapper's override, on the probe image (10_wrapper_override.out): exit 0,
  file_targets=4, findings=4, and the line
  "notice: removed 1 run older than 30 days from /reports". The expired run is gone;
  the run of 5 days ago, the new run and notes remain (11_wrapper_override_after.out).
- With the compose file's /reports/runs (20_compose_override.out,
  21_compose_override_after.out): no notice, all three entries remain.
- With the wrapper's override on the shipped image (30_shipped_image.out,
  31_shipped_image_after.out): no notice, all three remain: the fault as shipped.
- With the wrapper's override and OPENULTRASAST_RUNS_RETENTION_DAYS=0 passed into the
  container (40_retention_zero.out, 41_retention_zero_after.out): no notice, all three
  remain.
- The probe image is removed (90_remove_probe.out); no container remains
  (91_containers_after.out).
The wrapper itself was not run.

Tests (tests/test_run_pruning.py).
- test_a_scan_through_the_wrapper_removes_the_expired_runs_from_the_mounted_runs_directory
  calls prune_scan_runs, as cli.py:720 does, with OPENULTRASAST_RUNS_DIR=/reports and
  a runs directory that stands in for /reports, which only root can make on the host.
  It expects one notice, and the run of 5 days ago and the current run to remain.
- test_a_scan_that_compose_runs_without_the_wrapper_removes_nothing: /reports/runs
  removes nothing and says nothing.
- test_the_wrapper_passes_the_override_that_a_scan_prunes: the shell wrapper's command
  holds "-e OPENULTRASAST_RUNS_DIR=" + WRAPPER_RUNS_MOUNT, so its word and the scan's
  mount point cannot drift apart. Nothing reads the PowerShell wrapper's.
RED. An archive of HEAD (src, tests, pyproject.toml) with the first test as written,
the package imported from the archive (s10_c7_red_where.out): 1 failed, 1 passed; the
passed one was a throwaway test that printed where the package came from and was
removed after. The failure is at
"assert () == ('removed 1 run older than 30 days from .../reports',)"
(s10_c7_red.out). The command, run from the archive's directory, where the throwaway
test was tests/test_zz_where.py:
env -u OPENROUTER_API_KEY -u DEEPSEEK_API_KEY PYTHONPATH=/tmp/opencode/s10_c7_head/src
/home/mc/Source/OpenUltraSAST/.venv/bin/python -m pytest -q -p no:cacheprovider
tests/test_run_pruning.py tests/test_zz_where.py -k "where or through_the_wrapper"
GREEN: 250 passed on the final tree (s10_c7_green4.out; the command is not
in the file) over
tests/test_run_pruning.py tests/test_scan_output_location.py tests/test_config.py
tests/test_run.py tests/test_mcp.py tests/test_agent_skills.py
tests/test_shell_wrapper.py tests/test_task_images.py tests/test_benchmark.py
tests/test_benchmark_artifact_contract.py tests/test_model_scope.py
tests/test_pair_harvest.py.
Mutants, to show the two guards bite: the tree's sources with one line changed and the
final test file (the copies are /tmp/opencode/s10_c7_mutA, mutB, mutC).
- the predicate "_runs_dir_override().startswith(WRAPPER_RUNS_MOUNT)" fails the
  compose test alone (s10_c7_mutA2.out: 1 failed, 36 passed);
- WRAPPER_RUNS_MOUNT = "/reports2" fails the wrapper test and the first test
  (s10_c7_mutB2.out: 2 failed, 35 passed);
- HEAD's condition, "if runs_dir_is_overridden():", fails the first test alone, at the
  assertion above (s10_c7_mutC2.out: 1 failed, 36 passed).

Checks on the final tree. mkdocs build --strict exits 0 (s10_c7_mkdocs2.out; its
examples page is byte-identical to the first build's); ruff format, ruff check, mypy,
compileall and the three gates pass, and the gates print what they printed before the
change (s10_c7d_exits.txt). Three files date from before the test module's docstring
was edited, on documentation unchanged since: the first build's examples page holds
each of the three added phrases once and the old wording zero times
(s10_c7_site_sentence.out), and tests/test_docs_site.py with
tests/test_removed_plane_references.py gave 8 passed (s10_c7_docs_tests.out). An
earlier gates run found an unused name in the first test (s10_c7_ruff_check.out); it
is removed.

- Review: two rounds by a reviewer subagent, reading and re-running, no docker. Round one
  found the code right for answer 7 (RED reproduced on an archive of HEAD, 250 passed over
  the 12 files, the three mutants failing as stated) and conditioned the commit on a
  decision: the wrapper passed no retention variable into the image, so this change alone
  broke "0 keeps every run" on the wrapper path. Asked, the maintainer chose "Pass it
  through (Recommended)"; the wrapper's commit follows at once, before other work and any
  push. Round two found the delta to be the test module's docstring; re-ran the 12 files
  (250 passed), the docs tests, ruff, mypy, mkdocs and the three mutants; checked the
  round-two evidence against the test file's last change and every sentence of this
  message, and had two false sentences corrected: the spec.json path and the RED command.

By reading, not measured.
- cli.py:720 passes the config whose runs_dir is /reports in the image (config.py,
  _runs_dir), so the scan in the image prunes that directory.
- ops/shell/ousast.ps1:50 passes the same override; PowerShell is not installed here.
- A failed removal still costs the scan nothing: prune_scan_runs catches OSError and
  RecursionError, and tests/test_run_pruning.py has two scans whose removal fails.
- `ousast benchmark` in the image goes through the same line (cli.py:1123, then
  cli.py:720) and prunes once per benchmark scan. That is answer 7's rule.

Found and not fixed, for the maintainer.
- The notice names the path the scan sees, /reports, not the host's
  ~/.cache/openultrasast/runs.

Not checked: the whole test suite; the wrapper and a compose run (the image was run
with docker run on scratch mounts); a removal that fails inside the container; Windows
and ops/shell/ousast.ps1; a native scan with OPENULTRASAST_RUNS_DIR=/reports.
2026-11-27 19:36:15 +01:00

423 lines
17 KiB
Python

from __future__ import annotations
import json
import logging
import os
import tomllib
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Literal
from openultrasast.contracts import Contract
# Retirement notes (harnessx-removal Req 1.3, 3.3). A key that asked for a retired LLM capability fails and names
# the replacement, never a silent downgrade; the old budget section only warns. Every line below that names the
# removed plane carries its retirement date, which the reference-search test holds the rest of the tree to.
_RETIRED_ON = "retired 2026-09-30 with HarnessX"
_PLANE_RUN = "`ousast plane run`, see ops/ax/README.md"
_RETIRED_PANELS = (
f"LLM fusion panels were retired; fusion is deterministic; independent LLM agreement is the plane's `agree` task ({_PLANE_RUN})"
)
# Keys that loaded but were never read (retired 2026-10-02, legacy cleanup): accepting them silently would let
# a user believe they configure something.
_UNREAD_ON = "retired 2026-10-02 because nothing ever read it"
_UNREAD_DYNAMIC = "no dynamic or deep tier exists; deep mode will define its own keys when it is built"
_UNREAD_EVIDENCE = "evidence tiers come from the program model's ladder (model/ladder.py), not from configuration"
_UNREAD_VARIANTS = "the structural variant search it configured was deleted with semantic/variants.py"
_UNREAD_SANDBOX = "the search sandbox enforces isolation and read-only source (search/_sandbox.py); that is an invariant, not a knob"
_UNREAD_TOP_K = "no stage read it; `[complexity] max_hunter_hotspots` is the one complexity key the scan reads"
_UNREAD_EMBEDDINGS = (
"the json-local vector index it configured and `ousast index` were deleted; the decision engine embeds through "
"`ousast learn memory embed --model` (learn/embeddings.py)"
)
RETIRED_KEYS: dict[tuple[str, str], str] = {
("models", "verifier"): f"{_RETIRED_ON}: LLM verification runs on the plane (`verify` + `agree`, {_PLANE_RUN})",
("fusion", "panel_model"): f"{_RETIRED_ON}: {_RETIRED_PANELS}",
("fusion", "decider_model"): f"{_RETIRED_ON}: {_RETIRED_PANELS}",
("models", "patcher"): f"{_UNREAD_ON}: no patching stage calls a model",
("dynamic", "enabled"): f"{_UNREAD_ON}: {_UNREAD_DYNAMIC}",
("dynamic", "network_scope"): f"{_UNREAD_ON}: {_UNREAD_DYNAMIC}",
("evidence", "minimum_report_verified"): f"{_UNREAD_ON}: {_UNREAD_EVIDENCE}",
("evidence", "minimum_exploit"): f"{_UNREAD_ON}: {_UNREAD_EVIDENCE}",
("evidence", "minimum_patch"): f"{_UNREAD_ON}: {_UNREAD_EVIDENCE}",
("variants", "enabled"): f"{_UNREAD_ON}: {_UNREAD_VARIANTS}",
("variants", "max_mechanisms"): f"{_UNREAD_ON}: {_UNREAD_VARIANTS}",
("embeddings", "model"): f"{_UNREAD_ON}: {_UNREAD_EMBEDDINGS}",
("embeddings", "store"): f"{_UNREAD_ON}: {_UNREAD_EMBEDDINGS}",
("sandbox", "network"): f"{_UNREAD_ON}: {_UNREAD_SANDBOX}",
("sandbox", "workspace_readonly"): f"{_UNREAD_ON}: {_UNREAD_SANDBOX}",
("complexity", "top_k"): f"{_UNREAD_ON}: {_UNREAD_TOP_K}",
}
RETIRED_SECTION = "harnessx" # retired 2026-09-30: loads with one warning and is otherwise ignored (Req 3.3)
RETIRED_SECTION_WARNING = (
"`[harnessx]` is ignored (retired 2026-09-30): HarnessX was removed; agentic work runs on the ax plane "
"with per-task budgets, see ops/ax/README.md"
)
class RetiredConfigError(ValueError):
"""A config key asked for a capability that was retired; the message names its replacement."""
def _check_retired(data: dict[str, object]) -> None:
problems = []
for (section, key), reason in RETIRED_KEYS.items():
table = data.get(section)
if isinstance(table, dict) and key in table:
problems.append(f"`[{section}] {key}` was {reason}. Remove the key.")
if problems:
raise RetiredConfigError("\n".join(problems))
if RETIRED_SECTION in data:
logging.getLogger("openultrasast.config").warning(RETIRED_SECTION_WARNING)
def load_dotenv(path: Path | None = None, *, force: bool = False) -> None:
"""Load KEY=VALUE lines from .env into os.environ. Stdlib only; never overrides."""
if not force and (os.environ.get("PYTEST_CURRENT_TEST") or os.environ.get("OPENULTRASAST_SKIP_DOTENV")):
return
env_path = path if path is not None else Path(".env")
if not env_path.is_file():
return
for raw in env_path.read_text().splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
key = key.strip()
value = value.strip().strip("'").strip('"')
if key and key not in os.environ:
os.environ[key] = value
@dataclass(frozen=True)
class ModelConfig:
ranker: str | None = None
hunter: str | None = None
judge: str | None = None # second, independent judgement before anything is published as proven
chat_base_url: str | None = None # chat endpoint; independent of the embedding endpoint
chat_api_key_env: str | None = None # environment variable holding that endpoint's key
# Whether the chat model reasons before answering. Off by default because that is what the committed
# baseline was measured under: the provider silently ignores `temperature` while thinking, so thinking was
# disabled to make `temperature: 0` mean something. It did not — the measured run-to-run disagreement came
# from the agentic path, not the decoder — which is why the model layer arbitrates instead of averaging.
thinking: bool = False
@dataclass(frozen=True)
class SandboxConfig:
memory_mb: int = 2048
timeout_seconds: int = 300
pids_limit: int = 512
@dataclass(frozen=True)
class StaticAnalysisConfig:
sarif_paths: tuple[str, ...] = ()
@dataclass(frozen=True)
class ScoreConfig:
k: float = 60.0
min_score: int = 80
block_severity_reachable: int = 5
blocking: bool = False
@dataclass(frozen=True)
class RulesetConfig:
# Emission floors that replace "every regex match becomes a finding". The
# defaults (0.0) emit everything, keeping output byte-identical by default.
min_emit_priority: float = 0.0
min_emit_precision: float = 0.0
@dataclass(frozen=True)
class HardeningConfig:
# Release-readiness controls. redact_secrets masks credentials in traces/reports;
# max_findings caps the reported finding count for bounded CI runs (0 = unlimited).
redact_secrets: bool = True
max_findings: int = 0
@dataclass(frozen=True)
class FusionConfig:
# Two-panel fusion adjudication for triggered findings (standard mode). Deterministic
# panels and reconciler; high_assurance forces fusion on every finding.
enabled: bool = True
high_assurance: bool = False
@dataclass(frozen=True)
class ComplexityConfig:
# Hunter attention. A small default keeps PR/nightly map work cheap.
max_hunter_hotspots: int = 8
@dataclass(frozen=True)
class ModelLayerConfig:
# contributor-scan: the model layer in MAP. Named for the LAYER, not the model: `ModelConfig` is already
# the `[models]` block (hunter, judge, endpoint) and two meanings of one name is how you get a scan that
# silently reads the wrong settings. Additive -- without a CPG engine the scan is unchanged.
enabled: bool = True
# A TOTAL for the run, not a per-region cap. Conservative by default: a first scan of an unfamiliar
# repository should not be able to run away with someone's budget before they have decided they want it.
max_model_calls: int = 100
max_regions: int = 300
@dataclass(frozen=True)
class ObligationsConfig:
# authorization-obligations: the obligation checker in MAP (standard/deep only).
enabled: bool = True
min_siblings: int = 3
policy_path: str = ".openultrasast/obligations.toml"
@dataclass(frozen=True)
class PushConfig(Contract):
"""Inert experimental push settings; configuring them does not install a hook.
The 2 GiB local cache cap is a storage budget, not a performance promise. The
eventual cache evicts unleased entries; deadline and cleanup are separate costs.
No endpoint, fetch, engine download or capability admission is enabled here.
"""
comparison_base: str | None = None
deadline_seconds: float = 30.0
cancellation_allowance_seconds: float = 2.0
cache_max_bytes: int = 2 * 1024**3
mode: Literal["advisory", "blocking"] = "advisory"
incomplete_coverage_policy: Literal["allow", "block"] = "allow"
def __post_init__(self) -> None:
super().__post_init__()
if self.deadline_seconds <= 0 or self.cancellation_allowance_seconds <= 0 or self.cache_max_bytes <= 0:
raise ValueError("push deadlines, cancellation allowance and cache limit must be positive")
def _user_cache_dir() -> Path:
"""`$XDG_CACHE_HOME` when it is set and absolute, otherwise `~/.cache` (the XDG base-directory rule)."""
override = os.environ.get("XDG_CACHE_HOME", "")
if override and Path(override).is_absolute():
return Path(override)
return Path.home() / ".cache"
def _runs_dir_override() -> str:
"""The `OPENULTRASAST_RUNS_DIR` set in the environment; empty when runs go to the default location."""
return os.environ.get("OPENULTRASAST_RUNS_DIR", "")
WRAPPER_RUNS_MOUNT = "/reports"
def runs_dir_is_the_wrappers() -> bool:
"""Whether `OPENULTRASAST_RUNS_DIR` is the shell wrapper's: the runs directory, mounted in the image.
The wrappers pass `/reports` (`ops/shell/ousast.sh`), where the compose file mounts the directory a native
scan writes to by default, so a scan prunes it as it prunes the default location.
"""
return Path(_runs_dir_override()) == Path(WRAPPER_RUNS_MOUNT)
def runs_dir_is_overridden() -> bool:
"""Whether `OPENULTRASAST_RUNS_DIR` names where runs go.
Wherever it points, that location is not pruned; the wrapper's mount is the one exception
(`runs_dir_is_the_wrappers`).
"""
return bool(_runs_dir_override())
def _runs_dir() -> str:
"""Where a scan creates its run: the user's cache, unless `OPENULTRASAST_RUNS_DIR` says otherwise.
Always absolute, and taken from the working directory when the override is relative, never from the
target: a run inside the analysed tree is what this default exists to prevent.
"""
override = _runs_dir_override()
if not override:
return str(_user_cache_dir() / "openultrasast" / "runs")
path = Path(override)
return str(path if path.is_absolute() else Path.cwd() / path)
def _runs_retention_days() -> int:
"""How long a run stays in the default cache before a later scan removes it; 0 keeps every run."""
value = os.environ.get("OPENULTRASAST_RUNS_RETENTION_DAYS", "").strip()
if not value:
return 30
if not value.isdecimal():
raise ValueError(f"OPENULTRASAST_RUNS_RETENTION_DAYS must be a whole number of days, 0 or more, not {value!r}")
return int(value)
@dataclass(frozen=True)
class ResolvedConfig:
models: ModelConfig = ModelConfig()
sandbox: SandboxConfig = SandboxConfig()
static_analysis: StaticAnalysisConfig = StaticAnalysisConfig()
score: ScoreConfig = ScoreConfig()
ruleset: RulesetConfig = RulesetConfig()
fusion: FusionConfig = FusionConfig()
hardening: HardeningConfig = HardeningConfig()
complexity: ComplexityConfig = ComplexityConfig()
obligations: ObligationsConfig = ObligationsConfig()
model: ModelLayerConfig = ModelLayerConfig()
push: PushConfig = PushConfig()
# Read from the environment each time a config is built, so one made without `load_config` lands in the
# same place.
runs_dir: str = field(default_factory=_runs_dir)
runs_retention_days: int = field(default_factory=_runs_retention_days)
def load_config(config_path: Path | None = None, *, dotenv: bool = True) -> ResolvedConfig:
if dotenv:
load_dotenv()
data: dict[str, object] = {}
if config_path is not None and config_path.exists():
with config_path.open("rb") as handle:
data = tomllib.load(handle)
_check_retired(data)
return ResolvedConfig(
models=_load_models(data.get("models", {})),
sandbox=_load_sandbox(data.get("sandbox", {})),
static_analysis=_load_static_analysis(data.get("static_analysis", {})),
score=_load_score(data.get("score", {})),
ruleset=_load_ruleset_config(data.get("ruleset", {})),
fusion=_load_fusion(data.get("fusion", {})),
hardening=_load_hardening(data.get("hardening", {})),
complexity=_load_complexity(data.get("complexity", {})),
obligations=_load_obligations(data.get("obligations", {})),
model=_load_model(data.get("model", {})),
push=PushConfig.from_payload(data.get("push", {})),
)
def config_payload(config: ResolvedConfig) -> dict[str, object]:
"""Reproducible resolved settings, including the separate experimental push policy."""
return asdict(config)
def write_resolved_config(config: ResolvedConfig, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(config_payload(config), indent=2, sort_keys=True) + "\n")
def _section(value: object) -> dict[str, object]:
return value if isinstance(value, dict) else {}
def _string(value: object) -> str | None:
return value if isinstance(value, str) and value else None
def _load_models(value: object) -> ModelConfig:
data = _section(value)
return ModelConfig(
ranker=_string(data.get("ranker")),
hunter=_string(data.get("hunter")),
judge=_string(data.get("judge")),
chat_base_url=_string(data.get("chat_base_url")),
chat_api_key_env=_string(data.get("chat_api_key_env")),
thinking=bool(data.get("thinking", False)),
)
def _load_sandbox(value: object) -> SandboxConfig:
data = _section(value)
return SandboxConfig(
memory_mb=_int_value(data.get("memory_mb"), 2048),
timeout_seconds=_int_value(data.get("timeout_seconds"), 300),
pids_limit=_int_value(data.get("pids_limit"), 512),
)
def _int_value(value: object, default: int) -> int:
if isinstance(value, bool):
return default
if isinstance(value, int | str | bytes | bytearray):
return int(value)
return default
def _load_static_analysis(value: object) -> StaticAnalysisConfig:
data = _section(value)
paths = data.get("sarif_paths", [])
if not isinstance(paths, list):
paths = []
return StaticAnalysisConfig(sarif_paths=tuple(str(item) for item in paths))
def _load_score(value: object) -> ScoreConfig:
data = _section(value)
return ScoreConfig(
k=_float_value(data.get("k"), 60.0),
min_score=_int_value(data.get("min_score"), 80),
block_severity_reachable=_int_value(data.get("block_severity_reachable"), 5),
blocking=bool(data.get("blocking", False)),
)
def _load_ruleset_config(value: object) -> RulesetConfig:
data = _section(value)
return RulesetConfig(
min_emit_priority=_float_value(data.get("min_emit_priority"), 0.0),
min_emit_precision=_float_value(data.get("min_emit_precision"), 0.0),
)
def _load_hardening(value: object) -> HardeningConfig:
data = _section(value)
return HardeningConfig(
redact_secrets=bool(data.get("redact_secrets", True)),
max_findings=_int_value(data.get("max_findings"), 0),
)
def _load_fusion(value: object) -> FusionConfig:
data = _section(value)
return FusionConfig(
enabled=bool(data.get("enabled", True)),
high_assurance=bool(data.get("high_assurance", False)),
)
def _load_complexity(value: object) -> ComplexityConfig:
data = _section(value)
return ComplexityConfig(
max_hunter_hotspots=_int_value(data.get("max_hunter_hotspots"), 8),
)
def _float_value(value: object, default: float) -> float:
if isinstance(value, bool):
return default
if isinstance(value, int | float):
return float(value)
if isinstance(value, str):
try:
return float(value)
except ValueError:
return default
return default
def _load_model(value: object) -> ModelLayerConfig:
data = _section(value)
return ModelLayerConfig(
enabled=bool(data.get("enabled", ModelLayerConfig.enabled)),
max_model_calls=_int_value(data.get("max_model_calls"), ModelLayerConfig.max_model_calls),
max_regions=_int_value(data.get("max_regions"), ModelLayerConfig.max_regions),
)
def _load_obligations(value: object) -> ObligationsConfig:
data = _section(value)
return ObligationsConfig(
enabled=bool(data.get("enabled", True)),
min_siblings=_int_value(data.get("min_siblings"), 3),
policy_path=str(data.get("policy_path", ".openultrasast/obligations.toml")),
)