diff --git a/.github/workflows/v5-power-plan-input-contract.yml b/.github/workflows/v5-power-plan-input-contract.yml index 0635d526..59f14846 100644 --- a/.github/workflows/v5-power-plan-input-contract.yml +++ b/.github/workflows/v5-power-plan-input-contract.yml @@ -24,7 +24,7 @@ jobs: timeout-minutes: 10 steps: - name: Checkout exact PR head with no persistent credential - uses: actions/checkout@v4 + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2, immutable checkout revision with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 1 diff --git a/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_JSON_INPUT_AMBIGUITY_GUARD_2026-10-10.md b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_JSON_INPUT_AMBIGUITY_GUARD_2026-10-10.md new file mode 100644 index 00000000..218f230a --- /dev/null +++ b/docs/research/paper-rebuild-v2-2026-10-02/V5_POWER_PLANNER_JSON_INPUT_AMBIGUITY_GUARD_2026-10-10.md @@ -0,0 +1,33 @@ +# V5 mechanical power-planner input ambiguity guard — 2026-10-10 + +Status: `DEVELOPMENT_ONLY_INPUT_INTEGRITY; UNREVIEWED_HYPOTHESES; NOT_FINAL_POWER`. + +## Reproduced flaw + +The unqualified development-only `scripts/v5_power_margin_plan.py` previously used the default Python `json.loads` behavior on caller-supplied power-planning specifications. When an object supplied the same key multiple times, **the last occurrence silently won**. A synthetic JSON specification based on the existing regression fixture was augmented with contradictory `primary_non_target_family_size` entries (`1`, then `4`). The command succeeded with `PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT` using `4`, despite the conflicting source text. Nested hypothesis identity or per-hypothesis nuisance keys had the same ambiguity. At no point did this bug prove that final power, hypothesis-family completeness, or clinical utility were qualified; all scientific/confirmatory authority flags were already `false`. + +Standard Python's non-strict JSON decoder also accepts `NaN`, `Infinity`, and `-Infinity`, which are **not** JSON numbers under RFC 8259. The downstream numeric contract rejected these if routed through its numeric fields, but rejecting them at source is a clearer, uniform trust boundary. + +## Narrow source-bound correction + +The CLI now loads all caller-supplied planning specifications with a strict JSON object-pairs hook that **rejects duplicate keys at every object depth**, after JSON unescaping (including `\\u` escapes). There is no silent last-wins canonicalization; a failed input produces no new plan output. It also rejects nonstandard `NaN`/`Infinity` literals, invalid UTF-8, malformed JSON and non-object JSON roots with controlled input-contract errors. A valid unambiguous input still emits `PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT` and `final_90_percent_power_qualified=false`, without a review or confirmatory grant. + +Real CLI subprocess negative tests (from an unrelated working directory with no `PYTHONPATH`) cover conflicting top-level Holm-family sizes, nested descriptive paired SD, nested hypothesis ID, Unicode-escaped equivalent duplicate names, `NaN`, `Infinity`, non-object roots and malformed JSON. The existing exact-head GitHub Actions V5 input-contract workflow includes the expanded focused test suite. + +## Non-overwrite protection for existing scientific evidence + +A separate Mac-only synthetic regression demonstrated that the original direct CLI allowed `--spec` and `--output` to reference the **same existing path**: it exited with `PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT` while destroying its own input bytes. Any previously written development planning receipt or original evidence file could have been similarly overwritten by an unintended output path. + +A subsequent bounded output-integrity correction writes new plan bytes to a same-directory temporary file with restrictive creation permissions, flushes and `fsync`s the full content, then publishes its *completed* bytes by atomic no-clobber hard link before removing the temporary name. A partial write, disk-full exception, sync failure, destination collision or publication failure cannot leave a newly visible partially written output filename. Regression tests inject failures **after a partial write**, during `fsync`, and while publishing the hard link, proving no destination and no leftover temporary file; positive tests prove exact bytes and immutable existing outputs. This is atomic filename visibility after complete file sync on supported filesystems, **not** a guarantee of parent-directory fsync or crash/power-loss persistence on every filesystem. Unsupported hard links fail closed rather than falling back to unsafe output truncation. + +The CLI now serializes its *unqualified* development-only result first, then publishes complete bytes by same-filesystem atomic no-clobber hard link after writing and syncing a temporary file, rather than truncating an existing path. An existing output file, the input source itself, a symlink to evidence, or a second attempt to use the same output name is rejected with `OUTPUT_ALREADY_EXISTS` and no success receipt. A failed temporary write/flush/sync or link leaves no partial new evidence filename. This is not an absolute power-loss durability guarantee on every filesystem. Direct-subprocess regressions use temp files to verify preserved bytes, symlink preservation and repeat invocation, without touching any actual frozen evidence. + +## Explicit boundaries + +- Strict JSON syntax **cannot** establish that a user-supplied hypothesis list is prospectively complete, that declared coupling tags are valid, or that an SHA-shaped evidence identifier identifies genuine qualified research evidence. +- The descriptive paired SD values still do **not** qualify the crossed source-case and stochastic training-seed nuisance model or 90% power. +- Scientific `main`, the frozen case generator/evidence/307 bound files, benchmark margins, study endpoints, actual observations and prior negative results are unchanged. +- No inference, model weights, GPU, paid cloud, PHI, confirmatory/reserve case identity access, independent review or founder authority is implied. +- The fix is isolated in a stacked draft successor to PR #327 because the existing local PR #327 worktree has separately owned uncommitted edits and must not be overwritten or committed by another session. No history rewrite or merge is performed. + +Reference: statistical and founder authorization gate [#326](https://github.com/TheHalfMoon/commandMed/issues/326), original defect report [PR #327 issuecomment-6094934938](https://github.com/TheHalfMoon/commandMed/pull/327#issuecomment-6094934938). diff --git a/scripts/v5_power_margin_plan.py b/scripts/v5_power_margin_plan.py index 39886c4b..7e57ddac 100644 --- a/scripts/v5_power_margin_plan.py +++ b/scripts/v5_power_margin_plan.py @@ -11,6 +11,8 @@ import hashlib import json import math +import os +import tempfile import re from pathlib import Path import sys @@ -127,6 +129,20 @@ def conservative_holm_planning_alpha(family_alpha: float, family_size: int) -> f return alpha / family_size + +def _finite_meaningful_margin(domain_floor: float, repeatability95: float) -> float: + """Keep the fixed 2x-repeatability margin finite at every planning scope.""" + repeat_component = 2.0 * repeatability95 + if not math.isfinite(repeat_component): + raise PowerPlanContractError( + "repeatability95: two-times repeatability margin overflows finite precision" + ) + margin = max(domain_floor, repeat_component) + if not math.isfinite(margin) or margin <= 0.0: + raise PowerPlanContractError("meaningful_margin: positive finite margin required") + return margin + + def _plan_metric( *, domain_floor: float, @@ -139,7 +155,7 @@ def _plan_metric( floor = _finite_positive(domain_floor, "domain_floor") repeat = _finite_nonnegative(repeatability95, "repeatability95") sd = _finite_nonnegative(paired_sd, "paired_sd") - margin = max(floor, 2.0 * repeat) + margin = _finite_meaningful_margin(floor, repeat) if type(planned_clusters) is not int or planned_clusters < 2: raise PowerPlanContractError("planned_clusters: expected an integer >= 2") power = _finite_positive(desired_power, "desired_power") @@ -168,6 +184,13 @@ def _plan_metric( "paired_sd/meaningful_margin: finite input produced " "an unrepresentable normal-approximation planning result" ) from exc + # A strictly positive source-case SD must never become an *exact zero* + # detectable effect because float arithmetic underflows. Zero has a + # distinct, explicitly handled branch above; reject lost precision. + if mde == 0.0: + raise PowerPlanContractError( + "paired_sd: positive planning noise underflowed to a zero MDE" + ) if not math.isfinite(mde): raise PowerPlanContractError( "paired_sd: normal-approximation minimum effect must be finite" @@ -204,8 +227,11 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: metrics = spec.get("metrics") if not isinstance(metrics, dict) or not metrics: raise PowerPlanContractError("metrics: expected a non-empty object") - if any(not isinstance(name, str) or not name.strip() for name in metrics): - raise PowerPlanContractError("metrics: invalid metric name") + if any( + not isinstance(name, str) or not name.strip() or name != name.strip() + for name in metrics + ): + raise PowerPlanContractError("metrics: nonempty unpadded metric name required") family_size, unreviewed_family_sha = _unreviewed_family_bindings(spec, set(metrics)) planning_alpha = conservative_holm_planning_alpha(family_alpha, family_size) desired_power = _finite_positive(spec.get("desired_power"), "desired_power") @@ -240,7 +266,7 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: result_metrics[name] = { "domain_floor": floor, "repeatability95": repeat, - "meaningful_margin": max(floor, 2.0 * repeat), + "meaningful_margin": _finite_meaningful_margin(floor, repeat), "domain_floor_justification_sha256": row["domain_floor_justification_sha256"], "repeatability_evidence_sha256": row["repeatability_evidence_sha256"], } @@ -327,19 +353,93 @@ def build_plan(spec: dict[str, Any]) -> dict[str, Any]: } +def _strict_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + """Reject duplicate keys after JSON unicode-escape decoding at every depth.""" + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise PowerPlanContractError( + f"AMBIGUOUS_JSON_DUPLICATE_KEY: {key!r}" + ) + result[key] = value + return result + + +def _reject_json_constant(value: str) -> None: + # Python's default JSON parser accepts NaN/Infinity despite JSON RFC 8259. + raise PowerPlanContractError(f"NONSTANDARD_JSON_CONSTANT: {value}") + + +def _load_strict_plan(path: Path) -> dict[str, Any]: + """Load only unambiguous JSON; preserve every downstream provenance check.""" + try: + payload = json.loads( + path.read_text(encoding="utf-8"), + object_pairs_hook=_strict_json_object, + parse_constant=_reject_json_constant, + ) + except PowerPlanContractError: + # Preserve precise ambiguity and nonstandard-constant rejections. + raise + except (UnicodeError, OSError, ValueError, RecursionError) as exc: + # json.loads can raise ValueError for Python's oversized integer guard + # and RecursionError for adversarial nesting, not just JSONDecodeError. + raise PowerPlanContractError("INVALID_POWER_PLAN_JSON") from exc + if not isinstance(payload, dict): + raise PowerPlanContractError("POWER_PLAN_ROOT_MUST_BE_OBJECT") + return payload + + + +def _publish_complete_output_no_clobber(output: Path, serialized: str) -> None: + """Expose a new evidence filename only after all bytes are written and synced. + + Hard-link publication is atomic and fails if the destination already exists, + including a symlink. Temp and destination are on the same filesystem. + This does not claim directory fsync or power-loss durability. + """ + destination_bytes = serialized.encode("utf-8") + fd, temporary = tempfile.mkstemp( + dir=output.parent, prefix=f".{output.name}.", suffix=".tmp" + ) + try: + try: + pending = memoryview(destination_bytes) + while pending: + written = os.write(fd, pending) + if written <= 0: + raise OSError("incomplete output write") + pending = pending[written:] + os.fsync(fd) + finally: + os.close(fd) + # Unlike replace/rename, this cannot overwrite even if a competing + # writer creates the destination while our temporary file is written. + os.link(temporary, output) + finally: + Path(temporary).unlink(missing_ok=True) + + def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--spec", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() - spec = json.loads(args.spec.read_text(encoding="utf-8")) + spec = _load_strict_plan(args.spec) payload = build_plan(spec) - args.output.parent.mkdir(parents=True, exist_ok=True) - args.output.write_text( - json.dumps(payload, indent=2, sort_keys=True) + "\n", - encoding="utf-8", - newline="\n", - ) + # Evidence is append-only: an accidental --output pointing at the input, + # an existing scientific artifact, or a symlink must not overwrite bytes. + # Exclusive creation is atomic at the destination on macOS/Linux/Windows. + serialized = json.dumps(payload, indent=2, sort_keys=True, allow_nan=False) + "\n" + try: + args.output.parent.mkdir(parents=True, exist_ok=True) + _publish_complete_output_no_clobber(args.output, serialized) + except FileExistsError as exc: + raise PowerPlanContractError( + "OUTPUT_ALREADY_EXISTS: refusing to overwrite prior research evidence" + ) from exc + except OSError as exc: + raise PowerPlanContractError("OUTPUT_NOT_WRITABLE") from exc print(json.dumps({ "status": "PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT", "final_90_percent_power_qualified": False, diff --git a/tests/reliability_v5/test_power_margin_plan.py b/tests/reliability_v5/test_power_margin_plan.py index 4e0344b4..ff2acaa9 100644 --- a/tests/reliability_v5/test_power_margin_plan.py +++ b/tests/reliability_v5/test_power_margin_plan.py @@ -88,6 +88,18 @@ def test_build_plan_applies_frozen_margin_rule_and_power() -> None: assert result["confirmatory_execution_authorized"] is False +@pytest.mark.parametrize("malformed_metric", [ + " canonical_nll ", + "canonical_nll ", + "\tcanonical_nll", +]) +def test_reject_whitespace_metric_aliases_even_when_unreferenced(malformed_metric: str) -> None: + spec = _spec() + spec["metrics"][malformed_metric] = copy.deepcopy(spec["metrics"]["canonical_nll"]) + with pytest.raises(plan.PowerPlanContractError, match="unpadded metric name"): + plan.build_plan(spec) + + def test_zero_paired_sd_is_handled_without_fake_positive_noise() -> None: spec = _spec() spec["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"]["paired_sd"] = 0.0 @@ -273,3 +285,271 @@ def test_large_finite_nuisance_exposes_contract_error_not_overflow() -> None: spec["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"]["paired_sd"] = 1e308 with pytest.raises(plan.PowerPlanContractError, match="unrepresentable"): plan.build_plan(spec) + + + +def test_positive_subnormal_nuisance_cannot_report_exact_zero_mde() -> None: + spec = _spec() + spec["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"]["paired_sd"] = 5e-324 + with pytest.raises(plan.PowerPlanContractError, match="underflowed to a zero MDE"): + plan.build_plan(spec) + + +def test_subnormal_nuisance_cli_never_creates_false_zero_power_evidence(tmp_path: Path) -> None: + spec = _spec() + spec["paired_nuisance_by_hypothesis"]["SYNTH-HYP-00"]["paired_sd"] = 5e-324 + source = tmp_path / "subnormal-development-only-input.json" + result = tmp_path / "must-not-exist-power-plan.json" + source.write_text(json.dumps(spec), encoding="utf-8") + script = Path(__file__).resolve().parents[2] / "scripts" / "v5_power_margin_plan.py" + completed = subprocess.run( + [sys.executable, str(script), "--spec", str(source), "--output", str(result)], + cwd=tmp_path, capture_output=True, text=True, env={"PATH": "/usr/bin:/bin"}, + ) + assert completed.returncode != 0 + assert "underflowed to a zero MDE" in completed.stderr + assert not result.exists() + + + +def test_overflowed_twice_repeatability_rejected_even_for_unused_metric() -> None: + spec = _spec() + spec["metrics"]["additional_unreviewed_metric"] = { + "domain_floor": 0.001, + "repeatability95": 1e308, + "domain_floor_justification_sha256": "a" * 64, + "repeatability_evidence_sha256": "b" * 64, + } + with pytest.raises(plan.PowerPlanContractError, match="repeatability margin overflows"): + plan.build_plan(spec) + spec = _spec() + spec["metrics"]["canonical_nll"]["repeatability95"] = 1e308 + with pytest.raises(plan.PowerPlanContractError, match="repeatability margin overflows"): + plan.build_plan(spec) + + +def test_cli_rejects_overflow_margin_before_creating_evidence(tmp_path: Path) -> None: + spec = _spec() + spec["metrics"]["additional_unreviewed_metric"] = { + "domain_floor": 0.001, + "repeatability95": 1e308, + "domain_floor_justification_sha256": "a" * 64, + "repeatability_evidence_sha256": "b" * 64, + } + source = tmp_path / "overlarge-development-only-input.json" + output = tmp_path / "must-not-exist.json" + source.write_text(json.dumps(spec), encoding="utf-8") + script = Path(__file__).resolve().parents[2] / "scripts" / "v5_power_margin_plan.py" + completed = subprocess.run( + [sys.executable, str(script), "--spec", str(source), "--output", str(output)], + cwd=tmp_path, capture_output=True, text=True, env={"PATH": "/usr/bin:/bin"}, + ) + assert completed.returncode != 0 + assert "repeatability margin overflows" in completed.stderr + assert not output.exists() + +def _run_unambiguous_input_cli( + tmp_path: Path, raw_json: str +) -> tuple[subprocess.CompletedProcess[str], Path]: + spec = tmp_path / "submitted-input.json" + output = tmp_path / "unqualified-plan.json" + spec.write_text(raw_json, encoding="utf-8") + script = Path(__file__).resolve().parents[2] / "scripts" / "v5_power_margin_plan.py" + completed = subprocess.run( + [sys.executable, str(script), "--spec", str(spec), "--output", str(output)], + cwd=tmp_path, + capture_output=True, + text=True, + env={"PATH": "/usr/bin:/bin"}, + ) + return completed, output + + +@pytest.mark.parametrize( + "mutator,reason", + [ + ( + lambda raw: raw[:-1] + ', "primary_non_target_family_size": 1, "primary_non_target_family_size": 4}', + "AMBIGUOUS_JSON_DUPLICATE_KEY", + ), + ( + lambda raw: raw.replace( + '"paired_sd": 0.2', '"paired_sd": 0.1, "paired_sd": 0.2', 1 + ), + "AMBIGUOUS_JSON_DUPLICATE_KEY", + ), + ( + lambda raw: raw.replace( + '"hypothesis_id": "SYNTH-HYP-00"', + '"hypothesis_id": "SYNTH-HYP-01", "hypothesis_id": "SYNTH-HYP-00"', + 1, + ), + "AMBIGUOUS_JSON_DUPLICATE_KEY", + ), + ( + lambda raw: raw.replace( + '"paired_sd": 0.2', + '"paired_sd": 0.1, "paired_\\u0073d": 0.2', + 1, + ), + "AMBIGUOUS_JSON_DUPLICATE_KEY", + ), + ( + lambda raw: raw.replace('"paired_sd": 0.2', '"paired_sd": NaN', 1), + "NONSTANDARD_JSON_CONSTANT", + ), + ( + lambda raw: raw.replace('"paired_sd": 0.2', '"paired_sd": Infinity', 1), + "NONSTANDARD_JSON_CONSTANT", + ), + ], +) +def test_direct_cli_rejects_ambiguous_or_nonstandard_json_at_all_depths( + tmp_path: Path, mutator, reason: str +) -> None: + original = json.dumps(_spec(), sort_keys=True) + submitted = mutator(original) + assert submitted != original + completed, output = _run_unambiguous_input_cli(tmp_path, submitted) + assert completed.returncode != 0 + assert reason in completed.stderr + assert not output.exists() + + +@pytest.mark.parametrize("malformed", [ + '{"planned_clusters": ' + '9' * 6000 + '}', + '{"nested":' + '[' * 10000 + '0' + ']' * 10000 + '}', +]) +def test_cli_rejects_oversized_or_deeply_nested_json_as_contract_error( + tmp_path: Path, malformed: str, +) -> None: + completed, output = _run_unambiguous_input_cli(tmp_path, malformed) + assert completed.returncode != 0 + assert "PowerPlanContractError: INVALID_POWER_PLAN_JSON" in completed.stderr + assert "Traceback" in completed.stderr # CLI is developer-facing, not a silent success. + assert not output.exists() + + +def test_direct_cli_accepts_single_key_equivalent_unicode_json( + tmp_path: Path, +) -> None: + original = json.dumps(_spec(), sort_keys=True) + completed, output = _run_unambiguous_input_cli(tmp_path, original) + assert completed.returncode == 0, completed.stderr + receipt = json.loads(completed.stdout) + assert receipt["status"] == "PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT" + assert receipt["final_90_percent_power_qualified"] is False + result = json.loads(output.read_text(encoding="utf-8")) + assert result["family_membership_frozen_and_independently_reviewed"] is False + assert result["confirmatory_execution_authorized"] is False + + +def test_reject_json_array_root_and_invalid_syntax(tmp_path: Path) -> None: + for idx, (raw, reason) in enumerate(( + ("[]", "POWER_PLAN_ROOT_MUST_BE_OBJECT"), + ('{"scope": "DEVELOPMENT_ONLY_POWER_PLANNING"', "INVALID_POWER_PLAN_JSON"), + )): + case = tmp_path / str(idx) + case.mkdir() + completed, output = _run_unambiguous_input_cli(case, raw) + assert completed.returncode != 0 + assert reason in completed.stderr + assert not output.exists() + + + +@pytest.mark.parametrize("failed_stage", ["partial_write", "fsync", "publish_link"]) +def test_complete_output_never_publishes_partial_bytes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failed_stage: str, +) -> None: + output = tmp_path / "unqualified-plan.json" + payload = json.dumps(plan.build_plan(_spec()), sort_keys=True, allow_nan=False) + "\n" + original_write = plan.os.write + writes = 0 + + def partial_then_fail(fd: int, data: bytes) -> int: + nonlocal writes + writes += 1 + if writes == 1: + return original_write(fd, data[: max(1, len(data) // 2)]) + raise OSError("synthetic disk full after partial write") + + def simulated_error(*_args: object) -> None: + raise OSError("synthetic evidence publication failure") + + with monkeypatch.context() as patcher: + if failed_stage == "partial_write": + patcher.setattr(plan.os, "write", partial_then_fail) + elif failed_stage == "fsync": + patcher.setattr(plan.os, "fsync", simulated_error) + else: + patcher.setattr(plan.os, "link", simulated_error) + with pytest.raises(OSError, match="synthetic"): + plan._publish_complete_output_no_clobber(output, payload) + assert not output.exists() + assert list(tmp_path.iterdir()) == [] + + +def test_complete_output_publishes_exact_bytes_and_never_overwrites( + tmp_path: Path, +) -> None: + output = tmp_path / "unqualified-plan.json" + payload = json.dumps(plan.build_plan(_spec()), sort_keys=True, allow_nan=False) + "\n" + plan._publish_complete_output_no_clobber(output, payload) + assert output.read_bytes() == payload.encode("utf-8") + with pytest.raises(FileExistsError): + plan._publish_complete_output_no_clobber(output, "ATTEMPTED_OVERWRITE") + assert output.read_bytes() == payload.encode("utf-8") + assert list(tmp_path.iterdir()) == [output] + + +def test_direct_cli_does_not_overwrite_its_input(tmp_path: Path) -> None: + source = tmp_path / "source-plan.json" + original = json.dumps(_spec(), sort_keys=True) + source.write_text(original, encoding="utf-8") + script = Path(__file__).resolve().parents[2] / "scripts" / "v5_power_margin_plan.py" + result = subprocess.run( + [sys.executable, str(script), "--spec", str(source), "--output", str(source)], + cwd=tmp_path, capture_output=True, text=True, env={"PATH": "/usr/bin:/bin"}, + ) + assert result.returncode != 0 + assert "OUTPUT_ALREADY_EXISTS" in result.stderr + assert source.read_text(encoding="utf-8") == original + assert "PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT" not in result.stdout + + +def test_direct_cli_does_not_overwrite_existing_evidence(tmp_path: Path) -> None: + destination = tmp_path / "unqualified-plan.json" + original = b"ORIGINAL_IMMUTABLE_EVIDENCE_2026-10-10\n" + destination.write_bytes(original) + result, output = _run_unambiguous_input_cli(tmp_path, json.dumps(_spec())) + assert output == destination + assert result.returncode != 0 + assert "OUTPUT_ALREADY_EXISTS" in result.stderr + assert output.read_bytes() == original + assert "PASS_DEVELOPMENT_ONLY_INPUT_CONTRACT" not in result.stdout + + +def test_direct_cli_refuses_existing_evidence_symlink(tmp_path: Path) -> None: + target = tmp_path / "untouchable-source-evidence.txt" + target.write_text("EVIDENCE_MUST_BE_PRESERVED", encoding="utf-8") + destination = tmp_path / "unqualified-plan.json" + destination.symlink_to(target) + result, output = _run_unambiguous_input_cli(tmp_path, json.dumps(_spec())) + assert result.returncode != 0 + assert "OUTPUT_ALREADY_EXISTS" in result.stderr + assert output.is_symlink() + assert target.read_text(encoding="utf-8") == "EVIDENCE_MUST_BE_PRESERVED" + + +def test_repeated_identical_cli_invocation_never_rewrites_first_receipt( + tmp_path: Path, +) -> None: + spec = json.dumps(_spec()) + first, output = _run_unambiguous_input_cli(tmp_path, spec) + assert first.returncode == 0, first.stderr + first_bytes = output.read_bytes() + second, output2 = _run_unambiguous_input_cli(tmp_path, spec) + assert second.returncode != 0 + assert "OUTPUT_ALREADY_EXISTS" in second.stderr + assert output2.read_bytes() == first_bytes