feat(contributor-scan): a scan writes its run to the user cache, and the ledger only when it learns (3.1, part A)

Where a scan writes. A native scan now creates its run under the user cache,
~/.cache/openultrasast/runs/<scan-id>/ by default ($XDG_CACHE_HOME when it is
set and absolute), prints run_dir=<path> once, and no longer writes anything
under the analysed tree. OPENULTRASAST_RUNS_DIR still wins: an absolute value
is used as given, a relative one resolves against the working directory.
Pre-push storage is unchanged.

The calibration ledger, by maintainer decision: .openultrasast/calibration/
stays the store, and a scan writes the false-positive ledger into the tree
only when its content would change. On a read-only tree the scan records
ledger_not_written, with a sentence in the report, and completes; before, a
read-only target with one rejected finding crashed before report.md existed.

benchmarks/repos/measure.py follows the printed run directory. It read the
run from under the scanned copy, which would have recorded every repository
as failed, and it also read a stale run left in a copy.

Tests: tests/test_scan_output_location.py drives the real CLI and compares
the whole tree before and after; tests/test_repo_measure.py pins the
measurement script; an autouse fixture keeps every test's scan runs out of
the developer's cache; fourteen test files follow the run to its new place.
README, docs/examples.md and the scan skill name the ledger as the one write
a scan makes. _run_scan is touched by one line and stays over the complexity
cap.

Task 3.1 stays open for part B, the readable summary.
This commit is contained in:
Marius Ciepluch
2026-11-24 15:33:35 +01:00
parent d45fc98c4e
commit 6edae3a585
29 changed files with 509 additions and 50 deletions
+10 -2
View File
@@ -631,7 +631,7 @@ def _run_scan(path: Path, config_path: Path, mode: str, fail_on: str) -> ScanOut
write_verification_results(verifications, verification_path)
runtime.run_stage(
"record_calibration",
lambda: _persist_calibration_feedback(run, ledger_path, prior_learnings, findings, verifications),
lambda: _persist_calibration_feedback(run, ledger_path, prior_learnings, findings, verifications, runtime),
)
# Fusion: deterministic two-panel adjudication for triggered findings (standard mode).
fusion_decisions: list[FusionDecision] = []
@@ -887,11 +887,19 @@ def _persist_calibration_feedback(
prior_learnings: list[FalsePositiveLearning],
findings: list[StaticFinding],
verifications: list[VerificationResult],
runtime: HarnessRuntime,
) -> list[FalsePositiveLearning]:
# Store rejected or held findings as scoped learnings for the next scan.
new_learnings = learnings_from_verifications(findings, verifications)
merged = merge_false_positive_learnings(prior_learnings, new_learnings)
write_false_positive_learnings(merged, ledger_path)
if merged != prior_learnings:
# The ledger is the one thing a scan still writes into the analysed tree, so it is written only when its
# content would change: a false positive already in the store is not a new learning. A tree that refuses
# the write (mounted read-only) is recorded, not fatal.
try:
write_false_positive_learnings(merged, ledger_path)
except OSError as exc:
runtime.state["degradations"].append({"stage": "record_calibration", "reason": "ledger_not_written", "detail": str(exc)})
write_false_positive_learnings(new_learnings, run.root / "calibration" / "false_positive_learnings.json")
return merged
+25 -3
View File
@@ -4,7 +4,7 @@ import json
import logging
import os
import tomllib
from dataclasses import asdict, dataclass
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Literal
@@ -195,6 +195,27 @@ class PushConfig(Contract):
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() -> 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 = os.environ.get("OPENULTRASAST_RUNS_DIR")
if not override:
return str(_user_cache_dir() / "openultrasast" / "runs")
path = Path(override)
return str(path if path.is_absolute() else Path.cwd() / path)
@dataclass(frozen=True)
class ResolvedConfig:
models: ModelConfig = ModelConfig()
@@ -208,7 +229,9 @@ class ResolvedConfig:
obligations: ObligationsConfig = ObligationsConfig()
model: ModelLayerConfig = ModelLayerConfig()
push: PushConfig = PushConfig()
runs_dir: str = ".openultrasast/runs"
# 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)
def load_config(config_path: Path | None = None, *, dotenv: bool = True) -> ResolvedConfig:
@@ -232,7 +255,6 @@ def load_config(config_path: Path | None = None, *, dotenv: bool = True) -> Reso
obligations=_load_obligations(data.get("obligations", {})),
model=_load_model(data.get("model", {})),
push=PushConfig.from_payload(data.get("push", {})),
runs_dir=os.environ.get("OPENULTRASAST_RUNS_DIR", ".openultrasast/runs"),
)
+4
View File
@@ -440,6 +440,10 @@ _COVERAGE_DEGRADATIONS: dict[str, str] = {
"language not covered: {language} ({count} files). No quick rules{engine} exist for it, so **silence about "
"these files is not a clean result**."
),
"ledger_not_written": (
"The false-positive ledger in the analysed tree could not be written, so this scan's learnings are kept "
"only in this run directory and the next scan starts without them. {detail}"
),
}
+1 -1
View File
@@ -19,7 +19,7 @@ def create_scan_run(target: Path, config: ResolvedConfig) -> ScanRun:
resolved_target = target.resolve()
timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
scan_id = f"{timestamp}-{uuid4().hex[:8]}"
root = resolved_target / config.runs_dir / scan_id
root = Path(config.runs_dir) / scan_id
root.mkdir(parents=True, exist_ok=False)
(root / "preprocess").mkdir()
write_resolved_config(config, root / "resolved_config.json")