From 565f075cf204f25f5b648547b8d8ae46fe1977ff Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Mon, 23 Nov 2026 09:51:39 +0000 Subject: [PATCH 1/4] fix(dispatch): preserve one event identity per attempt Mint the canonical Hypatia event ID before execution, persist the ruled start record, and retain that identity across outcome mirrors. Fail closed on identity or write errors, including parallel dispatch children. Add producer contract controls, actual-row importer witnesses, and an explicit decision packet for the still-unresolved dual-route credit case. Keep production quarantine and outcome qualification unchanged. --- docs/design/e0-12-outcome-route-decision.adoc | 195 ++++++++++ docs/operations/NS-02-producer-identity.adoc | 110 ++++++ scripts/dispatch-runner.sh | 114 +++++- scripts/tests/dispatch-paths.sh | 365 +++++++++++++++--- tests/hypatia-event-import-test.exs | 162 ++++++++ tests/hypatia-record-outcome-smoke.sh | 10 + tests/hypatia-route-counterexample.exs | 117 ++++++ tests/outcome-verdict-test.sh | 18 +- 8 files changed, 1014 insertions(+), 77 deletions(-) create mode 100644 docs/design/e0-12-outcome-route-decision.adoc create mode 100644 docs/operations/NS-02-producer-identity.adoc mode change 100644 => 100755 scripts/tests/dispatch-paths.sh create mode 100644 tests/hypatia-event-import-test.exs create mode 100644 tests/hypatia-route-counterexample.exs diff --git a/docs/design/e0-12-outcome-route-decision.adoc b/docs/design/e0-12-outcome-route-decision.adoc new file mode 100644 index 00000000..5471111d --- /dev/null +++ b/docs/design/e0-12-outcome-route-decision.adoc @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += E0-12: Outcome route and observation identity decision +: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. + +== Decision requested + +Adopt the existing trusted fleet importer as the sole admission path for a +producer-identified attempt. Retain Hypatia's rescan as evidence about that +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. + +== Authorities and measured sources + +The Hypatia sources below are pinned at +`d158aed87f76b93e4f291e995bef9f26559c7fb2`; the inspected fleet baseline is +`f1b14e2a352491ff7972f0dfd592bfbb28d2f32c`. + +* https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/docs/operations/e0-closeout/work-orders/E0-12-fleet-writes-event-id.adoc[E0-12] + requires one identity per attempt and equal identities on its mirrored rows. + Its stop condition says that two different outcome rows from an attempt + need identities and a design explaining their relationship. +* https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/docs/design/e0-receipt.adoc[E0 receipt design], + section 5.2 and accepted D4, names + `shared-context/learning/fix-attempts.jsonl` beside the fleet outcome feed. + Starts carry no evidence credit and do not consume an outcome's identity. +* https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/docs/operations/e0-closeout/work-orders/E0-31-event-id-task.adoc[E0-31] + records the newer owner choice of `mix hypatia.event_id` for the producer. +* https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/docs/operations/dispatch-runner-contract.adoc[The May dispatch-runner contract] + says the runner MUST call `mix hypatia.record_outcome` after a fix and retains + default rescan behavior. Its later verdict table makes failed/incomplete + calls qualified failures without a rescan. + +== S-01: Producer-to-learning admission + +[cols="2,3,3",options="header"] +|=== +|Path |Current behavior |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. +|Producer outcome +|The runner writes `$HYPATIA_DATA/outcomes/YYYY-MM.jsonl` and a central copy at +`$VERISIMDB_DATA/outcomes/YYYY-MM.jsonl` when those stores differ. +|Both copies retain one producer ID. These raw rows have a verdict but no +Hypatia `verification` field; their mere presence in a learning-store directory +does not qualify them. +|Direct recording callback +|The runner calls Mix from `$HYPATIA_HOME`. Hypatia resolves its data through +`HYPATIA_VERISIM_DATA_PATH`, not the runner's `HYPATIA_DATA` variable. +|The public task creates a newly identified `local_caller` or `local_rescan` +row. A failed/incomplete verdict can be qualified immediately. +|Fleet importer +|`LearningScheduler.ingest_fleet_outcomes/1` reads only +`$HYPATIA_FLEET_PATH/shared-context/learning/fix-outcomes.jsonl`. +|The trusted import preserves a valid producer ID and deduplicates persisted +`fleet_import_id` values. No current runner forwarding step joins these paths. +|=== + +The direct call also emits an echo marked `bot=hypatia`; the importer skips +that echo. The echo alone is not the duplicate-credit defect demonstrated +below. Its missing event ID is an additional existing gap against ruled R6; +this patch does not silently repair that separate path. + +The raw monthly file and the qualified consumer store must not be treated as +interchangeable. Code inspection indicates that publishing the same producer +ID into both raw and admitted rows within the receipt lookup's store can make +lookup depend on row order: +https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/lib/hypatia/receipt.ex[`Receipt.locate/2`] +returns the first matching event-ID row. This is an inference from the pinned +implementation, not an additional executed counterexample. +The selected route must separate transport mirrors from the canonical +learning ledger, not merely add a third write. + +== Executed counterexample + +The producer fixture uses the real canonical Mix generator and an inert +throwaway fixer. It emits two distinct failed attempts and their exact +primary/central copies. The wire witness transfers those bytes explicitly to +the importer and passes three checks: identity/mirror fidelity, start exclusion +and replay-safe import, and absence of implicit qualification for raw monthly +rows. This is compatibility evidence, not automatic delivery. + +`tests/hypatia-route-counterexample.exs` then takes one actual emitted failure, +calls the actual `Mix.Tasks.Hypatia.RecordOutcome` task with its labels, verifies +that the echo imports nothing, and explicitly appends the producer row to the +importer's feed. On the pinned Hypatia base it reports: + +[cols="2,1",options="header"] +|=== +|Measurement |Observed +|Actual emitted attempts selected |1 +|Qualified failure contributions after the direct task |1 +|Qualified failure contributions after adding the producer row |2 +|Distinct persisted event IDs |2 +|Receipts |2 +|Counterexample process exit |1 +|Automatic delivery exercised |No +|=== + +The negative result falsifies joining the current paths while leaving the +independent recording callback active. It is deliberately not converted into +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: + +[source,shell] +---- +# Set these to the two 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" +export DISPATCH_TEST_MIX_BIN="$(command -v mix)" +export DISPATCH_TEST_EVIDENCE_DIR="$(mktemp -d)" +export MIX_ENV=test +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. +---- + +== Recommended 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 + and central transport copies remain one attempt. Mirrors live outside the + canonical learning store and never create extra admitted trials. +. Retain rescan verification, but change the current mandatory recording + callback into a verification/evidence step for that admitted attempt. It + must not independently record another qualified attempt. Revise the May + callback contract explicitly as part of implementation. +. An attempt's ID, an observation's ID and a qualification revision's ID have + distinct meanings. Bind any separately stored rescan observation to the + attempt through a restricted, source-bound contract. A public caller's + syntax-valid UUID is insufficient provenance. +. Derive at most one current contribution per attempt. Multiple observations + are evidence for that contribution, not additional successes, failures or + qualified false positives. Preserve the existing separate false-positive + accounting. + Conflicting observations must use an explicit qualification/retraction rule + and preserve the history. E0-35's withdrawal work remains a dependency; + approval of this direction does not claim that machinery is implemented. +. Do not silently reuse `parent_event_ids` for an unruled relation. D7 defines + that field for receipt revision ancestry. The detailed observation/attempt + correlation and its relation to D7 must be written and reviewed before code + relies on them. +. Preserve legacy rows and uncertainty. Do not infer common attempt identity + from equal content, timestamps or recipe names: two identical attempts may + be distinct. Historical reconciliation needs its own evidence and receipts. + +The invariant can be stated without inventing new mathematics: count effective +attempt qualifications, not raw rows or observations. A single attempt may +contribute at most one effective qualified contribution -- success, failure +or qualified false positive -- or none, under the existing gate. Qualified +false positives retain their current separate accounting, as implemented by +https://github.com/hyperpolymath/hypatia/blob/d158aed87f76b93e4f291e995bef9f26559c7fb2/lib/outcome_tracker.ex[`OutcomeTracker.qualified_outcome_counts/1`]. +A later authorised revision changes that effective contribution without +erasing prior evidence. + +=== Alternative: make a new restricted direct recorder the sole ingress + +The direct route could instead become an idempotent trusted producer-admission +API, while fleet files become audit-only for those events. This preserves more +of the current invocation shape, but requires new admission/provenance and +offline/replay machinery and an explicit restriction on E0-11. Adding a public +`--event-id` option is not that machinery: `OutcomeTracker.record_outcome/5` +deliberately strips caller identity to prevent forged replay/receipt identity, +and the current qualification fold counts rows even if their IDs agree. + +The importer option reuses the existing persisted producer identity, source +hash and replay controls and is recommended. Neither option is activated by +the bounded NS-02 producer patch. + +== Work authorised by approval of the recommended direction + +Prepare the explicit contract amendment and correlated observation design; +implement one source-bound admission path in isolated changes; and demonstrate +the actual producer-to-consumer flow with fault, replay, mirror, conflict and +forged-identity controls. Preserve the existing qualification criteria and +quarantine while those gates are developed. E0 acceptance, production +activation and any Kautz qualification remain separate decisions supported by +their own evidence. diff --git a/docs/operations/NS-02-producer-identity.adoc b/docs/operations/NS-02-producer-identity.adoc new file mode 100644 index 00000000..3b2c984f --- /dev/null +++ b/docs/operations/NS-02-producer-identity.adoc @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 += NS-02: Bounded producer identity evidence +: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. + +Fleet base: `f1b14e2a352491ff7972f0dfd592bfbb28d2f32c`. +Hypatia generator/importer base: `d158aed87f76b93e4f291e995bef9f26559c7fb2`. +E0-11 and E0-31 were confirmed in that Hypatia ancestry, at `6de3764` +(PR #1165) and `00ee725` (PR #1213). The existing receipt design fixes the +start record; the later E0-31 ruling fixes the Mix tooling choice. + +== Behavior + +An executable fix attempt calls `mix hypatia.event_id` once and checks the +canonical final output line. Nonzero generator exit is refused even if stdout +contains a plausible ID. Final-line checking follows the task's documented +handling of first-run compile chatter; it is validation, not a new generator. + +Before either fix-script or RRA execution, the producer appends the exact +sorted six-field start to +`$FLEET_ROOT/shared-context/learning/fix-attempts.jsonl`. Failed identity or +start persistence prevents the fix. An interrupted attempt leaves a start +without an outcome. + +The existing primary and central outcome destinations are preserved. Their +copies carry the same producer ID and serialized bytes. Primary failure +prevents later mirror/direct-report calls; mirror failure retains the primary +row and reports failure. New infrastructure failures propagate from parallel +children to the parent through a narrow marker alongside the existing tally; +success counters are added after successful outcome persistence. + +The production exit 78 before manifest processing and the complete licence +refusal branch remain unchanged. A policy refusal does not become a fix +attempt and keeps its existing row shape. No public caller may supply trusted +receipt identity through a new CLI flag. + +== Failing-before evidence and correction + +* Against unchanged producer source, the new row-identity assertion found + `null`: 62 existing checks passed and the new assertion failed. +* The whole-runner fixture showed the fixer executing without its required + start record. +* Independent review found that the old parallel drain discarded the new + infrastructure failure return. A failing-before control showed two failed + generator jobs, `FAILED=2`, and overall exit zero. The explicit error marker + now makes that case fail visibly. +* The existing smoke test assumed Mix was present in two no-call cases. Its + inert presence stub makes those assertions independent of the host without + allowing a real Mix call or changing production behavior. + +== Completed checks + +[cols="3,2",options="header"] +|=== +|Command / scope |Result +|`bash tests/outcome-verdict-test.sh` +|63 outcome checks pass; it also invokes the 112-check whole-runner fixture. +|`bash tests/automation-quarantine-test.sh` +|Seven blocked entrypoints and the no-publication/state-mutation assertion pass. +|`bash tests/hypatia-record-outcome-smoke.sh` +|5 checks pass. +|`bash scripts/tests/dispatch-paths.sh` with the actual canonical Mix generator +|112 checks pass, including serial and parallel generator/start/primary/mirror failures. +|`bash -n` on the four changed shell files; `git diff --check` +|Pass. ShellCheck was unavailable locally. +|`tests/hypatia-event-import-test.exs`, run by `MIX_ENV=test mix run --no-start` from Hypatia +|3 checks pass using actual emitted rows and an explicit test transfer. +|`mix test test/learning_scheduler_test.exs test/event_id_test.exs test/mix_tasks/event_id_test.exs --seed 0` from Hypatia +|56 tests pass, zero failures, covering the existing importer and event-ID contracts. +|`tests/hypatia-route-counterexample.exs`, same isolated runtime +|Exit 1: one actual attempt yields two qualified failures and two receipts after direct recording plus explicit import. This unresolved integration failure remains visible. +|=== + +The real generator and consumer witness used Elixir 1.19.4 / OTP 27.3.4.19, +matching Hypatia's pin. The fixture runs only a disposable copy of the runner, +using the pre-existing quarantine test seam and inert temporary fixes. The +unmodified production entrypoint is separately required to return 78. No +test makes a production exception or enables dispatch through an environment +switch. + +The harness can preserve actual rows under `DISPATCH_TEST_EVIDENCE_DIR`: +`success-starts.jsonl`, `success-primary.jsonl`, `success-central.jsonl`, and +the corresponding three `failure-*` files. Each primary/start pair contains +two distinct attempts; each central file is the exact second outcome. Set +`DISPATCH_TEST_HYPATIA_HOME` to the pinned Hypatia checkout and +`DISPATCH_TEST_MIX_BIN` to its configured Mix executable to use the canonical +generator. Omitting those selects the deterministic test stub, never a +production fallback generator. + +The companion decision packet contains the exact cross-repository commands. +The importer witness proves ID and receipt fidelity, mirror/replay +deduplication and start exclusion. Its deliberate copy into the import feed +does not demonstrate automatic delivery. + +== Claim boundary + +This patch establishes local producer identity and tested wire compatibility. +It does not establish power-loss durability, a multi-file atomic transaction, +exactly-once neural parameter updates, corpus quality, held-out usefulness, +live deployment, full E0-12/E0 acceptance or a higher Kautz type. + +The current monthly-log routes and direct recording callback remain unchanged. +Do not add forwarding without settling the decision packet: the reproduced +counterexample shows how that naive connection multiplies evidence. The new +identity patch does not justify relaxing the existing quarantine. diff --git a/scripts/dispatch-runner.sh b/scripts/dispatch-runner.sh index 3be4e087..ec8e5be6 100755 --- a/scripts/dispatch-runner.sh +++ b/scripts/dispatch-runner.sh @@ -121,6 +121,15 @@ fold_counts() { esac done < "$PARALLEL_TMPDIR/tally" } + +# Background wait calls do not retain each child's status. Mark a failed +# identity/start/outcome contract explicitly so the parent also fails closed. +mark_dispatch_error() { + count FAILED + if [[ "${IN_JOB:-0}" == 1 ]]; then + printf '%s\n' failed >> "$PARALLEL_TMPDIR/errors" + fi +} # --- end run counters --- # --- Parse arguments --- @@ -174,6 +183,8 @@ echo "" 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")" +# E0 receipt design, section 5.2: starts are separate from every outcome log. +ATTEMPT_FILE="${FLEET_ROOT}/shared-context/learning/fix-attempts.jsonl" # Repos that received at least one successful fix this run. Appended by # record_outcome (file, not a variable: execute_entry may run in @@ -205,9 +216,9 @@ fi # Configuration via env: # HYPATIA_HOME path to the hypatia checkout (defaults to # $REPOS_BASE/hypatia) -# HYPATIA_OUTCOME_REPORT set to "off" to disable mix calls (e.g. a -# CI runner without Elixir/mix on PATH); -# defaults to "on" +# 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_BATCH_ID when set, exit-2 hints suggest # `mix hypatia.rollback_batch $HYPATIA_BATCH_ID` # @@ -226,7 +237,7 @@ HYPATIA_BATCH_ID="${HYPATIA_BATCH_ID:-}" # 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 calls are made at all (reporting off, no checkout, no mix). +# 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() { @@ -315,7 +326,46 @@ hypatia_record_outcome() { return "$rc" } -# record_outcome [exit before after] +# 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 + if [[ ! -d "$HYPATIA_HOME" ]]; then + echo "ERROR: event id unavailable: HYPATIA_HOME is not a directory: $HYPATIA_HOME" >&2 + return 1 + fi + if ! command -v mix &>/dev/null; then + echo "ERROR: event id unavailable: mix is not on PATH" >&2 + return 1 + fi + generated=$(cd "$HYPATIA_HOME" && mix hypatia.event_id) || rc=$? + if [[ "$rc" -ne 0 ]]; then + echo "ERROR: event id generation failed: mix hypatia.event_id exited $rc" >&2 + return 1 + fi + # The task documents compilation messages before its final id line. Never + # accept trailing output, a malformed id, or output from a failed command. + event_id="${generated##*$'\n'}" + 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}$ ]]; then + echo "ERROR: event id generation returned no valid ADR-008 v8 profile T id" >&2 + return 1 + fi + if ! start_json=$(jq -cnS --arg event_id "$event_id" --arg recipe_id "$recipe_id" --arg repo "$repo" \ + '{chain_version: "e0-receipt/1", event_id: $event_id, kind: "start", + producer: "dispatch-runner", recipe_id: $recipe_id, repo: $repo}'); then + echo "ERROR: could not encode attempt start for event_id=$event_id" >&2 + return 1 + fi + if ! mkdir -p "$(dirname "$ATTEMPT_FILE")" || ! printf '%s\n' "$start_json" >> "$ATTEMPT_FILE"; then + echo "ERROR: could not append attempt start for event_id=$event_id to $ATTEMPT_FILE" >&2 + return 1 + fi + printf '%s\n' "$event_id" +} + +# record_outcome [exit before after event_id] # # 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 @@ -329,6 +379,9 @@ record_outcome() { local exit_code="${6:-}" local before="${7:-NA}" local after="${8:-NA}" + # 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 bot="dispatch-runner" local outcome @@ -341,7 +394,7 @@ record_outcome() { ts=$(date -u +"%Y-%m-%dT%H:%M:%SZ") local json - json=$(jq -cn \ + if ! json=$(jq -cn \ --arg pid "$pattern_id" \ --arg rid "$recipe_id" \ --arg repo "$repo" \ @@ -353,21 +406,31 @@ record_outcome() { --arg after "$after" \ --arg ts "$ts" \ --arg bot "$bot" \ + --arg event_id "$event_id" \ '{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}') + timestamp: $ts, bot: $bot} + + (if $event_id == "" then {} else {event_id: $event_id} end)'); then + echo "ERROR: could not encode outcome for $repo/$recipe_id event_id=$event_id" >&2 + return 1 + fi - echo "$json" >> "$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 # 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 - mkdir -p "$(dirname "$OUTCOME_FILE_CENTRAL")" - echo "$json" >> "$OUTCOME_FILE_CENTRAL" + 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 @@ -543,9 +606,15 @@ execute_entry() { tmp_finding=$(mktemp /tmp/dispatch-finding-XXXXXX.json) echo "$entry" > "$tmp_finding" - local before after rc verdict + local before after rc verdict event_id if [[ "$PARALLEL" -gt 1 ]]; then repo_lock "$PARALLEL_TMPDIR" "$repo_path"; fi before=$(recipe_check_count "$FLEET_SCRIPTS/$fix_script" "$repo_path") + if ! event_id=$(begin_attempt "$recipe_id" "$repo"); then + if [[ "$PARALLEL" -gt 1 ]]; then repo_unlock; fi + rm -f "$tmp_finding" + mark_dispatch_error + return 1 + fi echo " Running: $fix_script $repo_path $tmp_finding" rc=0 @@ -556,17 +625,27 @@ 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" || { + rm -f "$tmp_finding" + count EXECUTED + mark_dispatch_error + return 1 + } if [[ "$verdict" == failed || "$verdict" == incomplete ]]; then count FAILED else count SUCCEEDED fi - record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" "$before" "$after" rm -f "$tmp_finding" elif command -v "$RRA_BIN" &>/dev/null; then # Use robot-repo-automaton fix command + local event_id + if ! event_id=$(begin_attempt "$recipe_id" "$repo"); then + mark_dispatch_error + return 1 + fi echo " Running: $RRA_BIN fix --repo $repo_path --commit" # robot-repo-automaton exposes no predicate, so a clean exit # is recorded as unverified, never as a confirmed fix. @@ -576,12 +655,16 @@ 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" || { + count EXECUTED + mark_dispatch_error + return 1 + } if [[ "$verdict" == failed ]]; then count FAILED else count SUCCEEDED fi - record_outcome "$pattern_id" "$recipe_id" "$repo" "" "$verdict" "$rc" else echo " SKIP: No fix mechanism available (no fix_script, no $RRA_BIN)" count SKIPPED @@ -722,6 +805,11 @@ done < "$MANIFEST_PATH" if [[ "$PARALLEL" -gt 1 ]]; then wait fold_counts + if [[ -s "$PARALLEL_TMPDIR/errors" ]]; then + echo "ERROR: a dispatch job could not commit its attempt identity or outcome" >&2 + rm -rf "$PARALLEL_TMPDIR" + exit 1 + fi fi rm -rf "$PARALLEL_TMPDIR" 2>/dev/null || true diff --git a/scripts/tests/dispatch-paths.sh b/scripts/tests/dispatch-paths.sh old mode 100644 new mode 100755 index f5adc9f0..cbd0d098 --- a/scripts/tests/dispatch-paths.sh +++ b/scripts/tests/dispatch-paths.sh @@ -1,94 +1,333 @@ #!/usr/bin/env bash # SPDX-License-Identifier: MPL-2.0 -# Exercise dispatch orchestration with an inert fix executable and isolated data. +# 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. set -euo pipefail fleet_test_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" fixture="$(mktemp -d)" trap 'rm -rf "$fixture"' EXIT -mkdir -p "$fixture/repos/sample" "$fixture/checkout/scripts" "$fixture/primary/dispatch" +mkdir -p "$fixture/repos/sample" "$fixture/checkout/scripts/lib" "$fixture/primary/dispatch" \ + "$fixture/bin" "$fixture/hypatia" cp "$fleet_test_root/scripts/repo-path-overrides.json" "$fixture/checkout/scripts/" -# dispatch-runner sources its outcome-verdict library from beside itself. -mkdir -p "$fixture/checkout/scripts/lib" 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" +manifest="$fixture/primary/dispatch/pending.jsonl" +canonical_mix="${DISPATCH_TEST_MIX_BIN:-$(command -v mix || true)}" +pass=0 +check() { + local label="$1"; shift + if ! "$@" > "$fixture/assertion-result" 2>&1; then + echo "FAIL: $label" >&2 + cat "$fixture/assertion-result" >&2 + [[ ! -f "$fixture/result" ]] || cat "$fixture/result" >&2 + exit 1 + fi + pass=$((pass + 1)) + printf 'PASS: %s\n' "$label" +} -# While dispatch is quarantined (docs/AUTOMATION-QUARANTINE.adoc), the -# production runner must refuse every call. The path/outcome contracts -# below run against a test-only copy with the interlock removed, inside the -# throwaway fixture; that copy is unreachable from any production entry point. +# While dispatch is quarantined, the production runner refuses every call. Only +# this disposable copy has exactly the BLOCKED printf and following exit removed; +# it is unreachable from production entry points and uses only fixture adapters. real_runner="$fleet_test_root/scripts/dispatch-runner.sh" seam_runner="$fixture/checkout/scripts/dispatch-runner.sh" interlock_msg='BLOCKED: repository directive enforcement is not qualified' -if ! grep -qF "$interlock_msg" "$real_runner"; then - echo "FAIL: dispatch-runner.sh no longer carries the quarantine interlock;" >&2 - echo " update this test to run the real runner and drop the seam." >&2 - exit 1 -fi -# Strip exactly the interlock: the BLOCKED printf and the exit 78 after it. +check 'production interlock exists' grep -qF "$interlock_msg" "$real_runner" awk -v msg="$interlock_msg" ' skip_exit && /^exit 78$/ { skip_exit = 0; next } index($0, msg) && /^printf / { skip_exit = 1; next } { print } ' "$real_runner" > "$seam_runner" +check 'test copy removed only the two interlock lines' test \ + "$(( $(wc -l < "$real_runner") - $(wc -l < "$seam_runner") ))" -eq 2 if grep -qF "$interlock_msg" "$seam_runner" || cmp -s "$real_runner" "$seam_runner"; then - echo "FAIL: could not build the test-only seam runner" >&2 + echo 'FAIL: could not build the test-only seam runner' >&2 exit 1 fi -# Run one dispatch against the fixture with the given runner and central store. +cat > "$fixture/bin/mix" <<'STUB' +#!/usr/bin/env bash +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.event_id) ;; + *) echo 'unexpected mix arguments' >&2; exit 98 ;; +esac +fixture_id=018e4000-0000-8000-8000-000000000001 +case "$FIXTURE_GENERATOR_MODE" in + fail) echo "$fixture_id"; exit 3 ;; + empty) exit 0 ;; + bad) echo 'not-an-event-id'; exit 0 ;; + v4) echo "${fixture_id:0:14}4${fixture_id:15}"; exit 0 ;; + variant) echo "${fixture_id:0:19}c${fixture_id:20}"; exit 0 ;; + uppercase) echo "${fixture_id^^}"; exit 0 ;; + trailing) printf '%s\ntrailing noise\n' "$fixture_id"; exit 0 ;; + chatter) echo 'Compiling fixture source' ;; +esac +if [[ -n "${DISPATCH_TEST_HYPATIA_HOME:-}" ]]; then + exec "$DISPATCH_TEST_MIX_BIN" hypatia.event_id +fi +# These are fixed wire fixtures, not a replacement event-id generator. The lock +# only lets two background runner jobs consume distinct fixture rows safely. +{ + flock 9 + head -n 1 "$FIXTURE_ROOT/ids" + tail -n +2 "$FIXTURE_ROOT/ids" > "$FIXTURE_ROOT/ids.next" + mv "$FIXTURE_ROOT/ids.next" "$FIXTURE_ROOT/ids" +} 9> "$FIXTURE_ROOT/ids.lock" +STUB +cat > "$fixture/checkout/scripts/fix-fixture.sh" <<'STUB' +#!/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 +# This observation is made by the fixer, before it changes the fixture repo. +jq -e '.kind == "start" and .producer == "dispatch-runner"' \ + "$FIXTURE_ROOT/checkout/shared-context/learning/fix-attempts.jsonl" >/dev/null +printf '%s\n' started >> "$FIXTURE_ROOT/fix-calls" +case "$FIXTURE_FIX_MODE" in + interrupt) kill -TERM "$PPID"; exit 0 ;; + fail) exit 7 ;; +esac +rm -f "$1/needs-fix" +STUB +cat > "$fixture/bin/rra" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +[[ "$1" == fix && "$2" == --repo && "$4" == --commit ]] +exec "$FIXTURE_ROOT/checkout/scripts/fix-fixture.sh" "$3" +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" + : > "$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 + runner_args=() + hypatia_home="${DISPATCH_TEST_HYPATIA_HOME:-$fixture/hypatia}" + runner_path="$fixture/bin:$PATH" + rra_bin="$fixture/bin/rra" +} invoke_runner() { - local runner="$1" central="$2" - env -u GITHUB_TOKEN -u FLEET_DISPATCH_TOKEN \ - FLEET_ROOT="$fixture/checkout" REPOS_BASE="$fixture/repos" \ - HYPATIA_DATA="$fixture/primary" VERISIMDB_DATA="$central" \ - HYPATIA_OUTCOME_REPORT=off KIN_DIR="$fixture/kin" RRA_BIN=/bin/true \ - bash "$runner" --limit 1 + local runner="$1" store="$2" + env -u GITHUB_TOKEN -u FLEET_DISPATCH_TOKEN -u BASH_ENV -u ENV \ + 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" \ + KIN_DIR="$fixture/kin" RRA_BIN="$rra_bin" FIXTURE_ROOT="$fixture" \ + FIXTURE_GENERATOR_MODE="$generator_mode" FIXTURE_FIX_MODE="$fix_mode" \ + DISPATCH_TEST_MIX_BIN="$canonical_mix" \ + bash "$runner" --limit "$limit" --parallel "$parallel" "${runner_args[@]}" } - -# Run one dispatch through the test-only seam runner (interlock removed). -run_dispatch() { - invoke_runner "$seam_runner" "$1" +run_dispatch() { invoke_runner "$seam_runner" "${1:-$fixture/central}" > "$fixture/result" 2>&1; } +expect_failure() { + local label="$1" rc=0 + run_dispatch || rc=$? + check "$label: runner refuses" test "$rc" -ne 0 +} +no_fix_or_outcome() { + check "$1: fixer was not called" test ! -s "$fixture/fix-calls" + check "$1: no outcome was written" test ! -s "$primary" +} +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 "$primary" "$DISPATCH_TEST_EVIDENCE_DIR/$1-primary.jsonl" + cp "$central" "$DISPATCH_TEST_EVIDENCE_DIR/$1-central.jsonl" } -manifest="$fixture/primary/dispatch/pending.jsonl" -printf '%s\n' '{"repo":"sample","tier":"eliminate","strategy":"auto_execute","pattern_id":"fixture","recipe_id":"none","auto_fixable":true}' > "$manifest" - -# The production runner refuses with exit 78 and writes no outcome state. -set +e -quarantine_err="$(invoke_runner "$real_runner" "$fixture/primary/." 2>&1 >/dev/null)" -quarantine_rc=$? -set -e -test "$quarantine_rc" -eq 78 -grep -qF "$interlock_msg" <<<"$quarantine_err" -test ! -e "$fixture/primary/outcomes" -# Planted control: the seam copy must NOT be refused, or the assertion above -# could never distinguish a quarantined runner from an unquarantined one. -set +e -invoke_runner "$seam_runner" "$fixture/scratch-control" >/dev/null 2>&1 -control_rc=$? -set -e -test "$control_rc" -ne 78 -rm -rf "$fixture/primary/outcomes" "$fixture/scratch-control" "$fixture/kin" -# Default primary and central stores are the same; exactly one JSONL record. +reset_fixture +quarantine_rc=0 +invoke_runner "$real_runner" "$fixture/primary/." > "$fixture/result" 2>&1 || quarantine_rc=$? +check 'production runner exits 78 before manifest work' test "$quarantine_rc" -eq 78 +check 'quarantine calls no generator' test ! -s "$fixture/mix-calls" +check 'quarantine writes no attempt or outcome state' test ! -e "$fixture/checkout/shared-context" +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/." -month="$(date -u +%Y-%m)" -test "$(wc -l < "$fixture/primary/outcomes/$month.jsonl")" -eq 1 -jq -e '.outcome == "success"' "$fixture/primary/outcomes/$month.jsonl" >/dev/null -# Separate stores both receive one copy of this new outcome. -run_dispatch "$fixture/central" -test "$(wc -l < "$fixture/primary/outcomes/$month.jsonl")" -eq 2 -test "$(wc -l < "$fixture/central/outcomes/$month.jsonl")" -eq 1 +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 \ + 'keys == ["chain_version","event_id","kind","producer","recipe_id","repo"] and .chain_version == "e0-receipt/1" and .kind == "start" and .producer == "dispatch-runner" and .recipe_id == "recipe-fixture" and .repo == "sample"' "$starts" +check 'start uses canonical compact sorted JSON' test "$(cat "$starts")" "=" "$(jq -cS . "$starts")" +check 'event id has ADR-008 v8 text and variant' jq -e \ + '.event_id | test("^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")' "$starts" +check 'first start and outcome have one id' test "$(jq -r .event_id "$starts")" "=" "$(jq -r .event_id "$primary")" +touch "$fixture/repos/sample/needs-fix" +run_dispatch +check 'each identical attempt minted exactly once' test "$(grep -c '^hypatia.event_id$' "$fixture/mix-calls")" -eq 2 +check 'identical attempts have distinct event ids' jq -se 'map(.event_id) | length == 2 and (unique | length == 2)' "$primary" +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 +retain_rows success + +reset_fixture +fix_mode=fail +run_dispatch "$fixture/primary/." +run_dispatch +check 'failed fix retains its producer id and exit code' jq -e '.verdict == "failed" and .exit_code == 7 and (.event_id | type == "string")' "$primary" +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")" +retain_rows failure + +reset_fixture +fix_mode=interrupt +expect_failure 'interrupted after start' +check 'interrupted attempt leaves exactly one start' test "$(wc -l < "$starts")" -eq 1 +check 'interrupted fixer observed its durable start' test "$(wc -l < "$fixture/fix-calls")" -eq 1 +check 'interrupted attempt has no outcome' test ! -s "$primary" + +for mode in fail empty bad v4 variant uppercase trailing; do + reset_fixture + generator_mode="$mode" + expect_failure "generator $mode" + no_fix_or_outcome "generator $mode" + check "generator $mode: no start was written" test ! -e "$starts" + check "generator $mode: diagnostic is visible" grep -qi 'event.id' "$fixture/result" +done +reset_fixture +generator_mode=chatter +run_dispatch +check 'compile chatter is excluded from the id' jq -e '.event_id | test("^[0-9a-f-]{36}$")' "$primary" +reset_fixture +hypatia_home="$fixture/missing-hypatia" +expect_failure 'missing Hypatia checkout' +no_fix_or_outcome 'missing Hypatia checkout' +mkdir "$fixture/no-mix" +for command_name in bash dirname wc tr date mkdir mktemp jq realpath sed grep rm; do + ln -s "$(command -v "$command_name")" "$fixture/no-mix/$command_name" +done +reset_fixture +runner_path="$fixture/no-mix" +expect_failure 'missing mix executable' +no_fix_or_outcome 'missing mix executable' + +for failure in directory append; do + reset_fixture + mkdir -p "$fixture/checkout/shared-context" + if [[ "$failure" == directory ]]; then + : > "$fixture/checkout/shared-context/learning" + else + mkdir -p "$starts" + fi + expect_failure "start $failure failure" + no_fix_or_outcome "start $failure failure" +done +for failure in primary central; do + reset_fixture + report_mode=on + if [[ "$failure" == primary ]]; then mkdir -p "$primary"; else mkdir -p "$central"; fi + 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 +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 + reset_fixture + limit=0 parallel=2 + cat "$manifest" > "$fixture/entry" + cat "$fixture/entry" >> "$manifest" + case "$failure" in + generator) generator_mode=fail ;; + start) mkdir -p "$starts" ;; + primary) mkdir -p "$primary" ;; + central) mkdir -p "$central" ;; + esac + expect_failure "parallel $failure failure" + if [[ "$failure" == generator || "$failure" == start ]]; then + no_fix_or_outcome "parallel $failure failure" + fi +done + +# Both executable mechanisms require the same pre-execution identity contract. +reset_fixture +jq -c 'del(.fix_script)' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +run_dispatch +check 'RRA attempt keeps start identity' test "$(jq -r .event_id "$starts")" "=" "$(jq -r .event_id "$primary")" +check 'RRA remains unverified without a predicate' jq -e '.verdict == "unverified"' "$primary" +reset_fixture +generator_mode=fail +jq -c 'del(.fix_script)' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +expect_failure 'RRA generator failure' +no_fix_or_outcome 'RRA generator failure' + +reset_fixture +generator_mode=fail +runner_args=(--dry-run) +run_dispatch +no_fix_or_outcome 'fixture dry run' +check 'fixture dry run mints no id' test ! -s "$fixture/mix-calls" +reset_fixture +generator_mode=fail rra_bin="$fixture/no-rra" +jq -c 'del(.fix_script)' "$manifest" > "$fixture/entry" +mv "$fixture/entry" "$manifest" +run_dispatch +no_fix_or_outcome 'no executable fix mechanism' +check 'no executable fix mechanism mints no id' test ! -s "$fixture/mix-calls" + +reset_fixture +limit=0 parallel=2 +cat "$manifest" > "$fixture/entry" +cat "$fixture/entry" >> "$manifest" +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" + +# No attempted execution means no new attempt id. Preserve the licence refusal. +reset_fixture +generator_mode=fail +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 never calls the fixer' test ! -s "$fixture/fix-calls" +check 'licence refusal creates no start' test ! -e "$starts" + +reset_fixture +generator_mode=fail printf '%s\n' '{"repo":"sample","tier":"control","strategy":"review","pattern_id":"review-fixture"}' > "$manifest" -run_dispatch "$fixture/central" -test -s "$fixture/checkout/shared-context/findings/pending/sample--review-fixture.json" +run_dispatch +check 'review still writes its finding' test -s "$fixture/checkout/shared-context/findings/pending/sample--review-fixture.json" printf '%s\n' '{"repo":"sample","tier":"control","strategy":"report_only","pattern_id":"advisory-fixture"}' > "$manifest" -run_dispatch "$fixture/central" -test -s "$fixture/checkout/shared-context/advisories/$month.jsonl" -test ! -d "$fixture/repos/gitbot-fleet" - -# Legacy aliases remain fallbacks; direct checkouts still take precedence. +run_dispatch +check 'report-only still writes its advisory' test -s "$fixture/checkout/shared-context/advisories/$month.jsonl" +check 'review and report-only mint no ids' test ! -s "$fixture/mix-calls" +check 'paths stay inside configured checkout' test ! -d "$fixture/repos/gitbot-fleet" mkdir -p "$fixture/repos/developer-ecosystem/julia-ecosystem/packages/Axiom.jl" printf '%s\n' '{"repo":"Axiom.jl","tier":"control","strategy":"review","pattern_id":"alias-fixture"}' > "$manifest" -run_dispatch "$fixture/central" -test -s "$fixture/checkout/shared-context/findings/pending/Axiom.jl--alias-fixture.json" -echo 'Dispatch path and outcome contracts passed' +run_dispatch +check 'legacy repository path alias remains a fallback' test -s "$fixture/checkout/shared-context/findings/pending/Axiom.jl--alias-fixture.json" +printf 'Dispatch path and producer identity contracts: %s passed\n' "$pass" diff --git a/tests/hypatia-event-import-test.exs b/tests/hypatia-event-import-test.exs new file mode 100644 index 00000000..187cdaef --- /dev/null +++ b/tests/hypatia-event-import-test.exs @@ -0,0 +1,162 @@ +# SPDX-License-Identifier: MPL-2.0 +# Explicit wire-compatibility witness. Run from the pinned Hypatia checkout: +# DISPATCH_TEST_EVIDENCE_DIR=/absolute/emitted-fixture MIX_ENV=test \ +# mix run --no-start /absolute/gitbot-fleet/tests/hypatia-event-import-test.exs +# The fixture files must come from scripts/tests/dispatch-paths.sh. Copying +# their bytes into the import path below is a test transfer, not delivery code. + +unless Mix.env() == :test, do: raise("run this witness with MIX_ENV=test") + +if Process.whereis(Hypatia.Supervisor), + do: raise("run this witness with --no-start; the Hypatia application must be stopped") + +{:ok, _} = Application.ensure_all_started(:telemetry) +ExUnit.start(autorun: false, seed: 0) + +defmodule Fleet.HypatiaEventImportTest do + use ExUnit.Case, async: false + + alias Hypatia.{EventId, LearningScheduler, OutcomeTracker, Receipt} + + @moduletag capture_log: true + + setup do + evidence = System.fetch_env!("DISPATCH_TEST_EVIDENCE_DIR") |> Path.expand() + root = Path.join(System.tmp_dir!(), "fleet-wire-#{System.unique_integer([:positive])}") + data = Path.join(root, "data") + fleet = Path.join(root, "fleet") + keys = [:verisimdb_data_path, :annealing_state_path, :fleet_path] + original = Map.new(keys, &{&1, Application.fetch_env(:hypatia, &1)}) + + on_exit(fn -> + for {key, value} <- original do + case value do + {:ok, previous} -> Application.put_env(:hypatia, key, previous) + :error -> Application.delete_env(:hypatia, key) + end + end + + File.rm_rf!(root) + end) + + File.mkdir_p!(Path.join(data, "outcomes")) + File.mkdir_p!(Path.join(fleet, "shared-context/learning")) + Application.put_env(:hypatia, :verisimdb_data_path, data) + Application.put_env(:hypatia, :annealing_state_path, Path.join(data, "annealing")) + Application.put_env(:hypatia, :fleet_path, fleet) + + primary = File.read!(Path.join(evidence, "failure-primary.jsonl")) + central = File.read!(Path.join(evidence, "failure-central.jsonl")) + starts = File.read!(Path.join(evidence, "failure-starts.jsonl")) + + for bytes <- [primary, central, starts], do: assert(String.ends_with?(bytes, "\n")) + + %{ + data: data, + fleet: fleet, + source: Path.join(fleet, "shared-context/learning/fix-outcomes.jsonl"), + primary: primary, + central: central, + starts: starts + } + end + + test "actual producer rows retain two distinct attempt identities and their mirror", ctx do + assert [first, second] = decode(ctx.primary) + assert [mirrored] = decode(ctx.central) + assert [first_start, second_start] = decode(ctx.starts) + assert first["verdict"] == "failed" + assert second["verdict"] == "failed" + assert first["outcome"] == "failure" + assert second["outcome"] == "failure" + assert first["recipe_id"] not in [nil, "", "none", "null"] + assert first["recipe_id"] == second["recipe_id"] + assert EventId.valid?(first["event_id"]) + assert EventId.valid?(second["event_id"]) + refute first["event_id"] == second["event_id"] + assert first_start["kind"] == "start" + assert second_start["kind"] == "start" + assert first_start["event_id"] == first["event_id"] + assert second_start["event_id"] == second["event_id"] + assert mirrored == second + assert List.last(lines(ctx.primary)) == hd(lines(ctx.central)) + end + + test "explicit transfer imports attempts once, skips starts, and preserves receipt identity", + ctx do + File.write!(Path.join(ctx.fleet, "shared-context/learning/fix-attempts.jsonl"), ctx.starts) + assert {0, nil} = LearningScheduler.ingest_fleet_outcomes(nil) + assert stored(ctx.data) == [] + assert Receipt.all(ctx.data) == [] + + # Even a misplaced start must not consume the later outcome's identity. + File.write!(ctx.source, ctx.starts) + assert {0, _signature} = LearningScheduler.ingest_fleet_outcomes(nil) + assert stored(ctx.data) == [] + + # This deliberate test transfer is the boundary being exercised. The + # runner's current monthly-log paths do not perform this operation. + File.write!(ctx.source, ctx.starts <> ctx.primary <> ctx.central) + assert {2, signature} = LearningScheduler.ingest_fleet_outcomes(nil) + rows = stored(ctx.data) + expected_ids = ctx.primary |> decode() |> Enum.map(& &1["event_id"]) |> Enum.sort() + assert Enum.sort(Enum.map(rows, & &1["event_id"])) == expected_ids + + assert Enum.all?(rows, fn row -> + row["event_id_source"] == "producer" and + row["fleet_import_id"] == row["event_id"] and + row["verification"] == "failed" + end) + + assert OutcomeTracker.qualified_outcome_counts(rows) == %{ + successes: 0, + failures: 2, + false_positives: 0, + ignored: 0 + } + + receipts = Receipt.all(ctx.data) + assert Enum.sort(Enum.map(receipts, & &1["event_id"])) == expected_ids + assert Enum.all?(receipts, &(&1["verdict"] == "credited_failure")) + assert Enum.all?(receipts, &(&1["provenance"]["event_id_source"] == "producer")) + + before_replay = snapshot(ctx.data) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(signature) + assert {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + assert snapshot(ctx.data) == before_replay + end + + test "raw monthly producer rows do not implicitly become qualified fleet imports", ctx do + month = Date.utc_today() |> Date.to_iso8601() |> String.slice(0, 7) + File.write!(Path.join([ctx.data, "outcomes", month <> ".jsonl"]), ctx.primary) + + assert {0, nil} = LearningScheduler.ingest_fleet_outcomes(nil) + + assert OutcomeTracker.qualified_outcome_counts(stored(ctx.data)) == %{ + successes: 0, + failures: 0, + false_positives: 0, + ignored: 2 + } + + assert Receipt.all(ctx.data) == [] + end + + defp lines(bytes), do: String.split(bytes, "\n", trim: true) + defp decode(bytes), do: bytes |> lines() |> Enum.map(&Jason.decode!/1) + + defp stored(data) do + Path.wildcard(Path.join(data, "outcomes/*.jsonl")) + |> Enum.sort() + |> Enum.flat_map(&(File.read!(&1) |> decode())) + 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/hypatia-record-outcome-smoke.sh b/tests/hypatia-record-outcome-smoke.sh index 7c28c46b..aa945d05 100755 --- a/tests/hypatia-record-outcome-smoke.sh +++ b/tests/hypatia-record-outcome-smoke.sh @@ -30,6 +30,16 @@ fi # capture the early exit. TMP=$(mktemp -d /tmp/c15-smoke-XXXXXX) trap 'rm -rf "$TMP"' EXIT +# The function checks for mix before it checks placeholder recipe ids. Supply +# an inert executable so these no-call cases are independent of the host PATH. +mkdir "$TMP/bin" +cat > "$TMP/bin/mix" <<'STUB' +#!/usr/bin/env bash +echo 'unexpected mix call in a no-call smoke case' >&2 +exit 99 +STUB +chmod +x "$TMP/bin/mix" +export PATH="$TMP/bin:$PATH" # Extract just the function definitions we need (between # --- Hypatia # closed-loop contract --- and the next "# --- " section). Cheap and diff --git a/tests/hypatia-route-counterexample.exs b/tests/hypatia-route-counterexample.exs new file mode 100644 index 00000000..6d453af3 --- /dev/null +++ b/tests/hypatia-route-counterexample.exs @@ -0,0 +1,117 @@ +# SPDX-License-Identifier: MPL-2.0 +# Separate, deliberately failing gate against naive dual-route wiring: one +# emitted attempt can be credited by both the direct Mix callback and a later +# explicit fleet import. This is a counterexample to joining the current routes, +# not a universal acceptance test for a future exclusive-ingress design. +# Run from Hypatia with MIX_ENV=test, --no-start and DISPATCH_TEST_EVIDENCE_DIR +# pointing at the real producer fixture from scripts/tests/dispatch-paths.sh. + +unless Mix.env() == :test, do: raise("run this witness with MIX_ENV=test") + +if Process.whereis(Hypatia.Supervisor), + do: raise("run this witness with --no-start; the Hypatia application must be stopped") + +{:ok, _} = Application.ensure_all_started(:telemetry) + +defmodule Fleet.HypatiaRouteCounterexample do + alias Hypatia.{EventId, LearningScheduler, OutcomeTracker, Receipt} + + def run do + evidence = System.fetch_env!("DISPATCH_TEST_EVIDENCE_DIR") |> Path.expand() + [line | _] = File.read!(Path.join(evidence, "failure-primary.jsonl")) |> lines() + row = Jason.decode!(line) + true = row["verdict"] == "failed" and row["outcome"] == "failure" + true = EventId.valid?(row["event_id"]) + root = Path.join(System.tmp_dir!(), "fleet-route-#{System.unique_integer([:positive])}") + data = Path.join(root, "data") + fleet = Path.join(root, "fleet") + keys = [:verisimdb_data_path, :annealing_state_path, :fleet_path] + original = Map.new(keys, &{&1, Application.fetch_env(:hypatia, &1)}) + + try do + File.mkdir_p!(Path.join(data, "outcomes")) + Application.put_env(:hypatia, :verisimdb_data_path, data) + Application.put_env(:hypatia, :annealing_state_path, Path.join(data, "annealing")) + Application.put_env(:hypatia, :fleet_path, fleet) + file = if row["file"] in [nil, ""], do: ".", else: row["file"] + + # The actual task called by dispatch-runner, with that attempt's actual + # labels. The task deliberately does not accept producer identity. + Mix.Tasks.Hypatia.RecordOutcome.run([ + "--recipe", + row["recipe_id"], + "--repo", + row["repo"], + "--file", + file, + "--outcome", + "failure", + "--verdict", + "failed", + "--format", + "json" + ]) + + [local] = stored(data) + true = local["event_id"] != row["event_id"] + true = local["source_kind"] == "local_caller" + before = OutcomeTracker.qualified_outcome_counts([local]) + true = before.failures == 1 + + # The callback's bot=hypatia echo is ignored; the duplicate below is + # caused by explicitly adding the real producer row, not by the echo. + {0, _} = LearningScheduler.ingest_fleet_outcomes(nil) + source = Path.join(fleet, "shared-context/learning/fix-outcomes.jsonl") + File.write!(source, line <> "\n", [:append]) + {1, _} = LearningScheduler.ingest_fleet_outcomes(nil) + rows = stored(data) + after_import = OutcomeTracker.qualified_outcome_counts(rows) + + IO.puts( + Jason.encode!(%{ + check: "one qualified contribution per emitted attempt", + emitted_attempts: 1, + producer_event_id: row["event_id"], + direct_event_id: local["event_id"], + qualified_before_import: before.failures, + qualified_after_import: after_import.failures, + receipts_after_import: length(Receipt.all(data)), + automatic_delivery_tested: false + }) + ) + + if after_import.failures == 1 do + IO.puts("PASS: one attempt has one qualified contribution across the two routes") + 0 + else + IO.puts( + :stderr, + "FAIL: one actual producer attempt has #{after_import.failures} qualified " <> + "contributions after direct recording plus explicit import; route contract is unresolved" + ) + + 1 + end + after + for {key, value} <- original do + case value do + {:ok, previous} -> Application.put_env(:hypatia, key, previous) + :error -> Application.delete_env(:hypatia, key) + end + end + + File.rm_rf!(root) + end + end + + defp lines(bytes), do: String.split(bytes, "\n", trim: true) + + defp stored(data) do + Path.wildcard(Path.join(data, "outcomes/*.jsonl")) + |> Enum.sort() + |> Enum.flat_map(&(File.read!(&1) |> lines())) + |> Enum.map(&Jason.decode!/1) + end +end + +System.halt(Fleet.HypatiaRouteCounterexample.run()) diff --git a/tests/outcome-verdict-test.sh b/tests/outcome-verdict-test.sh index 134ea650..93dadf40 100755 --- a/tests/outcome-verdict-test.sh +++ b/tests/outcome-verdict-test.sh @@ -21,6 +21,8 @@ # 8. Run counters from background jobs reach the parent (--parallel). # 9. The runner's own run_entry and post-loop drain keep those counts # (extracted; the quarantined main loop is not run). +# 10. The actual runner in dispatch-paths.sh's isolated fixture preserves one +# producer id across start/outcome/mirrors, and refuses an unrecorded start. set -euo pipefail @@ -137,7 +139,8 @@ RESCAN_REPOS_FILE="$TMP/rescan" # shellcheck disable=SC1091 source "$TMP/extracted.sh" -record_outcome "PA009" "recipe-shell-quote-vars" "repo-a" "" verified 0 3 0 +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-license-hygiene" "repo-d" "" refused_license_policy @@ -149,6 +152,10 @@ check "unverified row has no counts" '{"verdict":"unverified","before_hits":null check "refusal keeps its own outcome" '{"verdict":"refused_license_policy","outcome":"refused_license_policy","exit_code":null}' \ "$(sed -n 4p "$OUTCOME_FILE" | jq -c '{verdict, outcome, exit_code}')" check "only verified repos trigger a rescan" "repo-a" "$(cat "$RESCAN_REPOS_FILE")" +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")')" # --- 5. deprecated recipe ids --------------------------------------------- registry="$ROOT/scripts/fix-script-registry.json" @@ -341,6 +348,15 @@ 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 ' ')" +# --- 11. producer identity through the actual dispatch paths (E0-12) ------ +# The existing harness copies the runner into a disposable tree and removes +# exactly its quarantine interlock there. It never changes the production +# runner or exposes a runtime switch that could unlock it. +dispatch_rc=0 +bash "$ROOT/scripts/tests/dispatch-paths.sh" > "$TMP/dispatch-paths.log" 2>&1 || dispatch_rc=$? +cat "$TMP/dispatch-paths.log" +check "isolated actual-runner producer identity contracts" 0 "$dispatch_rc" + echo "" echo "Results: $pass passed, $fail failed" [[ "$fail" -eq 0 ]] From 37ea58c5b577485de9dc1e2af46af1d09e7056e6 Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:25:58 +0000 Subject: [PATCH 2/4] fix(dispatch): deliver identified attempts through one fleet admission --- docs/design/e0-12-outcome-route-decision.adoc | 75 +++- docs/operations/NS-02-producer-identity.adoc | 12 +- docs/operations/NS-02-single-admission.adoc | 277 +++++++++++++++ scripts/dispatch-runner.sh | 244 +++++++------ scripts/tests/dispatch-paths.sh | 151 +++++++- tests/hypatia-record-outcome-smoke.sh | 12 +- tests/hypatia-single-admission-test.exs | 324 ++++++++++++++++++ tests/outcome-verdict-test.sh | 120 +++---- 8 files changed, 999 insertions(+), 216 deletions(-) create mode 100644 docs/operations/NS-02-single-admission.adoc create mode 100644 tests/hypatia-single-admission-test.exs 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..43d90932 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" @@ -206,19 +208,18 @@ 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 +231,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 +260,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 +267,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 +286,67 @@ 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 + 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 +380,7 @@ begin_attempt() { printf '%s\n' "$event_id" } -# record_outcome [exit before after event_id] +# 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 +397,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 +443,54 @@ 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 + if ! mkdir -p "$(dirname "$OUTCOME_FILE")" || ! 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 - # 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 + # The feed is already committed. Transport mirrors are not another attempt. + # Coalesce textual, symlink and hardlink aliases, including aliases of the feed. + local path previous resolved duplicate + local written=("$OUTCOME_FILE") + 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 - fi + written+=("$path") + done - # 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="" + # 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) - 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 - ;; + verified) echo "$repo" >> "$RESCAN_REPOS_FILE" ;; + refused_*) hypatia_record_refusal "$recipe_id" "$repo" "$file" || true ;; esac - hypatia_record_outcome "$recipe_id" "$repo" "$file" "$hypatia_outcome" "$verdict_arg" || true } -# 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 +599,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 +659,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 +689,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..e64ac1ca 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,18 @@ 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" runner_args=() hypatia_home="${DISPATCH_TEST_HYPATIA_HOME:-$fixture/hypatia}" runner_path="$fixture/bin:$PATH" @@ -129,8 +140,10 @@ 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" \ 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 +156,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 +177,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 +198,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 +210,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 +258,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 +287,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 +333,107 @@ 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" + +# 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' + +# 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 From 23e5995aeb12e8f6bae693c78963cf7adfcd46ee Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:43:24 +0000 Subject: [PATCH 3/4] fix(dispatch): fail closed on repo-root mismatch and LFS pointer feed, serialise appends Refuse a configured Hypatia repository root that differs from REPOS_BASE, refuse an unhydrated Git LFS pointer as the canonical feed, and hold one lock across the feed and both mirror appends so parallel attempts keep one order. Tests cover each case. --- .gitignore | 2 ++ scripts/dispatch-runner.sh | 45 ++++++++++++++++++++++++++++++++- scripts/tests/dispatch-paths.sh | 25 ++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) 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/scripts/dispatch-runner.sh b/scripts/dispatch-runner.sh index 43d90932..1eae6353 100755 --- a/scripts/dispatch-runner.sh +++ b/scripts/dispatch-runner.sh @@ -306,6 +306,26 @@ validate_outcome_paths() { 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" @@ -457,7 +477,27 @@ record_outcome() { return 1 fi - if ! mkdir -p "$(dirname "$OUTCOME_FILE")" || ! printf '%s\n' "$json" >> "$OUTCOME_FILE"; then + # 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 + append_outcome_rows "$json" "$event_id" || append_rc=$? + exec {lock_fd}>&- + [[ "$append_rc" -eq 0 ]] || return "$append_rc" + record_outcome_followup +} + +# 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" + 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 @@ -481,7 +521,10 @@ record_outcome() { 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. diff --git a/scripts/tests/dispatch-paths.sh b/scripts/tests/dispatch-paths.sh index e64ac1ca..341767ad 100755 --- a/scripts/tests/dispatch-paths.sh +++ b/scripts/tests/dispatch-paths.sh @@ -129,6 +129,7 @@ reset_fixture() { 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" @@ -141,6 +142,7 @@ invoke_runner() { 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" \ @@ -335,6 +337,8 @@ 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 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 @@ -395,6 +399,27 @@ 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" From bc4598b00dcf94f228cb149a794db7a204504342 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:45:55 +0000 Subject: [PATCH 4/4] fix(dispatch): keep append helpers in the extracted contract and require flock for every run Define append_outcome_rows and record_outcome_followup before record_outcome so the verdict test's extraction includes them, and check for flock before any attempt, not only for --parallel. --- scripts/dispatch-runner.sh | 89 +++++++++++++++++++------------------- 1 file changed, 45 insertions(+), 44 deletions(-) diff --git a/scripts/dispatch-runner.sh b/scripts/dispatch-runner.sh index 1eae6353..1d1911c7 100755 --- a/scripts/dispatch-runner.sh +++ b/scripts/dispatch-runner.sh @@ -200,9 +200,10 @@ 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 @@ -400,6 +401,47 @@ begin_attempt() { printf '%s\n' "$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 @@ -493,47 +535,6 @@ record_outcome() { record_outcome_followup } -# 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" - 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. - local path previous resolved duplicate - local written=("$OUTCOME_FILE") - 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 -} - # --- Execute a single manifest entry --- execute_entry() { local entry="$1"