diff --git a/.gitignore b/.gitignore index 1ea4a3a6..df349030 100644 --- a/.gitignore +++ b/.gitignore @@ -122,6 +122,8 @@ htmlcov/ # Machine-readable locks .machine_readable/.locks/ +# Serialises feed and mirror appends in dispatch-runner.sh. +shared-context/learning/*.jsonl.lock # Temp diff --git a/docs/design/e0-12-outcome-route-decision.adoc b/docs/design/e0-12-outcome-route-decision.adoc index 5471111d..78634389 100644 --- a/docs/design/e0-12-outcome-route-decision.adoc +++ b/docs/design/e0-12-outcome-route-decision.adoc @@ -3,11 +3,14 @@ :toc: :date: 2026-11-23 -Status: PROPOSED; no owner ruling is recorded here. The bounded NS-02 producer -identity patch can be reviewed, but full E0-12 closure and automatic delivery -remain unqualified. Production dispatch remains quarantined. +Status: owner direction APPROVED on 2026-11-23. Jonathan approved the +recommended single fleet admission and correlated-rescan direction. The +original bounded producer patch and counterexample below remain historical +evidence. The follow-on defines actual versioned delivery; complete E0-12, +post-fix state attribution and production operation still require their +acceptance evidence. Production dispatch remains quarantined. -== Decision requested +== Approved direction Adopt the existing trusted fleet importer as the sole admission path for a producer-identified attempt. Retain Hypatia's rescan as evidence about that @@ -15,10 +18,30 @@ attempt, with explicit correlation and at most one effective contribution to learning per attempt. The current direct callback must cease creating an additional independent qualified attempt for the same dispatch. -This is the recommended contract direction, not an implemented route change -or a claim that the observation/revision schema already exists. It needs the -owner's ruling because the existing May contract requires the direct recording -call, while the E0 design introduces a distinct identity-preserving importer. +The owner approved this contract direction after reviewing the counterexample +and the conflict with the May mandatory recording call. The follow-on amends +that contract explicitly. Approval is not a claim that route implementation, +observation state binding or qualification revision machinery is complete. + +The bounded v1 uses `attempt_contract = "fleet-attempt/1"`, delivers directly +to the configured fleet feed, and suppresses independent direct recording for +identified attempts. The consumer stores its own versioned admission and +correlated observation. Mutable post-fix state is not yet bound: a later clean +or adverse scan is retained only as unbound audit evidence. Failed/incomplete +attempts retain their existing qualification criteria. This limitation is +required to avoid attributing a later repair's effects to an earlier attempt. + +The matching consumer must be deployed and configured before any producer +activation. An older E0-11 reader ignores the new marker and can still credit +a producer `verified` row under its historical interpretation. The version +field alone cannot make that older reader refuse it. Quarantine remains the +activation boundary. + +Pair the actual configured roots, not only the code versions: Hypatia's fleet +root must resolve to the producer's `FLEET_ROOT`, and its `HYPATIA_REPOS_DIR` +must identify the same repository root as `REPOS_BASE`. The real learning store +must be named by `HYPATIA_VERISIM_DATA_PATH` where configured. A runner cannot +prove the roots of another process whose configuration was not supplied. == Authorities and measured sources @@ -41,11 +64,11 @@ The Hypatia sources below are pinned at default rescan behavior. Its later verdict table makes failed/incomplete calls qualified failures without a rescan. -== S-01: Producer-to-learning admission +== S-01: Historical producer-to-learning admission counterexample [cols="2,3,3",options="header"] |=== -|Path |Current behavior |Identity and qualification +|Path |Behavior at the pinned baseline |Identity and qualification |Producer start |The NS-02 patch writes `shared-context/learning/fix-attempts.jsonl`. |One producer ID, before execution; no outcome or evidence credit. @@ -114,11 +137,14 @@ an expected-bad passing test. A future exclusive-ingress design needs an acceptance test through its actual chosen flow; this artificial dual-call diagnostic is not a universal acceptance condition for every possible design. -Reproduce both witnesses from a configured test Hypatia checkout: +Reproduce both historical witnesses from the exact isolated revisions below. +These commands do not test the approved v1 implementation: [source,shell] ---- -# Set these to the two isolated checkouts; do not use a live fleet store. +# Fleet revision: 565f075cf204f25f5b648547b8d8ae46fe1977ff (#709). +# Hypatia revision: d158aed87f76b93e4f291e995bef9f26559c7fb2. +# Set these to those isolated checkouts; do not use a live fleet store. export FLEET_CHECKOUT=/absolute/gitbot-fleet export HYPATIA_CHECKOUT=/absolute/hypatia export DISPATCH_TEST_HYPATIA_HOME="$HYPATIA_CHECKOUT" @@ -129,10 +155,31 @@ bash "$FLEET_CHECKOUT/scripts/tests/dispatch-paths.sh" cd "$HYPATIA_CHECKOUT" mix run --no-start "$FLEET_CHECKOUT/tests/hypatia-event-import-test.exs" mix run --no-start "$FLEET_CHECKOUT/tests/hypatia-route-counterexample.exs" -# The final command currently exits 1 and reports the duplicate contribution. +# The final command at those revisions exits 1 and reports the duplicate contribution. ---- -== Recommended ruling: one attempt admission, correlated rescan evidence +The approved v1 pair has a separate actual-delivery witness. From the matching +Hypatia consumer checkout, with Elixir 1.19.4 / OTP 27.3.4.19 and Nickel 1.11.0: + +[source,shell] +---- +export MIX_ENV=test +export NICKEL=/absolute/nickel +mix run --no-start /absolute/gitbot-fleet/tests/hypatia-single-admission-test.exs +---- + +It uses the actual runner in a disposable fixture, the canonical Mix event-ID +generator, a controlled fixer and scanner subprocess, and the configured feed. +No copying step delivers an original source event. Its only injected duplicate +is an explicit replay control after the original events have been admitted. +This tests delivery, identity, evidence gating and receipt binding; it does not +test the production scanner's effectiveness on real repairs. + +The existing fleet workflow jobs run shell contracts; they do not invoke this +cross-repository witness or certify a deployed consumer pair. Their green +status alone is insufficient evidence for activation. + +== Approved ruling: one attempt admission, correlated rescan evidence . Use the trusted E0-11 fleet import as the canonical admission path for producer-identified dispatch attempts. The source is append-only; primary diff --git a/docs/operations/NS-02-producer-identity.adoc b/docs/operations/NS-02-producer-identity.adoc index 3b2c984f..148d45e2 100644 --- a/docs/operations/NS-02-producer-identity.adoc +++ b/docs/operations/NS-02-producer-identity.adoc @@ -3,10 +3,14 @@ :toc: :date: 2026-11-23 -Status: implemented and independently reviewed for the bounded producer -contract. Full E0-12 closure remains blocked on the route and observation -decision in `docs/design/e0-12-outcome-route-decision.adoc`. No production -dispatch or quarantine removal occurred. +Status: historical bounded producer evidence at PR #709, +`565f075cf204f25f5b648547b8d8ae46fe1977ff`. The behavior and results below +describe that exact revision, including its former transport destinations and +direct callback. The owner subsequently approved the route direction in +`docs/design/e0-12-outcome-route-decision.adoc`; the versioned follow-on is +documented in `docs/operations/NS-02-single-admission.adoc`. Full E0-12 closure, +post-fix state attribution and production activation are not established by +this historical record. No quarantine removal occurred. Fleet base: `f1b14e2a352491ff7972f0dfd592bfbb28d2f32c`. Hypatia generator/importer base: `d158aed87f76b93e4f291e995bef9f26559c7fb2`. diff --git a/docs/operations/NS-02-single-admission.adoc b/docs/operations/NS-02-single-admission.adoc new file mode 100644 index 00000000..f1b631f9 --- /dev/null +++ b/docs/operations/NS-02-single-admission.adoc @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += NS-02: Single fleet admission producer evidence +:toc: +:date: 2026-11-23 + +Status: implemented and independently reviewed within the approved v1 scope. +Jonathan approved single trusted fleet admission with rescans as correlated +evidence on 2026-11-23. This note records the producer change and the local +paired acceptance witness. Production dispatch remains quarantined; no +activation, quarantine removal or full E0-12 closure is claimed. + +The producer change follows fleet revision +`565f075cf204f25f5b648547b8d8ae46fe1977ff` (#709). The earlier +link:NS-02-producer-identity.adoc[producer identity evidence] describes that +historical revision. The +link:../design/e0-12-outcome-route-decision.adoc[approved route decision] +records why independent direct recording and fleet import cannot both admit +the same attempt. + +== Implemented producer contract + +An executable fix attempt uses the existing +`cd "$HYPATIA_HOME" && mix hypatia.event_id` task once to obtain its canonical +ADR-008 version 8, profile T event ID. The runner validates the final output +line, allowing the task's documented compile chatter. A nonzero generator exit +is refused even if its output contains a plausible ID. There is no fallback +generator or generic outcome path without an ID for an actual fix attempt. + +Before invoking either a fix script or RRA, the runner appends the unchanged, +compact, sorted six-field start record. Its keys are `chain_version`, +`event_id`, `kind`, `producer`, `recipe_id` and `repo`; its fixed values include +`chain_version = "e0-receipt/1"`, `kind = "start"` and +`producer = "dispatch-runner"`. The start is separate from the outcome feed +and earns no learning credit. Interruption after this append can leave a start +without an outcome. + +Every actual outcome adds `attempt_contract = "fleet-attempt/1"` and +`repo_relative_path`. The latter is the normalized, resolved repository target +relative to `REPOS_BASE`, after `program_path`, repository override and symlink +resolution. Targets outside that root are refused. This field locates the +target; it does not bind a repository snapshot or establish when a later scan +observed it. + +[cols="2,4,3",options="header"] +|=== +|Record |Destination |Write contract +|Start +|`$FLEET_ROOT/shared-context/learning/fix-attempts.jsonl` +|Appended before execution, with the attempt's event ID. +|Canonical producer feed +|`$FLEET_ROOT/shared-context/learning/fix-outcomes.jsonl` +|First outcome append; this is the matching importer's source. +|Local transport mirror +|`$HYPATIA_DATA/dispatch/fleet-outcomes/YYYY-MM.jsonl` +|Exact serialized feed row, written after the feed. +|Central transport mirror +|`$VERISIMDB_DATA/dispatch/fleet-outcomes/YYYY-MM.jsonl` +|Exact serialized feed row, written after earlier distinct destinations. +|=== + +The canonical producer feed is an input to admission. Hypatia owns its +canonical admitted outcomes and receipts. Raw transport copies no longer go +to the consumer's `outcomes/` directory. Each attempt keeps one event ID +across its start, feed row and mirrors; two otherwise identical executions +receive different IDs. + +Identified attempts never call `mix hypatia.record_outcome`, including when +`HYPATIA_OUTCOME_REPORT=on`. The trusted fleet importer is their sole admission +path. The existing repository rescan queue remains a cache-refresh mechanism; +it is not an independent admission or correlated observation contract. + +The existing licence/policy refusal remains a separate, non-execution case. +It mints no attempt ID, writes no start and retains its legacy row shape and +best-effort false-positive callback. `HYPATIA_OUTCOME_REPORT` controls only +that refusal callback, not mandatory delivery of actual attempt outcomes. +The licence gate and unconditional production exit 78 before manifest +processing remain unchanged. + +== Aliases and failure semantics + +The runner resolves paths and checks existing file identity to coalesce +textual, symlink and hardlink aliases among the feed and transport mirrors. +An aliased destination receives one append. Any alias between the start file +and an outcome destination is refused. The checks also refuse paths within +known `outcomes/` or `receipts/` ledgers and existing hardlinks to their JSONL +files. Known roots include the transport roots and the explicitly supplied +`HYPATIA_VERISIM_DATA_PATH`. + +These are checks of the paths visible to the producer process. They do not +establish an atomic multi-file transaction, power-loss durability or the +configuration of another process. The test controls use real symlinks and +hardlinks, including existing ledger bytes that must remain unchanged. + +* Generator, path-validation or start-append failure prevents execution. +* Feed-append failure prevents subsequent mirror writes. +* Mirror failure leaves the already appended canonical feed row committed, + reports the error and does not retry the fixer or mint another ID. The + committed feed row remains available to the consumer. +* Infrastructure failures in parallel children reach the parent through the + existing dispatch error marker. Successful verdict counters are updated + only after the required outcome writes succeed. + +== Consumer and deployment pairing + +The matching `fleet-attempt/1` consumer must be deployed and configured before +any producer activation. A failing control with the older E0-11 consumer +showed it crediting a producer `verified` assertion: the import returned one +qualified contribution where the new witness required zero. The older reader +ignores the new marker; the version field cannot make it reject the row. +Unchanged quarantine remains the activation boundary. + +The physical roots must also agree across the two processes: + +* Hypatia's configured fleet root, including `HYPATIA_FLEET_PATH` when used, + must resolve to the producer's `FLEET_ROOT`. +* The consumer's `HYPATIA_REPOS_DIR` must identify the same repository root as + the producer's `REPOS_BASE`. +* `HYPATIA_VERISIM_DATA_PATH`, when supplied, must identify the consumer's + actual canonical learning store. `HYPATIA_DATA` and `VERISIMDB_DATA` name + transport roots and do not establish that consumer configuration by + themselves. + +The runner checks an explicitly supplied fleet root for mismatch and checks +an explicitly supplied consumer store for ledger pollution. Relative Hypatia +settings resolve from `HYPATIA_HOME`. Pairing an independently configured +consumer remains an integration prerequisite; unprovided cross-process roots +cannot be verified by the producer. + +In v1 the consumer embeds its own correlated rescan observation in one +canonical admitted outcome. A later clean or adverse scan of mutable, +unbound state remains audit-only: it supplies neither positive credit nor +false-positive blame for the earlier attempt. Existing failed/incomplete +numeric qualification criteria are retained. Binding positive observations +to the actual post-fix state remains a separate requirement. + +== Recorded verification + +The final local checks used Elixir 1.19.4 / OTP 27.3.4.19 for canonical Mix +generation and the paired witness. The receipt check used Nickel 1.11.0. + +[cols="3,3",options="header"] +|=== +|Check |Recorded result +|`bash tests/outcome-verdict-test.sh` +|63 passed, 0 failed; also invokes the 189-assertion whole-runner fixture. +|`bash scripts/tests/dispatch-paths.sh` +|189 passed, 0 failed in the focused runner controls. +|Same runner fixture with the actual canonical Mix generator +|189 passed, 0 failed; real emitted rows were captured. +|`bash tests/automation-quarantine-test.sh` +|All seven blocked invocations and the no-publication/state-mutation control passed. +|`bash tests/hypatia-record-outcome-smoke.sh` +|5 passed, 0 failed for the retained refusal helper guards. +|Bash syntax checks on the four changed shell files; `git diff --check` +|Passed. ShellCheck was unavailable locally. +|Independent read-only producer review +|No source blocker after review of routing, callback restriction, target resolution, alias controls and failure propagation. +|`tests/hypatia-single-admission-test.exs` with the matching consumer +|1 test, 0 failures; all four emitted receipts passed the existing Nickel receipt contract. +|=== + +The runner controls cover all actual verdict classes, interrupted starts, +missing or invalid IDs, generator failures, start/feed/mirror write failures, +parallel failure propagation, alias coalescing and refusal, normalized target +selection, preserved policy refusal and zero direct recorder calls for +identified attempts. + +Failing-before controls recorded the old producer's missing canonical feed +and independent recorder call. The earlier producer unit control had eight +failures, including missing version fields and acceptance of an actual outcome +without identity. The paired witness failed against the historical producer +at the missing-feed assertion, and against the older consumer at the incorrect +success credit. These are distinct from the passing matching-pair result. + +Session evidence was retained outside the repository under +`notes/continuation/`: `admission-final-outcome.log`, +`admission-final-quarantine.log`, `admission-final-smoke.log`, +`admission-canonical-generator.log`, `admission-red-feed.log`, +`admission-red-unit.log`, `single-admission-red-delivery.log`, +`single-admission-red-consumer.log` and `single-admission-green-delivery.log`. +The commands and assertions below are the reproducible repository evidence. + +== What the paired witness establishes + +The witness runs the actual runner in a disposable fixture with a controlled +fixer and the canonical Mix generator. Its established test seam removes only +the two unconditional interlock lines from that disposable copy. It does not +add a production bypass flag. Separate quarantine checks exercise the +unchanged production entrypoints. + +The runner itself creates the configured feed. No copy populates the source +for initial delivery. The matching consumer reads that same feed and admits +four distinct attempts: two qualified failures and two audit-only outcomes. +The test requires the same four unique IDs across starts, source outcomes, +admitted outcomes and receipts. Both transport mirrors match the source +bytes. A sentinel rejects any direct recording call for an identified +attempt. + +The scanner is a real subprocess invocation of a controlled fixture +executable. It checks the repository target argument and returns selected +clean or adverse JSON. The test checks both resulting unbound observations, +their distinct observation-versus-attempt IDs and their exact source-row +digests. This establishes invocation, interpretation and correlation; it does +not test the production scanner's effectiveness on real repairs. + +All four receipts bind to the canonical admitted row bytes, retain empty +revision-parent lists, and pass Hypatia's existing `schema/receipt.ncl` through +Nickel 1.11.0. After initial admission, the test explicitly appends duplicate +source bytes as a replay control. Repeated imports leave stored bytes and +the scan invocation count unchanged. That later injection is not a delivery +step for the original attempts. + +== Reproduction with matching checkouts + +Use isolated checkouts of this producer change and the matching +`fleet-attempt/1` consumer. Configure Elixir 1.19.4 / OTP 27.3.4.19, Hypatia's +test dependencies, Bash, jq and Nickel 1.11.0. Put the required executables on +`PATH`; these placeholders are not live store locations. + +[source,shell] +---- +export FLEET_CHECKOUT=/absolute/gitbot-fleet +export HYPATIA_CHECKOUT=/absolute/hypatia +export MIX_ENV=test + +cd "$FLEET_CHECKOUT" +bash tests/outcome-verdict-test.sh +bash tests/automation-quarantine-test.sh +bash tests/hypatia-record-outcome-smoke.sh +bash -n scripts/dispatch-runner.sh scripts/tests/dispatch-paths.sh \ + tests/outcome-verdict-test.sh tests/hypatia-record-outcome-smoke.sh +git diff --check +---- + +The outcome suite invokes the runner fixture. To run that fixture with the +actual canonical generator and retain its emitted evidence: + +[source,shell] +---- +export DISPATCH_TEST_HYPATIA_HOME="$HYPATIA_CHECKOUT" +export DISPATCH_TEST_MIX_BIN="$(command -v mix)" +export DISPATCH_TEST_EVIDENCE_DIR="$(mktemp -d)" +bash "$FLEET_CHECKOUT/scripts/tests/dispatch-paths.sh" +---- + +The evidence directory contains `success-feed.jsonl`, `success-primary.jsonl`, +`success-central.jsonl`, `success-starts.jsonl` and their `failure-*` +counterparts. Each feed, primary and start file contains two attempts; each +central file is the exact second outcome. These captures are separate from +the no-copy witness, which constructs and consumes its own disposable feed. + +Run the paired witness from the matching Hypatia checkout, without starting +the application: + +[source,shell] +---- +cd "$HYPATIA_CHECKOUT" +export NICKEL="$(command -v nickel)" +mix run --no-start "$FLEET_CHECKOUT/tests/hypatia-single-admission-test.exs" +---- + +The witness configures both fixture roots explicitly. Its +`FLEET_SINGLE_ADMISSION_SOURCE` override can select a historical producer for +a failing-before control; that is not a supported deployment pairing. + +== Claim boundary + +The existing fleet workflow jobs execute shell contracts. They do not run the +paired consumer witness or certify the deployed consumer version and roots. +A green shell job alone therefore does not establish a supported pair. + +The evidence establishes local producer delivery, identity preservation, +correlated audit evidence, receipt binding and replay stability for the +controlled fixture. It does not establish production activation, scanner +effectiveness, post-fix snapshot attribution, power-loss durability, +exactly-once neural parameter updates, corpus quality, full E0 acceptance or a +higher Kautz qualification. Those claims require their own evidence. diff --git a/scripts/dispatch-runner.sh b/scripts/dispatch-runner.sh index ec8e5be6..1d1911c7 100755 --- a/scripts/dispatch-runner.sh +++ b/scripts/dispatch-runner.sh @@ -179,10 +179,12 @@ echo " Dry run: $DRY_RUN" echo "" # --- Outcome recording --- -# Write outcomes to hypatia's local store (primary) and central store (backup) -OUTCOME_FILE="${HYPATIA_DATA}/outcomes/$(date -u +%Y-%m).jsonl" -OUTCOME_FILE_CENTRAL="${VERISIMDB_DATA}/outcomes/$(date -u +%Y-%m).jsonl" -mkdir -p "$(dirname "$OUTCOME_FILE")" +# The configured fleet importer owns admission. Raw transport rows never go +# into Hypatia's canonical outcomes ledger. The fleet feed is committed first; +# monthly transport mirrors preserve its exact bytes, outside that ledger. +OUTCOME_FILE="${FLEET_ROOT}/shared-context/learning/fix-outcomes.jsonl" +OUTCOME_FILE_LOCAL="${HYPATIA_DATA}/dispatch/fleet-outcomes/$(date -u +%Y-%m).jsonl" +OUTCOME_FILE_CENTRAL="${VERISIMDB_DATA}/dispatch/fleet-outcomes/$(date -u +%Y-%m).jsonl" # E0 receipt design, section 5.2: starts are separate from every outcome log. ATTEMPT_FILE="${FLEET_ROOT}/shared-context/learning/fix-attempts.jsonl" @@ -198,27 +200,27 @@ RESCAN_REPOS_FILE="$(mktemp /tmp/dispatch-rescan-repos.XXXXXX)" source "$(dirname "${BASH_SOURCE[0]}")/lib/outcome-verdict.sh" # Parallel jobs on one repo take a per-repo lock around check/fix/check -# (repo_lock), so --parallel needs flock. Refuse rather than run unlocked. -if [[ "$PARALLEL" -gt 1 ]] && ! command -v flock &>/dev/null; then - echo "ERROR: --parallel $PARALLEL needs flock (util-linux) to serialise fixes per repo" >&2 +# (repo_lock), and every outcome append holds the feed lock, so flock is +# needed for any run. Refuse before an attempt rather than after a fix. +if ! command -v flock &>/dev/null; then + echo "ERROR: dispatch needs flock (util-linux) to serialise fixes and outcome appends" >&2 exit 1 fi # --- Hypatia closed-loop contract --- # -# Per hypatia/docs/operations/dispatch-runner-contract.adoc, after each -# fix the runner MUST invoke `mix hypatia.record_outcome` so Bayesian -# confidence updating, auto-quarantine, and re-scan verification all see -# real evidence. Without this call, every recipe stays at -# :insufficient_data and the closed-loop verification metric (PR #309) -# never engages. Closes estate-audit blocker C15. +# Owner ruling: identified attempts enter learning only through the trusted +# fleet feed. The importer owns any correlated rescan observation and admission; +# a successful append here is delivery, not proof that either has happened. +# The independent Mix recorder survives only for policy refusals, which are not +# executed attempts. Mutable post-fix trees carry no snapshot binding in v1. # # Configuration via env: # HYPATIA_HOME path to the hypatia checkout (defaults to # $REPOS_BASE/hypatia) -# HYPATIA_OUTCOME_REPORT set to "off" to disable outcome reports; -# defaults to "on". Fix attempts still require -# mix and HYPATIA_HOME to mint their event id. +# HYPATIA_OUTCOME_REPORT set to "off" to disable legacy refusal callbacks; +# defaults to "on". Canonical delivery is mandatory. +# Fix attempts still need mix to mint their event id. # HYPATIA_BATCH_ID when set, exit-2 hints suggest # `mix hypatia.rollback_batch $HYPATIA_BATCH_ID` # @@ -230,43 +232,10 @@ HYPATIA_HOME="${HYPATIA_HOME:-${REPOS_BASE}/hypatia}" HYPATIA_OUTCOME_REPORT="${HYPATIA_OUTCOME_REPORT:-on}" HYPATIA_BATCH_ID="${HYPATIA_BATCH_ID:-}" -# Does this Hypatia know `--verdict`? Learned ONCE per run, from the help text of -# the task and never from an exit code: a Hypatia from before E0-01 ignores an -# option that it does not know, so a no_op call would be recorded as a success. -# verdict Hypatia names --verdict: every verdict is passed to it, and no_op and -# unverified are recorded (they carry no credit). -# legacy an older Hypatia: no --verdict, and no call for no_op or unverified -# (the behaviour before this check, exactly). -# off no outcome calls (reporting off, no checkout, no mix). -# A help command that fails is not an older Hypatia: the run stops, visibly. -HYPATIA_VERDICT_MODE="off" -hypatia_detect_verdict_mode() { - HYPATIA_VERDICT_MODE="off" - [[ "$HYPATIA_OUTCOME_REPORT" == "on" ]] || return 0 - [[ -d "$HYPATIA_HOME" ]] || return 0 - command -v mix &>/dev/null || return 0 - - local help_text rc=0 - help_text=$(cd "$HYPATIA_HOME" && mix help hypatia.record_outcome 2>&1) || rc=$? - if [[ "$rc" -ne 0 ]]; then - HYPATIA_VERDICT_MODE="error" - echo "ERROR: 'mix help hypatia.record_outcome' failed (exit $rc) in $HYPATIA_HOME: Hypatia does not answer, and a Hypatia that does not answer is not an older Hypatia. Stopping." >&2 - return 1 - fi - if grep -q -- '--verdict' <<< "$help_text"; then - HYPATIA_VERDICT_MODE="verdict" - else - HYPATIA_VERDICT_MODE="legacy" - fi - echo "hypatia outcome mode: $HYPATIA_VERDICT_MODE" -} - -hypatia_record_outcome() { +hypatia_record_refusal() { local recipe_id="$1" local repo="$2" local file="$3" - local outcome="$4" - local verdict="${5:-}" # Opt-out short-circuit. if [[ "$HYPATIA_OUTCOME_REPORT" != "on" ]]; then @@ -292,13 +261,6 @@ hypatia_record_outcome() { local file_arg="${file:-.}" [[ -z "$file_arg" ]] && file_arg="." - # The verdict goes along only when Hypatia knows the option, and only the - # 5 verdicts of the pair table (a refusal has none). - local verdict_args=() - if [[ "$HYPATIA_VERDICT_MODE" == "verdict" && -n "$verdict" ]]; then - verdict_args=(--verdict "$verdict") - fi - local rc=0 ( cd "$HYPATIA_HOME" @@ -306,8 +268,7 @@ hypatia_record_outcome() { --recipe "$recipe_id" \ --repo "$repo" \ --file "$file_arg" \ - --outcome "$outcome" \ - "${verdict_args[@]}" + --outcome false_positive ) || rc=$? case "$rc" in @@ -326,12 +287,87 @@ hypatia_record_outcome() { return "$rc" } +# Physical paths, not environment variable names, separate source, starts and +# learning ledgers. HYPATIA_DATA/VERISIMDB_DATA are transport roots, not a claim +# about the consumer's actual store. An explicit consumer store is checked too; +# otherwise pairing that process with this fleet root remains a deployment +# prerequisite. Relative Hypatia settings resolve from its checkout. +validate_outcome_paths() { + local path start_path resolved root ledger file configured_fleet + local paths=("$OUTCOME_FILE" "$OUTCOME_FILE_LOCAL" "$OUTCOME_FILE_CENTRAL") + local roots=("${HYPATIA_DATA:-}" "${VERISIMDB_DATA:-}") + start_path=$(realpath -m -- "$ATTEMPT_FILE") || return 1 + if [[ -n "${HYPATIA_FLEET_PATH:-}" ]]; then + configured_fleet="$HYPATIA_FLEET_PATH" + [[ "$configured_fleet" == /* ]] || configured_fleet="$HYPATIA_HOME/$configured_fleet" + configured_fleet=$(realpath -m -- "$configured_fleet") || return 1 + resolved=$(realpath -m -- "$FLEET_ROOT") || return 1 + if [[ "$configured_fleet" != "$resolved" ]]; then + echo "ERROR: configured Hypatia fleet source differs from FLEET_ROOT" >&2 + return 1 + fi + fi + # The consumer resolves each repo_relative_path under its own repository + # root, while this runner emits it relative to REPOS_BASE. A different root + # would attach rescans to another checkout, so refuse before any attempt. + if [[ -n "${HYPATIA_REPOS_DIR:-}" ]]; then + local configured_repos + configured_repos="$HYPATIA_REPOS_DIR" + [[ "$configured_repos" == /* ]] || configured_repos="$HYPATIA_HOME/$configured_repos" + configured_repos=$(realpath -m -- "$configured_repos") || return 1 + resolved=$(realpath -m -- "$REPOS_BASE") || return 1 + if [[ "$configured_repos" != "$resolved" ]]; then + echo "ERROR: configured Hypatia repository root differs from REPOS_BASE" >&2 + return 1 + fi + fi + # A checkout without LFS hydration holds a pointer, not JSONL; appending to + # it would hand the importer a malformed canonical feed. + if [[ -s "$OUTCOME_FILE" ]] && head -n 1 -- "$OUTCOME_FILE" | grep -q '^version https://git-lfs\.github\.com/spec/'; then + echo "ERROR: $OUTCOME_FILE is an unhydrated Git LFS pointer; hydrate it before dispatch" >&2 + return 1 + fi + if [[ -n "${HYPATIA_VERISIM_DATA_PATH:-}" ]]; then + root="$HYPATIA_VERISIM_DATA_PATH" + [[ "$root" == /* ]] || root="$HYPATIA_HOME/$root" + roots+=("$root") + fi + for path in "${paths[@]}"; do + resolved=$(realpath -m -- "$path") || return 1 + if [[ "$resolved" == "$start_path" || "$path" -ef "$ATTEMPT_FILE" ]]; then + echo "ERROR: attempt start and outcome destination alias each other: $path" >&2 + return 1 + fi + done + for root in "${roots[@]}"; do + [[ -n "$root" ]] || continue + for ledger in "$root/outcomes" "$root/receipts"; do + ledger=$(realpath -m -- "$ledger") || return 1 + for path in "$ATTEMPT_FILE" "${paths[@]}"; do + resolved=$(realpath -m -- "$path") || return 1 + if [[ "$resolved" == "$ledger" || "$resolved" == "$ledger/"* ]]; then + echo "ERROR: raw fleet evidence must not enter the canonical learning ledger: $path" >&2 + return 1 + fi + # realpath cannot reveal a hardlink into an existing ledger. + for file in "$ledger/"*.jsonl; do + if [[ "$path" -ef "$file" ]]; then + echo "ERROR: raw fleet evidence aliases a canonical ledger row file: $path" >&2 + return 1 + fi + done + done + done + done +} + # begin_attempt -> event_id, only after its start is appended. # event_id is ADR-008 version 8, profile T. E0-31 names Hypatia's existing Mix # task as the producer tool; there is no fallback generator. E0-08 section 5.2 # fixes this six-field start schema and its separate append-only destination. begin_attempt() { local recipe_id="$1" repo="$2" generated event_id start_json rc=0 + validate_outcome_paths || return 1 if [[ ! -d "$HYPATIA_HOME" ]]; then echo "ERROR: event id unavailable: HYPATIA_HOME is not a directory: $HYPATIA_HOME" >&2 return 1 @@ -365,7 +401,48 @@ begin_attempt() { printf '%s\n' "$event_id" } -# record_outcome [exit before after event_id] +# Appends one row to the canonical feed, then to each distinct mirror. The +# caller holds the feed lock. +append_outcome_rows() { + local json="$1" event_id="$2" + local path previous resolved duplicate + local written=("$OUTCOME_FILE") + if ! printf '%s\n' "$json" >> "$OUTCOME_FILE"; then + echo "ERROR: could not append outcome for event_id=$event_id to $OUTCOME_FILE" >&2 + return 1 + fi + # The feed is already committed. Transport mirrors are not another attempt. + # Coalesce textual, symlink and hardlink aliases, including aliases of the feed. + for path in "$OUTCOME_FILE_LOCAL" "$OUTCOME_FILE_CENTRAL"; do + resolved=$(realpath -m -- "$path") || return 1 + duplicate=false + for previous in "${written[@]}"; do + if [[ "$resolved" == "$(realpath -m -- "$previous")" || "$path" -ef "$previous" ]]; then + duplicate=true + break + fi + done + [[ "$duplicate" == false ]] || continue + if ! mkdir -p "$(dirname "$path")" || ! printf '%s\n' "$json" >> "$path"; then + echo "ERROR: could not mirror outcome for event_id=$event_id to $path; canonical feed row is committed" >&2 + return 1 + fi + written+=("$path") + done +} + +# Runs after a row is committed; the verdict and repo come from record_outcome. +record_outcome_followup() { + # Only the trusted importer admits an identified attempt. No independent + # recorder and no no-ID fallback may create a second learning event. + # The existing repo-only rescan is a cache refresh, not correlated evidence. + case "$verdict" in + verified) echo "$repo" >> "$RESCAN_REPOS_FILE" ;; + refused_*) hypatia_record_refusal "$recipe_id" "$repo" "$file" || true ;; + esac +} + +# record_outcome [exit before after event_id repo_relative_path] # # is one of lib/outcome-verdict.sh's verdicts, or refused_* for a # policy refusal. `outcome` is kept for older readers and reports the exit @@ -382,8 +459,29 @@ record_outcome() { # Execution attempts pass the id already committed by begin_attempt. # Policy refusals do not execute a fix and keep their existing row shape. local event_id="${9:-}" + local repo_relative_path="${10:-}" local bot="dispatch-runner" + case "$verdict" in + refused_*) + if [[ -n "$event_id" || -n "$repo_relative_path" ]]; then + echo "ERROR: a policy refusal is not an identified fix attempt" >&2 + return 1 + fi + ;; + verified|no_op|unverified|incomplete|failed) + if [[ ! "$event_id" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ ]] || + [[ -z "$repo_relative_path" || "$repo_relative_path" == /* || + "/$repo_relative_path/" == *'/../'* || "/$repo_relative_path/" == *'/./'* || + "/$repo_relative_path/" == *'//'* ]]; then + echo "ERROR: actual fix outcome requires an event id and normalized relative repo target" >&2 + return 1 + fi + ;; + *) echo "ERROR: unsupported fix outcome verdict: $verdict" >&2; return 1 ;; + esac + validate_outcome_paths || return 1 + local outcome case "$verdict" in refused_*) outcome="$verdict" ;; @@ -407,72 +505,36 @@ record_outcome() { --arg ts "$ts" \ --arg bot "$bot" \ --arg event_id "$event_id" \ + --arg repo_relative_path "$repo_relative_path" \ '{pattern_id: $pid, recipe_id: $rid, repo: $repo, file: $file, outcome: $outcome, verdict: $verdict, exit_code: (if $exit_code == "" then null else ($exit_code | tonumber) end), before_hits: (if $before == "NA" then null else ($before | tonumber) end), after_hits: (if $after == "NA" then null else ($after | tonumber) end), timestamp: $ts, bot: $bot} - + (if $event_id == "" then {} else {event_id: $event_id} end)'); then + + (if $event_id == "" then {} else + {event_id: $event_id, attempt_contract: "fleet-attempt/1", repo_relative_path: $repo_relative_path} + end)'); then echo "ERROR: could not encode outcome for $repo/$recipe_id event_id=$event_id" >&2 return 1 fi - if ! printf '%s\n' "$json" >> "$OUTCOME_FILE"; then - echo "ERROR: could not append outcome for event_id=$event_id to $OUTCOME_FILE" >&2 + # One lock covers the feed append and both mirror appends, so parallel + # attempts cannot interleave them and leave the mirrors in another order + # than the canonical feed. + local lock_fd append_rc=0 + if ! mkdir -p "$(dirname "$OUTCOME_FILE")" || + ! exec {lock_fd}>>"$OUTCOME_FILE.lock" || + ! flock -x "$lock_fd"; then + echo "ERROR: could not lock the outcome feed for event_id=$event_id" >&2 return 1 fi - # Avoid duplicate JSONL records when the two configured stores are the same. - local primary_path central_path - primary_path=$(realpath -m "$OUTCOME_FILE") - central_path=$(realpath -m "$OUTCOME_FILE_CENTRAL") - if [[ "$primary_path" != "$central_path" && ! "$OUTCOME_FILE" -ef "$OUTCOME_FILE_CENTRAL" ]]; then - if ! mkdir -p "$(dirname "$OUTCOME_FILE_CENTRAL")" || ! printf '%s\n' "$json" >> "$OUTCOME_FILE_CENTRAL"; then - echo "ERROR: could not mirror outcome for event_id=$event_id to $OUTCOME_FILE_CENTRAL; primary row is committed" >&2 - return 1 - fi - fi - - # Hypatia closed-loop contract — best-effort, never fails the dispatch - # loop. Map verdicts to the contract's outcome vocabulary: - # verified → success - # failed / incomplete → failure (the fix ran but the work remains) - # refused_* → false_positive (the recipe is misfiring, not - # the code; surfaces this to auto-quarantine) - # no_op / unverified → with a Hypatia that knows --verdict: recorded, as - # success WITH the verdict, which Hypatia stores as - # an audit row with no credit (E0-01). With an older - # Hypatia: skipped, as before, because without the - # verdict it would be recorded as a success. - local hypatia_outcome verdict_arg="" - case "$verdict" in - verified) - hypatia_outcome="success" - verdict_arg="$verdict" - echo "$repo" >> "$RESCAN_REPOS_FILE" - ;; - failed|incomplete) - hypatia_outcome="failure" - verdict_arg="$verdict" - ;; - refused_license_policy|refused_*) - hypatia_outcome="false_positive" - ;; - no_op|unverified) - [[ "$HYPATIA_VERDICT_MODE" == "verdict" ]] || return 0 - hypatia_outcome="success" - verdict_arg="$verdict" - ;; - *) - return 0 - ;; - esac - hypatia_record_outcome "$recipe_id" "$repo" "$file" "$hypatia_outcome" "$verdict_arg" || true + append_outcome_rows "$json" "$event_id" || append_rc=$? + exec {lock_fd}>&- + [[ "$append_rc" -eq 0 ]] || return "$append_rc" + record_outcome_followup } -# Learn once per run which of the 2 calls Hypatia takes. Stop if it does not answer. -hypatia_detect_verdict_mode || exit 1 - # --- Execute a single manifest entry --- execute_entry() { local entry="$1" @@ -581,6 +643,22 @@ execute_entry() { return fi + # Bind the locator to the actual target, including monorepo aliases + # and program_path. This is not a snapshot or evidence that a later + # rescan observes the fixer's post-execution repository state. + local repo_relative_path resolved_base + if ! resolved_base=$(realpath -e -- "$REPOS_BASE") || + ! repo_path=$(realpath -e -- "$repo_path"); then + mark_dispatch_error + return 1 + fi + if [[ "$repo_path" != "$resolved_base/"* ]]; then + echo "ERROR: resolved fix target must be a repository inside REPOS_BASE" >&2 + mark_dispatch_error + return 1 + fi + repo_relative_path="${repo_path#"$resolved_base"/}" + # Resolve fix_script from registry if not set in manifest if [[ "$fix_script" == "none" || "$fix_script" == "null" ]]; then local registry="$FLEET_SCRIPTS/fix-script-registry.json" @@ -625,7 +703,7 @@ execute_entry() { if [[ "$PARALLEL" -gt 1 ]]; then repo_unlock; fi verdict=$(outcome_verdict "$rc" "$before" "$after") echo " $verdict (exit $rc, targets $before -> $after)" - record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" "$before" "$after" "$event_id" || { + record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" "$before" "$after" "$event_id" "$repo_relative_path" || { rm -f "$tmp_finding" count EXECUTED mark_dispatch_error @@ -655,7 +733,7 @@ execute_entry() { local verdict verdict=$(outcome_verdict "$rc" NA NA) echo " $verdict (exit $rc)" - record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" NA NA "$event_id" || { + record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" NA NA "$event_id" "$repo_relative_path" || { count EXECUTED mark_dispatch_error return 1 diff --git a/scripts/tests/dispatch-paths.sh b/scripts/tests/dispatch-paths.sh index cbd0d098..341767ad 100755 --- a/scripts/tests/dispatch-paths.sh +++ b/scripts/tests/dispatch-paths.sh @@ -3,7 +3,7 @@ # Exercise the actual dispatch orchestration with inert fixes and isolated data. # Optional DISPATCH_TEST_HYPATIA_HOME and DISPATCH_TEST_MIX_BIN use the canonical # generator for successful cases. DISPATCH_TEST_EVIDENCE_DIR retains emitted rows -# for a separate consumer wire/replay witness; it does not enable delivery. +# including the actual canonical feed for the separate consumer witness. set -euo pipefail fleet_test_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" fixture="$(mktemp -d)" @@ -14,8 +14,9 @@ cp "$fleet_test_root/scripts/repo-path-overrides.json" "$fixture/checkout/script cp "$fleet_test_root/scripts/lib/outcome-verdict.sh" "$fixture/checkout/scripts/lib/" month="$(date -u +%Y-%m)" starts="$fixture/checkout/shared-context/learning/fix-attempts.jsonl" -primary="$fixture/primary/outcomes/$month.jsonl" -central="$fixture/central/outcomes/$month.jsonl" +feed="$fixture/checkout/shared-context/learning/fix-outcomes.jsonl" +primary="$fixture/primary/dispatch/fleet-outcomes/$month.jsonl" +central="$fixture/central/dispatch/fleet-outcomes/$month.jsonl" manifest="$fixture/primary/dispatch/pending.jsonl" canonical_mix="${DISPATCH_TEST_MIX_BIN:-$(command -v mix || true)}" pass=0 @@ -56,7 +57,13 @@ set -euo pipefail printf '%s\n' "$*" >> "$FIXTURE_ROOT/mix-calls" case "$*" in 'help hypatia.record_outcome') echo '--verdict verified|no_op|incomplete|unverified|failed'; exit 0 ;; - hypatia.record_outcome*) exit 0 ;; + hypatia.record_outcome*) + if [[ "$FIXTURE_ALLOW_REFUSAL" != yes ]]; then + touch "$FIXTURE_ROOT/unexpected-record" + echo 'independent recording forbidden for a producer attempt' >&2 + exit 99 + fi + exit 0 ;; hypatia.event_id) ;; *) echo 'unexpected mix arguments' >&2; exit 98 ;; esac @@ -110,14 +117,19 @@ STUB chmod +x "$fixture/bin/mix" "$fixture/bin/rra" "$fixture/checkout/scripts/fix-fixture.sh" reset_fixture() { - rm -rf "$fixture/primary/outcomes" "$fixture/central" "$fixture/checkout/shared-context" "$fixture/kin" + rm -rf "$fixture/primary/outcomes" "$fixture/primary/dispatch/fleet-outcomes" \ + "$fixture/central" "$fixture/checkout/shared-context" "$fixture/kin" + rm -f "$fixture/unexpected-record" : > "$fixture/mix-calls" : > "$fixture/fix-calls" printf '%s\n' '018e4000-0000-8000-8000-000000000001' \ '018e4000-0000-8000-8000-000000000002' > "$fixture/ids" touch "$fixture/repos/sample/needs-fix" printf '%s\n' '{"repo":"sample","tier":"eliminate","strategy":"auto_execute","pattern_id":"fixture","recipe_id":"recipe-fixture","fix_script":"fix-fixture.sh","auto_fixable":true}' > "$manifest" - generator_mode=ok fix_mode=ok report_mode=off parallel=1 limit=1 + generator_mode=ok fix_mode=ok report_mode=on parallel=1 limit=1 allow_refusal=no + hypatia_store="$fixture/learning-store" + hypatia_fleet="$fixture/checkout" + hypatia_repos="" runner_args=() hypatia_home="${DISPATCH_TEST_HYPATIA_HOME:-$fixture/hypatia}" runner_path="$fixture/bin:$PATH" @@ -129,8 +141,11 @@ invoke_runner() { PATH="$runner_path" FLEET_ROOT="$fixture/checkout" REPOS_BASE="$fixture/repos" \ HYPATIA_DATA="$fixture/primary" VERISIMDB_DATA="$store" \ HYPATIA_HOME="$hypatia_home" HYPATIA_OUTCOME_REPORT="$report_mode" \ + HYPATIA_FLEET_PATH="$hypatia_fleet" HYPATIA_VERISIM_DATA_PATH="$hypatia_store" \ + HYPATIA_REPOS_DIR="$hypatia_repos" \ KIN_DIR="$fixture/kin" RRA_BIN="$rra_bin" FIXTURE_ROOT="$fixture" \ FIXTURE_GENERATOR_MODE="$generator_mode" FIXTURE_FIX_MODE="$fix_mode" \ + FIXTURE_ALLOW_REFUSAL="$allow_refusal" \ DISPATCH_TEST_MIX_BIN="$canonical_mix" \ bash "$runner" --limit "$limit" --parallel "$parallel" "${runner_args[@]}" } @@ -143,11 +158,13 @@ expect_failure() { no_fix_or_outcome() { check "$1: fixer was not called" test ! -s "$fixture/fix-calls" check "$1: no outcome was written" test ! -s "$primary" + check "$1: no canonical feed row was written" test ! -s "$feed" } retain_rows() { [[ -n "${DISPATCH_TEST_EVIDENCE_DIR:-}" ]] || return 0 mkdir -p "$DISPATCH_TEST_EVIDENCE_DIR" cp "$starts" "$DISPATCH_TEST_EVIDENCE_DIR/$1-starts.jsonl" + cp "$feed" "$DISPATCH_TEST_EVIDENCE_DIR/$1-feed.jsonl" cp "$primary" "$DISPATCH_TEST_EVIDENCE_DIR/$1-primary.jsonl" cp "$central" "$DISPATCH_TEST_EVIDENCE_DIR/$1-central.jsonl" } @@ -162,6 +179,12 @@ check 'quarantine writes no primary state' test ! -e "$fixture/primary/outcomes" # Two identical manifest entries and initial repo states are two attempts. run_dispatch "$fixture/primary/." +check 'actual runner delivers to the canonical fleet feed' test -s "$feed" +check 'attempt declares frozen v1 and actual relative target' jq -e \ + '.attempt_contract == "fleet-attempt/1" and .repo_relative_path == "sample"' "$feed" +check 'identified attempt never calls the independent recorder' test ! -e "$fixture/unexpected-record" +check 'canonical feed and local mirror are byte-identical' cmp -s "$feed" "$primary" +check 'raw transport never writes the monthly learning ledger' test ! -e "$fixture/primary/outcomes" check 'first outcome is verified' jq -e '.verdict == "verified" and .before_hits == 1 and .after_hits == 0' "$primary" check 'same store gets exactly one outcome' test "$(wc -l < "$primary")" -eq 1 check 'start has exactly the ruled six fields' jq -e \ @@ -177,6 +200,8 @@ check 'identical attempts have distinct event ids' jq -se 'map(.event_id) | leng check 'both starts match their outcomes' test "$(jq -r .event_id "$starts")" "=" "$(jq -r .event_id "$primary")" check 'mirrored outcome is the exact same row' test "$(tail -n 1 "$primary")" "=" "$(cat "$central")" check 'mirror contains one outcome' test "$(wc -l < "$central")" -eq 1 +check 'all canonical feed rows match the local transport copy' cmp -s "$feed" "$primary" +check 'both identified attempts avoid the independent recorder' test ! -e "$fixture/unexpected-record" retain_rows success reset_fixture @@ -187,6 +212,8 @@ check 'failed fix retains its producer id and exit code' jq -e '.verdict == "fai check 'failed attempt keeps one id across all copies' test "$(jq -r .event_id "$starts")" "=" "$(jq -r .event_id "$primary")" check 'identical failed attempts have distinct event ids' jq -se 'map(.event_id) | length == 2 and (unique | length == 2)' "$primary" check 'failed mirrored outcome is byte-identical' test "$(tail -n 1 "$primary")" "=" "$(cat "$central")" +check 'failed attempts go to the same canonical feed' cmp -s "$feed" "$primary" +check 'failed attempts avoid the independent recorder' test ! -e "$fixture/unexpected-record" retain_rows failure reset_fixture @@ -233,24 +260,28 @@ for failure in directory append; do expect_failure "start $failure failure" no_fix_or_outcome "start $failure failure" done -for failure in primary central; do +for failure in feed primary central; do reset_fixture report_mode=on - if [[ "$failure" == primary ]]; then mkdir -p "$primary"; else mkdir -p "$central"; fi + case "$failure" in feed) mkdir -p "$feed";; primary) mkdir -p "$primary";; central) mkdir -p "$central";; esac expect_failure "$failure outcome append failure" check "$failure append failure leaves its start" test -s "$starts" check "$failure append failure does not call direct outcome reporting" test \ "$(grep -c '^hypatia.record_outcome ' "$fixture/mix-calls" || true)" -eq 0 - if [[ "$failure" == primary ]]; then - check 'primary append failure does not write a mirror' test ! -e "$central" - else - check 'mirror append failure preserves the committed primary row' jq -e '.event_id | type == "string"' "$primary" - fi + case "$failure" in + feed) + check 'feed failure writes no local mirror' test ! -e "$primary" + check 'feed failure writes no central mirror' test ! -e "$central" ;; + primary|central) + check "$failure mirror failure preserves the committed canonical feed" jq -e '.event_id | type == "string"' "$feed" + check "$failure mirror failure reports the existing commit" grep -q 'canonical feed row is committed' "$fixture/result" + check "$failure mirror failure never retries the fixer" test "$(wc -l < "$fixture/fix-calls")" -eq 1 ;; + esac done # Infrastructure failures must reach the parent under --parallel too: wait # without a job id otherwise hides a failed child behind an overall exit 0. -for failure in generator start primary central; do +for failure in generator start feed primary central; do reset_fixture limit=0 parallel=2 cat "$manifest" > "$fixture/entry" @@ -258,6 +289,7 @@ for failure in generator start primary central; do case "$failure" in generator) generator_mode=fail ;; start) mkdir -p "$starts" ;; + feed) mkdir -p "$feed" ;; primary) mkdir -p "$primary" ;; central) mkdir -p "$central" ;; esac @@ -303,18 +335,130 @@ run_dispatch check 'parallel attempts each receive an id' jq -se 'map(.event_id) | length == 2 and (unique | length == 2)' "$primary" check 'parallel starts and outcomes name the same attempts' test \ "$(jq -r .event_id "$starts" | sort)" "=" "$(jq -r .event_id "$primary" | sort)" -check 'parallel repo lock still credits only one fix' jq -se 'map(.verdict) | sort == ["no_op","verified"]' "$primary" +check 'parallel repo lock classifies only one verified fix' jq -se 'map(.verdict) | sort == ["no_op","verified"]' "$primary" +check 'parallel identified attempts avoid the independent recorder' test ! -e "$fixture/unexpected-record" +check 'parallel canonical feed and local mirror keep one order' cmp -s "$feed" "$primary" +check 'parallel canonical feed and central mirror keep one order' cmp -s "$feed" "$central" + +# Physical aliases coalesce transport writes but may never mix starts or raw +# transport with a canonical learning ledger. These fixtures use real symlinks +# and hardlinks; no permission test relies on the test user being unprivileged. +for alias_kind in symlink hardlink; do + reset_fixture + mkdir -p "$(dirname "$primary")" "$(dirname "$feed")" + : > "$feed" + if [[ "$alias_kind" == symlink ]]; then ln -s "$feed" "$primary"; else ln "$feed" "$primary"; fi + run_dispatch + check "$alias_kind alias of feed is appended once" test "$(wc -l < "$feed")" -eq 1 + check "$alias_kind feed alias preserves mirror bytes" cmp -s "$feed" "$central" + + reset_fixture + mkdir -p "$(dirname "$feed")" + : > "$starts" + if [[ "$alias_kind" == symlink ]]; then ln -s "$starts" "$feed"; else ln "$starts" "$feed"; fi + expect_failure "$alias_kind alias between feed and starts" + no_fix_or_outcome "$alias_kind alias between feed and starts" + check "$alias_kind start alias mints no event" test ! -s "$fixture/mix-calls" +done +reset_fixture +mkdir -p "$(dirname "$primary")" "$(dirname "$central")" +: > "$primary" +ln "$primary" "$central" +run_dispatch +check 'hardlinked local and central transports are appended once' test "$(wc -l < "$primary")" -eq 1 +check 'hardlinked transports contain the canonical bytes' cmp -s "$feed" "$primary" +reset_fixture +mkdir -p "$(dirname "$primary")" "$(dirname "$starts")" +: > "$starts" +ln "$starts" "$primary" +expect_failure 'transport alias of starts' +no_fix_or_outcome 'transport alias of starts' + +for alias_target in feed primary; do + reset_fixture + mkdir -p "$hypatia_store/outcomes" "$(dirname "$feed")" "$(dirname "$primary")" + printf '%s\n' '{"existing":"learning-row"}' > "$hypatia_store/outcomes/existing.jsonl" + if [[ "$alias_target" == feed ]]; then + ln "$hypatia_store/outcomes/existing.jsonl" "$feed" + else + ln "$hypatia_store/outcomes/existing.jsonl" "$primary" + fi + expect_failure "$alias_target hardlink into explicit learning ledger" + check "$alias_target ledger alias never calls the fixer" test ! -s "$fixture/fix-calls" + check "$alias_target ledger alias mints no event" test ! -s "$fixture/mix-calls" + check "$alias_target ledger bytes are unchanged" test "$(cat "$hypatia_store/outcomes/existing.jsonl")" = '{"existing":"learning-row"}' +done +reset_fixture +mkdir -p "$hypatia_store/outcomes" "$fixture/checkout/shared-context" +ln -s "$hypatia_store/outcomes" "$fixture/checkout/shared-context/learning" +expect_failure 'canonical feed directory inside explicit learning ledger' +check 'ledger directory alias never executes' test ! -s "$fixture/fix-calls" +check 'ledger directory alias creates no start' test ! -e "$hypatia_store/outcomes/fix-attempts.jsonl" +reset_fixture +hypatia_fleet="$fixture/another-fleet" +expect_failure 'explicit consumer fleet root differs' +no_fix_or_outcome 'explicit consumer fleet root differs' + +reset_fixture +hypatia_repos="$fixture/another-repos" +expect_failure 'explicit consumer repository root differs' +no_fix_or_outcome 'explicit consumer repository root differs' +check 'consumer repository root mismatch mints no event' test ! -s "$fixture/mix-calls" +reset_fixture +hypatia_repos="$fixture/repos" +run_dispatch +check 'matching consumer repository root is accepted' test -s "$feed" + +# A checkout whose feed is an unhydrated LFS pointer fails before any attempt. +reset_fixture +mkdir -p "$(dirname "$feed")" +printf '%s\n' 'version https://git-lfs.github.com/spec/v1' \ + 'oid sha256:0000000000000000000000000000000000000000000000000000000000000000' \ + 'size 1' > "$feed" +expect_failure 'unhydrated LFS pointer feed' +check 'LFS pointer feed never calls the fixer' test ! -s "$fixture/fix-calls" +check 'LFS pointer feed mints no event' test ! -s "$fixture/mix-calls" +check 'LFS pointer feed is left unchanged' test "$(wc -l < "$feed")" -eq 3 + +# The v1 path is the actual target, after alias/program_path/symlink resolution. +reset_fixture +mkdir -p "$fixture/repos/actual/nested" +touch "$fixture/repos/actual/nested/needs-fix" +jq -c --arg path "$fixture/repos/sample/../actual/./nested" '.repo="manifest-name" | .program_path=$path' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +run_dispatch +check 'program_path binds the actual normalized relative target' jq -e \ + '.repo == "manifest-name" and .repo_relative_path == "actual/nested"' "$feed" +reset_fixture +ln -s "$fixture/repos/actual/nested" "$fixture/repos/target-link" +jq -c '.repo="target-link"' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +run_dispatch +check 'target symlink records its actual resolved path' jq -e '.repo_relative_path == "actual/nested"' "$feed" +reset_fixture +mkdir -p "$fixture/repos/developer-ecosystem/julia-ecosystem/packages/Axiom.jl" +jq -c '.repo="Axiom.jl"' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +run_dispatch +check 'repository override records its actual relative target' jq -e \ + '.repo_relative_path == "developer-ecosystem/julia-ecosystem/packages/Axiom.jl"' "$feed" # No attempted execution means no new attempt id. Preserve the licence refusal. reset_fixture generator_mode=fail +allow_refusal=yes jq -c '.recipe_id = "recipe-license-hygiene"' "$manifest" > "$fixture/entry" mv "$fixture/entry" "$manifest" run_dispatch check 'licence refusal still has its original outcome' jq -e '.verdict == "refused_license_policy" and (has("event_id") | not)' "$primary" -check 'licence refusal mints no execution id' test ! -s "$fixture/mix-calls" +check 'licence refusal mints no execution id' test "$(grep -c '^hypatia.event_id$' "$fixture/mix-calls" || true)" -eq 0 +check 'licence refusal retains only its false-positive callback' test "$(cat "$fixture/mix-calls")" = \ + 'hypatia.record_outcome --recipe recipe-license-hygiene --repo sample --file . --outcome false_positive' +check 'licence refusal has no attempt contract or relative target' jq -e \ + '(has("attempt_contract") or has("repo_relative_path")) | not' "$feed" check 'licence refusal never calls the fixer' test ! -s "$fixture/fix-calls" check 'licence refusal creates no start' test ! -e "$starts" +check 'licence callback is the only permitted recording call' test ! -e "$fixture/unexpected-record" reset_fixture generator_mode=fail diff --git a/tests/hypatia-record-outcome-smoke.sh b/tests/hypatia-record-outcome-smoke.sh index aa945d05..1e7a05f3 100755 --- a/tests/hypatia-record-outcome-smoke.sh +++ b/tests/hypatia-record-outcome-smoke.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # SPDX-License-Identifier: MPL-2.0 # -# Smoke test for hypatia_record_outcome() in scripts/dispatch-runner.sh. +# Smoke test for the refusal-only hypatia_record_refusal() callback. # # Covers the no-op short-circuit paths that don't require an actual # hypatia checkout or `mix` on PATH: @@ -102,14 +102,14 @@ assert_warn_ok() { # Case 1: opt-out. HYPATIA_OUTCOME_REPORT=off \ assert_silent_ok "opt-out silently no-ops" \ - hypatia_record_outcome "rid-1" "owner/repo" "src/file.py" "success" + hypatia_record_refusal "rid-1" "owner/repo" "src/file.py" # Case 2: HYPATIA_HOME not a directory. HYPATIA_OUTCOME_REPORT=on \ HYPATIA_HOME="$TMP/does-not-exist" \ assert_warn_ok "missing HYPATIA_HOME warns and no-ops" \ "not a directory" \ - hypatia_record_outcome "rid-2" "owner/repo" "src/file.py" "success" + hypatia_record_refusal "rid-2" "owner/repo" "src/file.py" # Cases 3a-c need HYPATIA_HOME to exist so the recipe-id guard fires # rather than the missing-dir guard. @@ -119,19 +119,19 @@ mkdir -p "$TMP/repos/hypatia" HYPATIA_OUTCOME_REPORT=on \ HYPATIA_HOME="$TMP/repos/hypatia" \ assert_silent_ok "empty recipe_id silently no-ops" \ - hypatia_record_outcome "" "owner/repo" "src/file.py" "success" + hypatia_record_refusal "" "owner/repo" "src/file.py" # Case 3b: "none" recipe_id. HYPATIA_OUTCOME_REPORT=on \ HYPATIA_HOME="$TMP/repos/hypatia" \ assert_silent_ok "'none' recipe_id silently no-ops" \ - hypatia_record_outcome "none" "owner/repo" "src/file.py" "success" + hypatia_record_refusal "none" "owner/repo" "src/file.py" # Case 3c: "null" recipe_id. HYPATIA_OUTCOME_REPORT=on \ HYPATIA_HOME="$TMP/repos/hypatia" \ assert_silent_ok "'null' recipe_id silently no-ops" \ - hypatia_record_outcome "null" "owner/repo" "src/file.py" "success" + hypatia_record_refusal "null" "owner/repo" "src/file.py" echo "" echo "Results: $pass passed, $fail failed" diff --git a/tests/hypatia-single-admission-test.exs b/tests/hypatia-single-admission-test.exs new file mode 100644 index 00000000..bfd306c6 --- /dev/null +++ b/tests/hypatia-single-admission-test.exs @@ -0,0 +1,324 @@ +# SPDX-License-Identifier: MPL-2.0 +# Actual delivery witness: run from the matching Hypatia checkout with +# MIX_ENV=test mix run --no-start /absolute/fleet/tests/hypatia-single-admission-test.exs +# Nickel 1.11.0 is required on PATH or at the NICKEL environment path. +# FLEET_SINGLE_ADMISSION_SOURCE optionally selects another producer revision for +# the failing-before control. The source feed is never populated by test copy. + +unless Mix.env() == :test, do: raise("run this witness with MIX_ENV=test") + +if Process.whereis(Hypatia.Supervisor), + do: raise("run with --no-start and no running Hypatia application") + +{:ok, _} = Application.ensure_all_started(:telemetry) +ExUnit.start(autorun: false, seed: 0) + +defmodule Fleet.HypatiaSingleAdmissionTest do + use ExUnit.Case, async: false + + alias Hypatia.{EventId, LearningScheduler, OutcomeTracker, Receipt} + + @moduletag capture_log: true + @moduletag timeout: 180_000 + + setup do + source = + System.get_env("FLEET_SINGLE_ADMISSION_SOURCE", Path.expand("..", __DIR__)) + |> Path.expand() + + hypatia = File.cwd!() + real_mix = System.find_executable("mix") || raise("canonical Mix is required") + root = Path.join(System.tmp_dir!(), "fleet-admission-#{System.unique_integer([:positive])}") + data = Path.join(root, "data") + fleet = Path.join(root, "fleet") + repos = Path.join(root, "repos") + keys = [:verisimdb_data_path, :annealing_state_path, :fleet_path] + original = Map.new(keys, &{&1, Application.fetch_env(:hypatia, &1)}) + env_keys = ~w(PATH HYPATIA_REPOS_DIR ADMISSION_FIXTURE ADMISSION_SCAN_MODE) + original_env = Map.new(env_keys, &{&1, System.get_env(&1)}) + + on_exit(fn -> + for {key, value} <- original do + case value do + {:ok, prior} -> Application.put_env(:hypatia, key, prior) + :error -> Application.delete_env(:hypatia, key) + end + end + + for {key, value} <- original_env do + if value, do: System.put_env(key, value), else: System.delete_env(key) + end + + File.rm_rf!(root) + end) + + for dir <- ["data/dispatch", "data/recipes", "fleet/scripts/lib", "repos/sample", "bin"] do + File.mkdir_p!(Path.join(root, dir)) + end + + Application.put_env(:hypatia, :verisimdb_data_path, data) + Application.put_env(:hypatia, :annealing_state_path, Path.join(data, "annealing-states")) + Application.put_env(:hypatia, :fleet_path, fleet) + System.put_env("HYPATIA_REPOS_DIR", repos) + System.put_env("ADMISSION_FIXTURE", root) + System.put_env("PATH", Path.join(root, "bin") <> ":" <> System.fetch_env!("PATH")) + + original_runner = File.read!(Path.join(source, "scripts/dispatch-runner.sh")) + lines = String.split(original_runner, "\n") + + index = + Enum.find_index(lines, fn line -> + String.starts_with?(line, "printf ") and + String.contains?(line, "BLOCKED: repository directive enforcement is not qualified") + end) + + assert is_integer(index), "production quarantine marker must exist" + assert Enum.at(lines, index + 1) == "exit 78" + runner = Path.join(fleet, "scripts/dispatch-runner.sh") + + # The established test seam removes exactly the two unconditional interlock + # lines in a disposable copy. Production has no bypass flag. + isolated = lines |> List.delete_at(index + 1) |> List.delete_at(index) + File.write!(runner, Enum.join(isolated, "\n")) + assert length(lines) - length(isolated) == 2 + + for path <- ["scripts/repo-path-overrides.json", "scripts/lib/outcome-verdict.sh"] do + File.cp!(Path.join(source, path), Path.join(fleet, path)) + end + + executable!(Path.join(root, "bin/mix"), ~S""" + #!/usr/bin/env bash + set -euo pipefail + printf '%s\n' "$*" >> "$ADMISSION_FIXTURE/mix-calls" + case "$*" in + 'help hypatia.record_outcome') printf '%s\n' '--verdict'; exit 0 ;; + hypatia.event_id) exec "$ADMISSION_REAL_MIX" "$@" ;; + hypatia.record_outcome*) printf '%s\n' forbidden >> "$ADMISSION_FIXTURE/direct-calls"; exit 99 ;; + *) printf '%s\n' 'unexpected Mix command' >&2; exit 98 ;; + esac + """) + + executable!(Path.join(fleet, "scripts/fix-admission-fixture.sh"), ~S""" + #!/usr/bin/env bash + # outcome-predicate: --check + set -euo pipefail + if [[ "$1" == --check ]]; then + if [[ -e "$2/needs-fix" ]]; then echo 1; else echo 0; fi + exit 0 + fi + jq -e '.kind == "start" and .producer == "dispatch-runner"' \ + "$ADMISSION_FIXTURE/fleet/shared-context/learning/fix-attempts.jsonl" >/dev/null + printf '%s\n' executed >> "$ADMISSION_FIXTURE/fix-calls" + if [[ "$ADMISSION_FIX_MODE" == failure ]]; then exit 7; fi + rm -f "$1/needs-fix" + """) + + executable!(Path.join(root, "bin/panic-attack"), ~S""" + #!/usr/bin/env bash + set -euo pipefail + [[ "$1" == assail && "$2" == "$ADMISSION_FIXTURE/repos/sample" ]] + printf '%s\n' "$2" >> "$ADMISSION_FIXTURE/scan-calls" + if [[ "$ADMISSION_SCAN_MODE" == clean ]]; then + printf '%s\n' '{"weak_points":[]}' + else + printf '%s\n' '{"weak_points":[{"category":"FixtureCategory","file":"fixture.txt","line":1}]}' + fi + """) + + File.write!( + Path.join(data, "recipes/recipe-admission-fixture.json"), + Jason.encode!(%{ + "id" => "recipe-admission-fixture", + "confidence" => 0.5, + "target_categories" => ["FixtureCategory"] + }) + ) + + File.write!( + Path.join(data, "dispatch/pending.jsonl"), + Jason.encode!(%{ + "repo" => "sample", + "tier" => "eliminate", + "strategy" => "auto_execute", + "pattern_id" => "fixture", + "recipe_id" => "recipe-admission-fixture", + "fix_script" => "fix-admission-fixture.sh", + "auto_fixable" => true + }) <> "\n" + ) + + env = [ + {"FLEET_ROOT", fleet}, + {"REPOS_BASE", repos}, + {"HYPATIA_FLEET_PATH", fleet}, + {"HYPATIA_DATA", data}, + {"HYPATIA_VERISIM_DATA_PATH", data}, + {"VERISIMDB_DATA", Path.join(root, "mirror")}, + {"HYPATIA_HOME", hypatia}, + {"HYPATIA_OUTCOME_REPORT", "on"}, + {"KIN_DIR", Path.join(root, "kin")}, + {"ADMISSION_REAL_MIX", real_mix}, + {"GITHUB_TOKEN", ""}, + {"FLEET_DISPATCH_TOKEN", ""}, + {"BASH_ENV", ""}, + {"ENV", ""} + ] + + %{root: root, data: data, fleet: fleet, repos: repos, runner: runner, env: env} + end + + test "actual delivery admits each attempt once and never attributes an unbound scan", ctx do + run_attempt(ctx, "failure") + run_attempt(ctx, "failure") + source = Path.join(ctx.fleet, "shared-context/learning/fix-outcomes.jsonl") + + assert File.regular?(source), "producer must write the actual configured import feed" + assert stored(ctx.data) == [], "producer must not write raw rows into the learning ledger" + + refute File.exists?(Path.join(ctx.root, "direct-calls")), + "identified attempts must not use the direct recorder" + + assert [first, second] = read_rows(source) + assert first["attempt_contract"] == "fleet-attempt/1" + assert first["repo_relative_path"] == "sample" + assert EventId.valid?(first["event_id"]) + assert EventId.valid?(second["event_id"]) + refute first["event_id"] == second["event_id"] + assert {2, _signature} = LearningScheduler.ingest_fleet_outcomes(nil) + assert counts(ctx.data) == %{successes: 0, failures: 2, false_positives: 0, ignored: 0} + refute File.exists?(Path.join(ctx.root, "scan-calls")), "qualified failures require no rescan" + + for {mode, expected} <- [{"clean", "verified"}, {"adverse", "still_present"}] do + System.put_env("ADMISSION_SCAN_MODE", mode) + run_attempt(ctx, "success") + assert {0, _signature} = LearningScheduler.ingest_fleet_outcomes(nil) + row = stored(ctx.data) |> List.last() + assert row["admission_version"] == "fleet-attempt/1" + assert row["rescan_observation"]["binding"] == "unbound" + assert row["rescan_observation"]["result"] == expected + assert row["rescan_observation"]["attempt_event_id"] == row["event_id"] + + source_row = + read_lines(source) + |> Enum.find(&(Jason.decode!(&1)["event_id"] == row["event_id"])) + + assert is_binary(source_row) + assert row["producer_source"]["row_sha256"] == sha256(source_row) + assert row["rescan_observation"]["source_row_sha256"] == sha256(source_row) + assert EventId.valid?(row["rescan_observation"]["observation_id"]) + refute row["rescan_observation"]["observation_id"] == row["event_id"] + refute OutcomeTracker.qualified_outcome?(row) + end + + rows = stored(ctx.data) + assert length(rows) == 4 + assert counts(ctx.data) == %{successes: 0, failures: 2, false_positives: 0, ignored: 2} + assert length(read_lines(Path.join(ctx.root, "scan-calls"))) == 2 + assert length(read_lines(Path.join(ctx.root, "fix-calls"))) == 4 + refute File.exists?(Path.join(ctx.root, "direct-calls")) + assert Enum.all?(rows, &(&1["source_kind"] == "fleet_import")) + + source_bytes = File.read!(source) + month = Date.utc_today() |> Date.to_iso8601() |> String.slice(0, 7) + + for mirror <- [ctx.data, Path.join(ctx.root, "mirror")] do + assert File.read!(Path.join([mirror, "dispatch/fleet-outcomes", month <> ".jsonl"])) == + source_bytes + end + + receipts = Receipt.all(ctx.data) + assert length(receipts) == 4 + assert Enum.count(receipts, &(&1["verdict"] == "credited_failure")) == 2 + assert Enum.count(receipts, &(&1["verdict"] == "audit_only")) == 2 + + event_ids = read_rows(source) |> Enum.map(& &1["event_id"]) |> Enum.sort() + assert length(Enum.uniq(event_ids)) == 4 + assert Enum.all?(event_ids, &EventId.valid?/1) + assert Enum.sort(Enum.map(rows, & &1["event_id"])) == event_ids + assert Enum.sort(Enum.map(receipts, & &1["event_id"])) == event_ids + + starts = read_rows(Path.join(ctx.fleet, "shared-context/learning/fix-attempts.jsonl")) + assert Enum.sort(Enum.map(starts, & &1["event_id"])) == event_ids + + for receipt <- receipts do + assert receipt["source"]["kind"] == "fleet_import" + assert String.starts_with?(receipt["source"]["log"], "outcomes/") + line = String.to_integer(receipt["source"]["line"]) + bytes = read_lines(Path.join(ctx.data, receipt["source"]["log"])) |> Enum.at(line - 1) + assert receipt["proof_or_test_ref"]["row_sha256"] == sha256(bytes) + assert Jason.decode!(bytes)["event_id"] == receipt["event_id"] + assert receipt["parent_event_ids"] == [] + assert "rescan" in receipt["missing_evidence"] + check_receipt_contract!(ctx.root, receipt) + end + + # Replayed transport is an injected duplicate control, not setup needed to + # deliver the original events: all four were imported directly above. + before = snapshot(ctx.data) + File.write!(source, source_bytes, [:append]) + assert {0, signature} = LearningScheduler.ingest_fleet_outcomes(nil) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(signature) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert snapshot(ctx.data) == before + assert length(read_lines(Path.join(ctx.root, "scan-calls"))) == 2 + end + + defp run_attempt(ctx, mode) do + File.write!(Path.join(ctx.repos, "sample/needs-fix"), "fixture\n") + + {output, status} = + System.cmd("bash", [ctx.runner, "--limit", "1", "--parallel", "1"], + env: [{"ADMISSION_FIX_MODE", mode} | ctx.env], + stderr_to_stdout: true + ) + + assert status == 0, "fixture runner failed: #{output}" + end + + defp executable!(path, source) do + File.write!(path, source) + File.chmod!(path, 0o700) + end + + defp read_lines(path), do: path |> File.read!() |> String.split("\n", trim: true) + defp read_rows(path), do: path |> read_lines() |> Enum.map(&Jason.decode!/1) + + defp stored(data) do + Path.wildcard(Path.join(data, "outcomes/*.jsonl")) + |> Enum.sort() + |> Enum.flat_map(&read_rows/1) + end + + defp counts(data), do: OutcomeTracker.qualified_outcome_counts(stored(data)) + defp sha256(bytes), do: :crypto.hash(:sha256, bytes) |> Base.encode16(case: :lower) + + defp check_receipt_contract!(root, receipt) do + nickel = + System.get_env("NICKEL") || System.find_executable("nickel") || + raise("Nickel 1.11.0 is required to check the actual admission receipts") + + json = Path.join(root, "receipt-contract.json") + check = Path.join(root, "receipt-contract.ncl") + schema = Path.expand("schema/receipt.ncl") + File.write!(json, Jason.encode!(receipt)) + + File.write!( + check, + "let s = import #{Jason.encode!(schema)} in (import #{Jason.encode!(json)}) | s.Receipt\n" + ) + + {output, status} = + System.cmd(nickel, ["export", "--format", "json", check], stderr_to_stdout: true) + + assert status == 0, "actual admission receipt failed the existing Nickel contract: #{output}" + end + + defp snapshot(data) do + Path.wildcard(Path.join(data, "**/*")) + |> Enum.filter(&File.regular?/1) + |> Map.new(&{Path.relative_to(&1, data), File.read!(&1)}) + end +end + +result = ExUnit.run() +System.halt(if(result.failures == 0, do: 0, else: 1)) diff --git a/tests/outcome-verdict-test.sh b/tests/outcome-verdict-test.sh index 93dadf40..47001d8c 100755 --- a/tests/outcome-verdict-test.sh +++ b/tests/outcome-verdict-test.sh @@ -133,16 +133,18 @@ awk ' ' "$ROOT/scripts/dispatch-runner.sh" > "$TMP/extracted.sh" export REPOS_BASE="$TMP/repos" HYPATIA_OUTCOME_REPORT=off OUTCOME_FILE="$TMP/outcomes.jsonl" +OUTCOME_FILE_LOCAL="$OUTCOME_FILE" export OUTCOME_FILE_CENTRAL="$OUTCOME_FILE" # read by the sourced record_outcome +ATTEMPT_FILE="$TMP/starts.jsonl" RESCAN_REPOS_FILE="$TMP/rescan" : > "$RESCAN_REPOS_FILE" # shellcheck disable=SC1091 source "$TMP/extracted.sh" producer_id=018e4000-0000-8000-8000-000000000001 -record_outcome "PA009" "recipe-shell-quote-vars" "repo-a" "" verified 0 3 0 "$producer_id" -record_outcome "PA009" "recipe-shell-quote-vars" "repo-b" "" no_op 0 0 0 -record_outcome "PA009" "recipe-x" "repo-c" "" unverified 0 +record_outcome "PA009" "recipe-shell-quote-vars" "repo-a" "" verified 0 3 0 "$producer_id" repo-a +record_outcome "PA009" "recipe-shell-quote-vars" "repo-b" "" no_op 0 0 0 "$producer_id" repo-b +record_outcome "PA009" "recipe-x" "repo-c" "" unverified 0 NA NA "$producer_id" repo-c record_outcome "PA009" "recipe-license-hygiene" "repo-d" "" refused_license_policy check "verified row" '{"verdict":"verified","outcome":"success","exit_code":0,"before_hits":3,"after_hits":0}' \ @@ -156,6 +158,19 @@ check "outcome retains the producer's event id" "$producer_id" \ "$(sed -n 1p "$OUTCOME_FILE" | jq -r '.event_id')" check "policy refusal remains outside fix attempts" false \ "$(sed -n 4p "$OUTCOME_FILE" | jq 'has("event_id")')" +check "producer row carries v1 and actual relative target" 'fleet-attempt/1 repo-a' \ + "$(sed -n 1p "$OUTCOME_FILE" | jq -r '[.attempt_contract,.repo_relative_path] | join(" ")')" +missing_id_rc=0 +record_outcome PA009 recipe-x repo-x "" failed 7 1 1 > "$TMP/missing-id.log" 2>&1 || missing_id_rc=$? +check "an actual fix outcome without identity is refused" 1 "$missing_id_rc" +check "identity refusal appends no row" 4 "$(wc -l < "$OUTCOME_FILE" | tr -d ' ')" +for bad_path in '' . .. ../escape /absolute repo/../escape repo/./child repo//child repo/; do + invalid_path_rc=0 + record_outcome PA009 recipe-x repo-x "" failed 7 1 1 "$producer_id" "$bad_path" \ + > "$TMP/invalid-path.log" 2>&1 || invalid_path_rc=$? + check "unnormalized relative target '$bad_path' is refused" 1 "$invalid_path_rc" +done +check "target refusals append no rows" 4 "$(wc -l < "$OUTCOME_FILE" | tr -d ' ')" # --- 5. deprecated recipe ids --------------------------------------------- registry="$ROOT/scripts/fix-script-registry.json" @@ -263,90 +278,53 @@ for PARALLEL in 1 2; do "EXECUTED=$EXECUTED SUCCEEDED=$SUCCEEDED FAILED=$FAILED SKIPPED=$SKIPPED" done -# --- 10. the verdict goes to Hypatia when Hypatia knows the option (E0-02) - -# A stub `mix` on PATH records its arguments and answers `mix help -# hypatia.record_outcome` as the case needs. The mode is learned once, from the -# help text and never from an exit code: an older Hypatia ignores an option that -# it does not know, so a no_op call would be recorded as a success. The main -# loop is not run; it sits behind the quarantine (exit 78). +# --- 10. only policy refusals retain the legacy callback ----------------- +# Identified attempts are delivered solely through the fleet feed. A Mix stub +# records any forbidden independent admission even if a best-effort caller masks +# its exit status. Policy refusals are not attempts and keep their old callback. stub_dir="$TMP/stub-bin" mkdir -p "$stub_dir" "$TMP/hy-home" cat > "$stub_dir/mix" <<'STUB' #!/usr/bin/env bash -if [[ "$1" == "help" ]]; then - case "$STUB_HELP" in - verdict) echo "mix hypatia.record_outcome --recipe R --verdict verified|no_op|incomplete|unverified|failed"; exit 0 ;; - legacy) echo "mix hypatia.record_outcome --recipe R --repo X --file F --outcome O"; exit 0 ;; - *) echo "mix: cannot start" >&2; exit 3 ;; - esac -fi -echo "$*" >> "$STUB_LOG" -exit 0 +printf '%s\n' "$*" >> "$STUB_LOG" +exit "${STUB_RC:-0}" STUB chmod +x "$stub_dir/mix" - -# run_case [on|off]: runs the runner's own contract -# block in a subshell, as the runner does: detect first, stop if that fails, -# then record each verdict and one refusal. run_case() { - local mode="$1" report="${2:-on}" + local report="$1" callback_rc="${2:-0}" : > "$TMP/stub.log" ( - export PATH="$stub_dir:$PATH" STUB_HELP="$mode" STUB_LOG="$TMP/stub.log" + export PATH="$stub_dir:$PATH" STUB_LOG="$TMP/stub.log" STUB_RC="$callback_rc" export HYPATIA_HOME="$TMP/hy-home" HYPATIA_OUTCOME_REPORT="$report" REPOS_BASE="$TMP/repos" OUTCOME_FILE="$TMP/case-outcomes.jsonl" - OUTCOME_FILE_CENTRAL="$OUTCOME_FILE" - RESCAN_REPOS_FILE="$TMP/case-rescan" + OUTCOME_FILE_LOCAL="$OUTCOME_FILE" OUTCOME_FILE_CENTRAL="$OUTCOME_FILE" + ATTEMPT_FILE="$TMP/case-starts.jsonl" RESCAN_REPOS_FILE="$TMP/case-rescan" : > "$OUTCOME_FILE" : > "$RESCAN_REPOS_FILE" # shellcheck disable=SC1091 source "$TMP/extracted.sh" - rc=0 - hypatia_detect_verdict_mode || rc=$? - echo "detect_rc=$rc mode=${HYPATIA_VERDICT_MODE:-unset}" - if [[ "$rc" -eq 0 ]]; then - for v in verified no_op unverified incomplete failed; do - record_outcome PA009 recipe-x repo f "$v" 0 3 0 - done - record_outcome PA009 recipe-lic repo "" refused_license_policy - fi - ) > "$TMP/case.out" 2>&1 || true + for v in verified no_op unverified incomplete failed; do + record_outcome PA009 recipe-x repo f "$v" 0 3 0 "$producer_id" repo + done + printf 'attempt_calls=%s\n' "$(wc -l < "$STUB_LOG" | tr -d ' ')" + record_outcome PA009 recipe-lic repo "" refused_license_policy + ) > "$TMP/case.out" 2>&1 } -calls() { cat "$TMP/stub.log"; } - -run_case verdict -check "knows --verdict: mode is verdict" "detect_rc=0 mode=verdict" "$(grep '^detect_rc' "$TMP/case.out")" -check "knows --verdict: the mode is logged once" 1 "$(grep -c '^hypatia outcome mode: verdict' "$TMP/case.out")" -check "knows --verdict: 6 calls, one for each verdict and the refusal" 6 "$(calls | wc -l | tr -d ' ')" -for pair in verified:success no_op:success unverified:success incomplete:failure failed:failure; do - v="${pair%%:*}" o="${pair##*:}" - check "knows --verdict: $v is passed with outcome $o" \ - "hypatia.record_outcome --recipe recipe-x --repo repo --file f --outcome $o --verdict $v" \ - "$(calls | grep -- "--verdict $v\$" || true)" -done -check "knows --verdict: a refusal has no --verdict" \ - "hypatia.record_outcome --recipe recipe-lic --repo repo --file . --outcome false_positive" \ - "$(calls | grep -- 'recipe-lic' || true)" - -run_case legacy -check "older Hypatia: mode is legacy" "detect_rc=0 mode=legacy" "$(grep '^detect_rc' "$TMP/case.out")" -check "older Hypatia: the mode is logged once" 1 "$(grep -c '^hypatia outcome mode: legacy' "$TMP/case.out")" -check "older Hypatia: no --verdict in any call" 0 "$(calls | grep -c -- '--verdict' || true)" -check "older Hypatia: no call for no_op or unverified, 4 calls in all" 4 "$(calls | wc -l | tr -d ' ')" -check "older Hypatia: the calls are the calls of today" \ - "success failure failure false_positive" \ - "$(calls | sed -E 's/.*--outcome ([a-z_]+).*/\1/' | tr '\n' ' ' | sed 's/ $//')" - -run_case fail -check "help fails: detection fails" "detect_rc=1 mode=error" "$(grep '^detect_rc' "$TMP/case.out")" -check "help fails: a visible error says why" 1 "$(grep -c 'does not answer' "$TMP/case.out")" -check "help fails: no record call is made" 0 "$(calls | wc -l | tr -d ' ')" -check "the runner stops when detection fails (before any call)" 1 \ - "$(grep -c '^hypatia_detect_verdict_mode || exit 1$' "$ROOT/scripts/dispatch-runner.sh")" - -run_case fail off -check "reporting off: no help call and no record call" "detect_rc=0 mode=off 0" \ - "$(grep '^detect_rc' "$TMP/case.out") $(calls | wc -l | tr -d ' ')" +run_case on +check "reporting on: identified attempts make no independent recording call" attempt_calls=0 \ + "$(grep '^attempt_calls=' "$TMP/case.out")" +check "reporting on: the only callback is the policy refusal" \ + 'hypatia.record_outcome --recipe recipe-lic --repo repo --file . --outcome false_positive' \ + "$(cat "$TMP/stub.log")" +check "refusal callback never probes an attempt verdict mode" 0 \ + "$(grep -c '^help ' "$TMP/stub.log" || true)" +run_case off +check "reporting off: attempts are still delivered" 5 \ + "$(jq -s 'map(select(.attempt_contract == "fleet-attempt/1")) | length' "$TMP/case-outcomes.jsonl")" +check "reporting off: no callback" 0 "$(wc -l < "$TMP/stub.log" | tr -d ' ')" +run_case on 3 +check "refusal callback failure remains visible and best-effort" 1 \ + "$(grep -c 'record_outcome failed' "$TMP/case.out")" # --- 11. producer identity through the actual dispatch paths (E0-12) ------ # The existing harness copies the runner into a disposable tree and removes