From b3ac6299f38c07216aaef91aab06bd13d689ab8e Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:41:42 -0800 Subject: [PATCH 01/22] fix: reject non-finite policy and report numbers Addresses occ_1db50b0180e3b3fd5d56f963 at the shared validation boundary, including direct callers and exponent overflow. --- SHA256SUMS | 8 ++++---- SOURCE.json | 2 +- scripts/check_release_bundle.py | 2 +- shared/scripts/schema_validation.py | 13 +++++++++++++ shared/scripts/test_schema_validation.py | 9 +++++++++ 5 files changed, 28 insertions(+), 6 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 57c87f1..1f4620e 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -b273423034914ee3c6599e3c780551f70bc8fef51f72a636f839810e82c3bacf SOURCE.json +10b7294a59ba26ba23ff462931952fb455a862c8fcc1eecaa571266886f9b185 SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -38,12 +38,12 @@ af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tes 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py e759ec5d797ca0101f81cd23e66b63229d0e55da463625b488a12a9a64758716 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -155a5dbbfe0423bb54ac1fb7d4bb1b1b3f6a91d920221d6d15b205b5689dc93e scripts/check_release_bundle.py +b81407a64338462a69195accf2a96eb75caf161a100df529c3d312830b396f4e scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md -82ffbacd09255c9311813cec37bd75d745df16ec21f457542ec5cd3b30739014 shared/scripts/schema_validation.py -7fef855399e1c4b7372d235c1d0fa3567583c4d428e8ee9f5cf122f596dd11e7 shared/scripts/test_schema_validation.py +11989881f6c77932edadb35e8e48f1671e0b5e6a0ec414a95fb7f3dc26f99481 shared/scripts/schema_validation.py +a16919c0981bcd1df2439839c18ed69cf1ad4c4b32da6b3e2610b154ca63c310 shared/scripts/test_schema_validation.py c7ad8aa74f5325b8bad0a44c979e4089cf3f57da787c209ed5d9cb71c7aaac1d shared/scripts/test_validate_feedback_report.py ca5cb3890f97d49affc5be7a15ba2c1a1859ca9afd459eeb6358fa27cbb05372 shared/scripts/validate_feedback_report.py 2d92172fe932ee0a39c7fc97dbd15f579fb21aa93adef40f53899472781481b3 tools/public_surface.json diff --git a/SOURCE.json b/SOURCE.json index 470d7e2..61e801d 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "513568419e76edf18ee1fa494d7c080ecb8ce96f9dfb9832aed6a1334edfe719", + "product_source_sha256": "f11915553c5f5e21cd4c39382910cd3333aebf1718282068290cacafad349cec", "included_roots": [ "keel-policy", "keel-setup", diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 74e7957..e209c70 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "513568419e76edf18ee1fa494d7c080ecb8ce96f9dfb9832aed6a1334edfe719" +PRODUCT_SOURCE_SHA256 = "f11915553c5f5e21cd4c39382910cd3333aebf1718282068290cacafad349cec" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", diff --git a/shared/scripts/schema_validation.py b/shared/scripts/schema_validation.py index c537580..ee9a20a 100644 --- a/shared/scripts/schema_validation.py +++ b/shared/scripts/schema_validation.py @@ -8,6 +8,7 @@ from __future__ import annotations import json +import math import re import uuid from datetime import datetime @@ -70,6 +71,18 @@ def validate( *, root_schema: dict[str, Any] | None = None, ) -> list[str]: + if root_schema is None: + # JSON numbers must be finite, including values in open objects and + # overflowed exponents. Check direct library callers as well as JSON. + pending = [(path, instance)] + while pending: + location, value = pending.pop() + if isinstance(value, float) and not math.isfinite(value): + return [f"{location}: number must be finite"] + if isinstance(value, dict): + pending.extend((f"{location}.{key}", child) for key, child in value.items()) + elif isinstance(value, list): + pending.extend((f"{location}[{index}]", child) for index, child in enumerate(value)) root_schema = schema if root_schema is None else root_schema unknown_keywords = set(schema) - SUPPORTED if unknown_keywords: diff --git a/shared/scripts/test_schema_validation.py b/shared/scripts/test_schema_validation.py index 26188b1..9622947 100644 --- a/shared/scripts/test_schema_validation.py +++ b/shared/scripts/test_schema_validation.py @@ -8,6 +8,15 @@ class SchemaSubsetValidatorTest(unittest.TestCase): + def test_nonfinite_numbers_are_rejected_even_in_open_objects(self): + for raw in ("NaN", "Infinity", "-Infinity", "1e999"): + value = json.loads(raw) + for candidate, schema in ((value, {"type": "number", "exclusiveMinimum": 0}), + ({"open": [value]}, {"type": "object"})): + with self.subTest(raw=raw): + self.assertTrue(schema_validation.validate(candidate, schema)) + self.assertEqual(schema_validation.validate(0.5, {"type": "number", "exclusiveMinimum": 0}), []) + def test_required_types_limits_unknowns_and_uniqueness(self): schema = { "type": "object", From 08bb694829868954f302520e1ef1da53658690de Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:41:57 -0800 Subject: [PATCH 02/22] fix: require timezone-aware RFC 3339 policy timestamps Addresses occ_b64c6c8e992d40be66b415c1; rejects naive, compact and invalid offsets while preserving Z and numeric-offset instants. --- SHA256SUMS | 8 ++++---- SOURCE.json | 2 +- scripts/check_release_bundle.py | 2 +- shared/scripts/schema_validation.py | 6 ++++-- shared/scripts/test_schema_validation.py | 8 ++++++++ 5 files changed, 18 insertions(+), 8 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 1f4620e..654e053 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -10b7294a59ba26ba23ff462931952fb455a862c8fcc1eecaa571266886f9b185 SOURCE.json +ce9dd93ebc4150ef24d4197488d87092a482860e1d7a5c15c67a94e1db2eb9df SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -38,12 +38,12 @@ af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tes 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py e759ec5d797ca0101f81cd23e66b63229d0e55da463625b488a12a9a64758716 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -b81407a64338462a69195accf2a96eb75caf161a100df529c3d312830b396f4e scripts/check_release_bundle.py +fcfb5f487ccbcfd916792050a74745fec6b6371998fe547f98d06ec6e91240b6 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md -11989881f6c77932edadb35e8e48f1671e0b5e6a0ec414a95fb7f3dc26f99481 shared/scripts/schema_validation.py -a16919c0981bcd1df2439839c18ed69cf1ad4c4b32da6b3e2610b154ca63c310 shared/scripts/test_schema_validation.py +98b38972b470bff93158c8611a4c3d200518c1520e348f144796c3fea314d529 shared/scripts/schema_validation.py +2f50fe0506fbed88b0f3f0f098a81896801a8551560bb514fcca657aca3de130 shared/scripts/test_schema_validation.py c7ad8aa74f5325b8bad0a44c979e4089cf3f57da787c209ed5d9cb71c7aaac1d shared/scripts/test_validate_feedback_report.py ca5cb3890f97d49affc5be7a15ba2c1a1859ca9afd459eeb6358fa27cbb05372 shared/scripts/validate_feedback_report.py 2d92172fe932ee0a39c7fc97dbd15f579fb21aa93adef40f53899472781481b3 tools/public_surface.json diff --git a/SOURCE.json b/SOURCE.json index 61e801d..71b7935 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "f11915553c5f5e21cd4c39382910cd3333aebf1718282068290cacafad349cec", + "product_source_sha256": "bc279e50935be23f81331dc16d73807db3a98da444ada32a449e8a1bc158223e", "included_roots": [ "keel-policy", "keel-setup", diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index e209c70..088c756 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "f11915553c5f5e21cd4c39382910cd3333aebf1718282068290cacafad349cec" +PRODUCT_SOURCE_SHA256 = "bc279e50935be23f81331dc16d73807db3a98da444ada32a449e8a1bc158223e" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", diff --git a/shared/scripts/schema_validation.py b/shared/scripts/schema_validation.py index ee9a20a..cdad9ee 100644 --- a/shared/scripts/schema_validation.py +++ b/shared/scripts/schema_validation.py @@ -42,11 +42,13 @@ def _format_matches(value: str, expected: str) -> bool: return False return True if expected == "date-time": + if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])", value) is None: + return False try: - datetime.fromisoformat(value.replace("Z", "+00:00")) + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError: return False - return "T" in value + return parsed.utcoffset() is not None if expected == "email": return re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", value) is not None return False diff --git a/shared/scripts/test_schema_validation.py b/shared/scripts/test_schema_validation.py index 9622947..a0bd8e0 100644 --- a/shared/scripts/test_schema_validation.py +++ b/shared/scripts/test_schema_validation.py @@ -8,6 +8,14 @@ class SchemaSubsetValidatorTest(unittest.TestCase): + def test_date_time_requires_an_unambiguous_rfc3339_instant(self): + schema = {"type": "string", "format": "date-time"} + for value in ("2026-11-06T12:00:00", "20261106T120000Z", "2026-11-06T12:00Z", + "2026-11-06 12:00:00Z", "2026-11-06T12:00:00+24:00", "2026-02-30T12:00:00Z"): + self.assertTrue(schema_validation.validate(value, schema), value) + for value in ("2026-11-06T12:00:00Z", "2026-11-06T12:00:00.123-08:00", "2026-11-06T12:00:00+05:30"): + self.assertEqual(schema_validation.validate(value, schema), [], value) + def test_nonfinite_numbers_are_rejected_even_in_open_objects(self): for raw in ("NaN", "Infinity", "-Infinity", "1e999"): value = json.loads(raw) From ce85e36b0886730168baba77851741cdb3dd8fd0 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:42:12 -0800 Subject: [PATCH 03/22] fix: scan feedback array strings and portable source paths Addresses occ_0c87b0ab4ef78950d1a787c1, including credentials in source_locations and Windows drive, UNC and backslash paths. --- SHA256SUMS | 8 ++++---- SOURCE.json | 2 +- scripts/check_release_bundle.py | 2 +- shared/scripts/test_validate_feedback_report.py | 11 +++++++++++ shared/scripts/validate_feedback_report.py | 9 +++++++-- 5 files changed, 24 insertions(+), 8 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 654e053..b067588 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -ce9dd93ebc4150ef24d4197488d87092a482860e1d7a5c15c67a94e1db2eb9df SOURCE.json +f5f3c00f562c41e27e5c599890cf6f66ad088d1d63e30798ab7d1a88fc5ef67a SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -38,12 +38,12 @@ af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tes 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py e759ec5d797ca0101f81cd23e66b63229d0e55da463625b488a12a9a64758716 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -fcfb5f487ccbcfd916792050a74745fec6b6371998fe547f98d06ec6e91240b6 scripts/check_release_bundle.py +f4ccd6ec03af955a1b795abd1b0615d008954c2bb44617310f2fc26cb0bb0963 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md 98b38972b470bff93158c8611a4c3d200518c1520e348f144796c3fea314d529 shared/scripts/schema_validation.py 2f50fe0506fbed88b0f3f0f098a81896801a8551560bb514fcca657aca3de130 shared/scripts/test_schema_validation.py -c7ad8aa74f5325b8bad0a44c979e4089cf3f57da787c209ed5d9cb71c7aaac1d shared/scripts/test_validate_feedback_report.py -ca5cb3890f97d49affc5be7a15ba2c1a1859ca9afd459eeb6358fa27cbb05372 shared/scripts/validate_feedback_report.py +640051660bb791a90eb67cea54e452e2a07420723df3c31ced71c323a6c28de3 shared/scripts/test_validate_feedback_report.py +658a2253c0aa0c25d9672ecf1e20402c28da475d6270d8770e1f29f31e35b8e0 shared/scripts/validate_feedback_report.py 2d92172fe932ee0a39c7fc97dbd15f579fb21aa93adef40f53899472781481b3 tools/public_surface.json diff --git a/SOURCE.json b/SOURCE.json index 71b7935..ab8445c 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "bc279e50935be23f81331dc16d73807db3a98da444ada32a449e8a1bc158223e", + "product_source_sha256": "98a9b6349053b8c88707eca5e0dcfbbc750d967e9aa7df6a93eb1bf42ca60716", "included_roots": [ "keel-policy", "keel-setup", diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 088c756..1f0314a 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "bc279e50935be23f81331dc16d73807db3a98da444ada32a449e8a1bc158223e" +PRODUCT_SOURCE_SHA256 = "98a9b6349053b8c88707eca5e0dcfbbc750d967e9aa7df6a93eb1bf42ca60716" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", diff --git a/shared/scripts/test_validate_feedback_report.py b/shared/scripts/test_validate_feedback_report.py index 2448ed6..c9be444 100644 --- a/shared/scripts/test_validate_feedback_report.py +++ b/shared/scripts/test_validate_feedback_report.py @@ -35,6 +35,17 @@ def report(): class FeedbackValidatorTest(unittest.TestCase): + def test_array_strings_receive_all_detectors_and_portable_path_checks(self): + for sample in ("Bearer example-sensitive", "token=opaque-value", "API_TOKEN=opaque-value", + "```source```", "/outside/file.py", "C:/project/file.py", "C:relative.py", + r"\\server\share\file.py", r"src\..\private.py", "../file.py"): + candidate = report() + candidate["optional_context"]["source_locations"] = [sample] + self.assertTrue(validator.validate(candidate, {"source_locations"}, None), sample) + candidate = report() + candidate["optional_context"]["source_locations"] = ["src/tool.py:9"] + self.assertEqual(validator.validate(candidate, {"source_locations"}, None), []) + def test_safe_default_report_passes_without_context_approval(self): self.assertEqual(validator.validate(report(), set(), None), []) diff --git a/shared/scripts/validate_feedback_report.py b/shared/scripts/validate_feedback_report.py index 6db9d16..70f6eca 100644 --- a/shared/scripts/validate_feedback_report.py +++ b/shared/scripts/validate_feedback_report.py @@ -42,7 +42,9 @@ def _walk(value: Any, path: str = ""): yield from _walk(child, child_path) elif isinstance(value, list): for index, child in enumerate(value): - yield from _walk(child, f"{path}[{index}]") + child_path = f"{path}[{index}]" + yield child_path, "", child + yield from _walk(child, child_path) def validate(report: Any, approved_context: set[str], channel: str | None) -> list[str]: @@ -84,7 +86,10 @@ def validate(report: Any, approved_context: set[str], channel: str | None) -> li for index, location in enumerate(locations): if not isinstance(location, str): failures.append(f"optional_context.source_locations[{index}] must be a string") - elif pathlib.PurePath(location).is_absolute() or ".." in pathlib.PurePosixPath(location).parts: + elif (not location or "\\" in location or pathlib.PureWindowsPath(location).drive + or pathlib.PurePosixPath(location).is_absolute() + or ".." in pathlib.PurePosixPath(location).parts + or any(ord(char) < 32 for char in location)): failures.append(f"optional_context.source_locations[{index}] must be repository-relative") else: failures.append("optional_context.source_locations must be an array") From 523f069cba8a9f462eb3879096e1e65b43598eb3 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:43:01 -0800 Subject: [PATCH 04/22] fix: reject fieldless policy condition trees Addresses occ_a2acb31c2859795c99dcdcac and the duplicate empty-condition aspect of occ_4fe6e63cc832a1b2e5f6c542. --- SHA256SUMS | 10 +++++----- SOURCE.json | 2 +- keel-policy/reference/policy-document.schema.json | 6 ++++-- keel-policy/scripts/validate_enforceability_report.py | 2 ++ .../tests/test_validate_enforceability_report.py | 7 +++++++ scripts/check_release_bundle.py | 2 +- 6 files changed, 20 insertions(+), 9 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index b067588..eb7fb88 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -f5f3c00f562c41e27e5c599890cf6f66ad088d1d63e30798ab7d1a88fc5ef67a SOURCE.json +be467b887150b14b3f7eb9b41b36a348e2e1a7671629679916346e9306e983ee SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -10,12 +10,12 @@ f5f3c00f562c41e27e5c599890cf6f66ad088d1d63e30798ab7d1a88fc5ef67a SOURCE.json 4ba18a72ba701fd0f21c8c341676bbbe823728fa7b286c97109df02b81b47936 keel-policy/reference/enforceability-report.schema.json 91fa5bbc7696846ec0d0039a88585ac99852b50a73613f92fea552f6931e7c44 keel-policy/reference/field-provenance.json 54416bf9c9af8f8fb75a9e883aa27aa62ecbcdffc2b1b6698d5fa1479fd6ddda keel-policy/reference/fields.md -4be41a65667952df8105e627026a921b66fc4fef19761242efabe69df0bd47cf keel-policy/reference/policy-document.schema.json +9c9563a832e43e655346eb6e644f4e3512d8ff06cef60639cf525c8412c9552b keel-policy/reference/policy-document.schema.json 7d662cffa24744af7a26f62d813127b4bc0a44ff62f725c883054165ddec3272 keel-policy/scripts/consume_authoring_context.py -188570c6787d720b8811a36382843b09f31bb37da78448c2a905fef2345511c9 keel-policy/scripts/validate_enforceability_report.py +ebf42588e3aaf8f0a4060567b916bf6eeb06de254564ab0b6806dffc169ec877 keel-policy/scripts/validate_enforceability_report.py b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb keel-policy/tests/test_authoring_context_consumption.py 820069a6ce02f74dccc4f57a5788359b1377520330d00ba88471d60fec901f17 keel-policy/tests/test_basic_profile_fields.py -322b430367e859dae341e9c225be34c6c5272c481074e7b1ae2242db527e1cbe keel-policy/tests/test_validate_enforceability_report.py +d8e9ec03fefe34aca796a2fed4a4506a43acadff68629ab93e74ed309bcbab67 keel-policy/tests/test_validate_enforceability_report.py 80624280a7ec0bd0273fcd37ffc9dec14003bb84b6e470a8b1e7f59f530a825f keel-setup/SKILL.md 2b9c2490e921e83b83372a09e422a30f0f7ee338a2809b8e07edbd381d9eb650 keel-setup/reference/coverage.schema.json 70a69dcab29f61aaa3f96de5f65854fca63c4549ddc20d84ee00e102fc68c691 keel-setup/reference/integration_profiles.v1.json @@ -38,7 +38,7 @@ af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tes 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py e759ec5d797ca0101f81cd23e66b63229d0e55da463625b488a12a9a64758716 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -f4ccd6ec03af955a1b795abd1b0615d008954c2bb44617310f2fc26cb0bb0963 scripts/check_release_bundle.py +1250c2931bcbbac8842e00705d68b905327f767b0990014103ce5f06e9c270da scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index ab8445c..16c359a 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "98a9b6349053b8c88707eca5e0dcfbbc750d967e9aa7df6a93eb1bf42ca60716", + "product_source_sha256": "1aebe978a580129d0a56367769123de3d4b78503acdcb6e340cdce01daa7a435", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-policy/reference/policy-document.schema.json b/keel-policy/reference/policy-document.schema.json index 44a68d5..e71a00c 100644 --- a/keel-policy/reference/policy-document.schema.json +++ b/keel-policy/reference/policy-document.schema.json @@ -21,7 +21,8 @@ ] }, "title": "All", - "type": "array" + "type": "array", + "minItems": 1 } }, "required": [ @@ -106,7 +107,8 @@ ] }, "title": "Any", - "type": "array" + "type": "array", + "minItems": 1 } }, "required": [ diff --git a/keel-policy/scripts/validate_enforceability_report.py b/keel-policy/scripts/validate_enforceability_report.py index 92b57f3..0faf473 100644 --- a/keel-policy/scripts/validate_enforceability_report.py +++ b/keel-policy/scripts/validate_enforceability_report.py @@ -103,6 +103,8 @@ def validate( if not isinstance(rule, dict): continue fields = _condition_fields(rule.get("if")) + if rule.get("action") not in NON_EFFECTING_ACTIONS and not fields: + failures.append(f"policy.rules[{rule_index}] automatic action requires a trusted condition leaf") for field in fields: matching = by_field.get(field, []) if not matching: diff --git a/keel-policy/tests/test_validate_enforceability_report.py b/keel-policy/tests/test_validate_enforceability_report.py index da7e437..600b8b9 100644 --- a/keel-policy/tests/test_validate_enforceability_report.py +++ b/keel-policy/tests/test_validate_enforceability_report.py @@ -47,6 +47,13 @@ def add_policy(candidate, field, action="allow"): class EnforceabilityValidatorTest(unittest.TestCase): + def test_empty_compounds_cannot_drive_automatic_actions_at_any_depth(self): + for condition in ({"all": []}, {"any": []}, {"not": {"all": []}}, + {"all": [{"field": "provider", "op": "eq", "value": "openai"}, {"any": []}]}): + candidate = add_policy(report(field="provider", status="trusted", replacement=None), "provider") + candidate["policy"]["rules"][0]["if"] = condition + self.assertTrue(validate(candidate), condition) + def test_action_name_requires_untrusted_status_and_exact_replacement(self): self.assertEqual(validate(report()), []) self.assertTrue(validate(report(status="trusted"))) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 1f0314a..c6b4f53 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "98a9b6349053b8c88707eca5e0dcfbbc750d967e9aa7df6a93eb1bf42ca60716" +PRODUCT_SOURCE_SHA256 = "1aebe978a580129d0a56367769123de3d4b78503acdcb6e340cdce01daa7a435" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From d8d3680ddadcba3e1e99bf3c71316f16685517ec Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:43:23 -0800 Subject: [PATCH 05/22] fix: bind approval requirements to one typed approver selector Addresses occ_b400f9aac60bc9a8bd548f28. Unsupported external workflow objects fail closed until a closed public contract exists. --- SHA256SUMS | 8 +- SOURCE.json | 2 +- .../reference/policy-document.schema.json | 298 +++++++++++++++++- scripts/check_release_bundle.py | 2 +- shared/scripts/test_schema_validation.py | 19 ++ 5 files changed, 313 insertions(+), 16 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index eb7fb88..9046af4 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -be467b887150b14b3f7eb9b41b36a348e2e1a7671629679916346e9306e983ee SOURCE.json +35dd013d8c06dfd5303df91244b076e7ba68cc92908564d49c70daff8555790f SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -10,7 +10,7 @@ be467b887150b14b3f7eb9b41b36a348e2e1a7671629679916346e9306e983ee SOURCE.json 4ba18a72ba701fd0f21c8c341676bbbe823728fa7b286c97109df02b81b47936 keel-policy/reference/enforceability-report.schema.json 91fa5bbc7696846ec0d0039a88585ac99852b50a73613f92fea552f6931e7c44 keel-policy/reference/field-provenance.json 54416bf9c9af8f8fb75a9e883aa27aa62ecbcdffc2b1b6698d5fa1479fd6ddda keel-policy/reference/fields.md -9c9563a832e43e655346eb6e644f4e3512d8ff06cef60639cf525c8412c9552b keel-policy/reference/policy-document.schema.json +5d4e384a5c0047b951569ce8e0956eeef7f233f736adea08c56c5d7f4575c138 keel-policy/reference/policy-document.schema.json 7d662cffa24744af7a26f62d813127b4bc0a44ff62f725c883054165ddec3272 keel-policy/scripts/consume_authoring_context.py ebf42588e3aaf8f0a4060567b916bf6eeb06de254564ab0b6806dffc169ec877 keel-policy/scripts/validate_enforceability_report.py b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb keel-policy/tests/test_authoring_context_consumption.py @@ -38,12 +38,12 @@ af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tes 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py e759ec5d797ca0101f81cd23e66b63229d0e55da463625b488a12a9a64758716 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -1250c2931bcbbac8842e00705d68b905327f767b0990014103ce5f06e9c270da scripts/check_release_bundle.py +6c24325eb207dc16fa0dae4b102c0587e11e58aa77adcc0d5d29f0abc19ad7af scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md 98b38972b470bff93158c8611a4c3d200518c1520e348f144796c3fea314d529 shared/scripts/schema_validation.py -2f50fe0506fbed88b0f3f0f098a81896801a8551560bb514fcca657aca3de130 shared/scripts/test_schema_validation.py +61ba88f8850ed8a962c647fc40bed90d25ba21e7d52c21d6e377967e3b8cd6a5 shared/scripts/test_schema_validation.py 640051660bb791a90eb67cea54e452e2a07420723df3c31ced71c323a6c28de3 shared/scripts/test_validate_feedback_report.py 658a2253c0aa0c25d9672ecf1e20402c28da475d6270d8770e1f29f31e35b8e0 shared/scripts/validate_feedback_report.py 2d92172fe932ee0a39c7fc97dbd15f579fb21aa93adef40f53899472781481b3 tools/public_surface.json diff --git a/SOURCE.json b/SOURCE.json index 16c359a..f8fb8c5 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "1aebe978a580129d0a56367769123de3d4b78503acdcb6e340cdce01daa7a435", + "product_source_sha256": "e92db82b378917400c248c24c800b01f8b8d336d1d8b09db86b086174f2fd045", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-policy/reference/policy-document.schema.json b/keel-policy/reference/policy-document.schema.json index e71a00c..27422f1 100644 --- a/keel-policy/reference/policy-document.schema.json +++ b/keel-policy/reference/policy-document.schema.json @@ -139,16 +139,9 @@ "title": "Email" }, "external_workflow": { - "anyOf": [ - { - "type": "object" - }, - { - "type": "null" - } - ], + "type": "null", "default": null, - "title": "External Workflow" + "description": "No closed external workflow contract is published in this offline bundle." }, "group_id": { "anyOf": [ @@ -278,7 +271,292 @@ "timeout_seconds" ], "title": "ApprovalRequirement", - "type": "object" + "type": "object", + "oneOf": [ + { + "properties": { + "type": { + "const": "org_role" + }, + "role": { + "maxLength": 32, + "minLength": 1, + "type": "string" + }, + "email": { + "type": "null" + }, + "group_id": { + "type": "null" + }, + "group_slug": { + "type": "null" + }, + "service_principal_id": { + "type": "null" + }, + "team_id": { + "type": "null" + }, + "team_slug": { + "type": "null" + }, + "user_id": { + "type": "null" + } + }, + "required": [ + "role" + ] + }, + { + "properties": { + "type": { + "const": "approver_group" + }, + "group_id": { + "format": "uuid", + "type": "string" + }, + "email": { + "type": "null" + }, + "group_slug": { + "type": "null" + }, + "role": { + "type": "null" + }, + "service_principal_id": { + "type": "null" + }, + "team_id": { + "type": "null" + }, + "team_slug": { + "type": "null" + }, + "user_id": { + "type": "null" + } + }, + "required": [ + "group_id" + ] + }, + { + "properties": { + "type": { + "const": "approver_group" + }, + "group_slug": { + "maxLength": 128, + "minLength": 1, + "type": "string" + }, + "email": { + "type": "null" + }, + "group_id": { + "type": "null" + }, + "role": { + "type": "null" + }, + "service_principal_id": { + "type": "null" + }, + "team_id": { + "type": "null" + }, + "team_slug": { + "type": "null" + }, + "user_id": { + "type": "null" + } + }, + "required": [ + "group_slug" + ] + }, + { + "properties": { + "type": { + "const": "team" + }, + "team_id": { + "format": "uuid", + "type": "string" + }, + "email": { + "type": "null" + }, + "group_id": { + "type": "null" + }, + "group_slug": { + "type": "null" + }, + "role": { + "type": "null" + }, + "service_principal_id": { + "type": "null" + }, + "team_slug": { + "type": "null" + }, + "user_id": { + "type": "null" + } + }, + "required": [ + "team_id" + ] + }, + { + "properties": { + "type": { + "const": "team" + }, + "team_slug": { + "maxLength": 128, + "minLength": 1, + "type": "string" + }, + "email": { + "type": "null" + }, + "group_id": { + "type": "null" + }, + "group_slug": { + "type": "null" + }, + "role": { + "type": "null" + }, + "service_principal_id": { + "type": "null" + }, + "team_id": { + "type": "null" + }, + "user_id": { + "type": "null" + } + }, + "required": [ + "team_slug" + ] + }, + { + "properties": { + "type": { + "const": "user" + }, + "user_id": { + "format": "uuid", + "type": "string" + }, + "email": { + "type": "null" + }, + "group_id": { + "type": "null" + }, + "group_slug": { + "type": "null" + }, + "role": { + "type": "null" + }, + "service_principal_id": { + "type": "null" + }, + "team_id": { + "type": "null" + }, + "team_slug": { + "type": "null" + } + }, + "required": [ + "user_id" + ] + }, + { + "properties": { + "type": { + "const": "email" + }, + "email": { + "format": "email", + "type": "string" + }, + "group_id": { + "type": "null" + }, + "group_slug": { + "type": "null" + }, + "role": { + "type": "null" + }, + "service_principal_id": { + "type": "null" + }, + "team_id": { + "type": "null" + }, + "team_slug": { + "type": "null" + }, + "user_id": { + "type": "null" + } + }, + "required": [ + "email" + ] + }, + { + "properties": { + "type": { + "const": "service_principal" + }, + "service_principal_id": { + "format": "uuid", + "type": "string" + }, + "email": { + "type": "null" + }, + "group_id": { + "type": "null" + }, + "group_slug": { + "type": "null" + }, + "role": { + "type": "null" + }, + "team_id": { + "type": "null" + }, + "team_slug": { + "type": "null" + }, + "user_id": { + "type": "null" + } + }, + "required": [ + "service_principal_id" + ] + } + ] }, "AttestationRequirement": { "additionalProperties": false, diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index c6b4f53..e2d01f0 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "1aebe978a580129d0a56367769123de3d4b78503acdcb6e340cdce01daa7a435" +PRODUCT_SOURCE_SHA256 = "e92db82b378917400c248c24c800b01f8b8d336d1d8b09db86b086174f2fd045" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", diff --git a/shared/scripts/test_schema_validation.py b/shared/scripts/test_schema_validation.py index a0bd8e0..3fa810f 100644 --- a/shared/scripts/test_schema_validation.py +++ b/shared/scripts/test_schema_validation.py @@ -8,6 +8,25 @@ class SchemaSubsetValidatorTest(unittest.TestCase): + def test_approval_selectors_are_closed_and_bound_to_their_type(self): + root = pathlib.Path(__file__).resolve().parents[2] + policy_schema = json.loads((root / "keel-policy/reference/policy-document.schema.json").read_text()) + schema = policy_schema["$defs"]["ApprovalRequirement"] + identifier = "12345678-1234-4234-8234-123456789abc" + choices = {"org_role": ("role", "admin"), "approver_group": ("group_id", identifier), + "team": ("team_slug", "reviewers"), "user": ("user_id", identifier), + "email": ("email", "review@example.invalid"), "service_principal": ("service_principal_id", identifier)} + for kind, (selector, value) in choices.items(): + base = {"type": kind, "timeout_seconds": 60} + self.assertTrue(schema_validation.validate(base, schema)) + valid = {**base, selector: value} + self.assertEqual(schema_validation.validate(valid, schema), [], kind) + other = "role" if selector != "role" else "email" + self.assertTrue(schema_validation.validate({**valid, other: "admin"}, schema)) + self.assertTrue(schema_validation.validate({**valid, "external_workflow": {"unexpected": True}}, schema)) + self.assertTrue(schema_validation.validate({"type": "approver_group", "timeout_seconds": 60, + "group_id": identifier, "group_slug": "reviewers"}, schema)) + def test_date_time_requires_an_unambiguous_rfc3339_instant(self): schema = {"type": "string", "format": "date-time"} for value in ("2026-11-06T12:00:00", "20261106T120000Z", "2026-11-06T12:00Z", From 3be527d8699d78f488f8b21b628536ac00c7ffae Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:45:55 -0800 Subject: [PATCH 06/22] fix: require exact destination confirmation before loopback key entry Addresses occ_f8afcdcf954b808bfa79484b. Interactive protocol doubles require independent exact URL confirmation before hidden credential entry; redirects remain blocked. --- SHA256SUMS | 12 ++++++------ SOURCE.json | 2 +- keel-setup/scripts/authoring_context.py | 9 +++++++++ keel-setup/scripts/verify_execute.py | 9 +++++++++ keel-setup/tests/test_authoring_context.py | 12 +++++++++++- keel-setup/tests/test_verify_execute.py | 12 +++++++++++- scripts/check_release_bundle.py | 2 +- 7 files changed, 48 insertions(+), 10 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 9046af4..02bc209 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -35dd013d8c06dfd5303df91244b076e7ba68cc92908564d49c70daff8555790f SOURCE.json +8e149d0680ad8d74a9ecd7adc766b8bda06b7a3d1ad82516729e41b240e1f9df SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -22,23 +22,23 @@ d8e9ec03fefe34aca796a2fed4a4506a43acadff68629ab93e74ed309bcbab67 keel-policy/te 9739501499b286d40f356af9c0378bbdcde41a364be083ccbc34adb000575160 keel-setup/reference/setup-state.schema.json 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md -4f54094b796b1e58591706a44b54b73626b374a5ce7892f5c8ed0509c8fb2372 keel-setup/scripts/authoring_context.py +383caedc85b1b2df50860f85dc79331bc811b45388daed62de9640610b4615a8 keel-setup/scripts/authoring_context.py 88d28844fff3cb1984649fafad9cc59950ea6e604adb0a12e98b7039b60b6150 keel-setup/scripts/fast_first_run.py 856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py 7a3b9b74a8a9cf4515990fa3816924244d8d2328b8fbaf33dfeca0efb5ea28c5 keel-setup/scripts/setup_state.py -550d24c9ddfc03ad7f03b3acf32033b5055987a443c70807fd2d1593c91fa06c keel-setup/scripts/verify_execute.py +69694ed9e70702551f98b1906d3596201f3948a230a7b45ce1e93f5672a39110 keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py -89eaed21a48503c3514b2ff336a5112da28ae21203e56d13444f0b79f6f8fcf1 keel-setup/tests/test_authoring_context.py +32873a16506fd78e1099e33c89693855918b4b530f7d7faf74dc96f85ef97f92 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py cb78b2d62beefee4aeea712fdcbabb4e0e633eb17c118e6fdbf06809aaa3b214 keel-setup/tests/test_fast_first_run.py 62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py -e759ec5d797ca0101f81cd23e66b63229d0e55da463625b488a12a9a64758716 keel-setup/tests/test_verify_execute.py +0f02c62545bf5eceeabde3513692f87601f261973b6eae47403fa44b9b1ad698 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -6c24325eb207dc16fa0dae4b102c0587e11e58aa77adcc0d5d29f0abc19ad7af scripts/check_release_bundle.py +49d1eb244dbb885558d3a6279a62a3876250420744cc379478100d45e7c13d03 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index f8fb8c5..de2a795 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "e92db82b378917400c248c24c800b01f8b8d336d1d8b09db86b086174f2fd045", + "product_source_sha256": "a793c21f90b963f10377bb49f5b673ae58e15d3ef3d3de04a2d7ad94720264d3", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/authoring_context.py b/keel-setup/scripts/authoring_context.py index 7c71832..fef0db6 100644 --- a/keel-setup/scripts/authoring_context.py +++ b/keel-setup/scripts/authoring_context.py @@ -642,6 +642,15 @@ def main(argv: list[str] | None = None) -> int: print(str(exc), file=sys.stderr) return 2 print("Pinned Keel setup release verified.", file=sys.stderr) + if args.base_url != DEFAULT_BASE_URL: + print(f"Protocol double destination: {args.base_url}. Use a test-only credential.", file=sys.stderr) + try: + confirmed = input("Type the exact destination URL to confirm: ") + except (EOFError, OSError, KeyboardInterrupt): + confirmed = "" + if confirmed != args.base_url: + print("Destination was not confirmed; no credential was read.", file=sys.stderr) + return 2 try: credential = _read_hidden_runtime_key() except (RuntimeError, KeyboardInterrupt) as exc: diff --git a/keel-setup/scripts/verify_execute.py b/keel-setup/scripts/verify_execute.py index 3e166a0..c1f99be 100644 --- a/keel-setup/scripts/verify_execute.py +++ b/keel-setup/scripts/verify_execute.py @@ -601,6 +601,15 @@ def main(argv: list[str] | None = None) -> int: print(str(exc), file=sys.stderr) return 2 print("Pinned Keel setup release verified.", file=sys.stderr) + if args.base_url != DEFAULT_BASE_URL: + print(f"Protocol double destination: {args.base_url}. Use a test-only credential.", file=sys.stderr) + try: + confirmed = input("Type the exact destination URL to confirm: ") + except (EOFError, OSError, KeyboardInterrupt): + confirmed = "" + if confirmed != args.base_url: + print("Destination was not confirmed; no credential was read.", file=sys.stderr) + return 2 try: key = _read_hidden_runtime_key() except (RuntimeError, KeyboardInterrupt) as exc: diff --git a/keel-setup/tests/test_authoring_context.py b/keel-setup/tests/test_authoring_context.py index 66d1837..a8eccfa 100644 --- a/keel-setup/tests/test_authoring_context.py +++ b/keel-setup/tests/test_authoring_context.py @@ -82,7 +82,9 @@ def server(responses): thread = threading.Thread(target=httpd.serve_forever, daemon=True) thread.start() try: - yield f"http://127.0.0.1:{httpd.server_port}" + base = f"http://127.0.0.1:{httpd.server_port}" + with mock.patch("builtins.input", return_value=base): + yield base finally: httpd.shutdown() thread.join() @@ -596,6 +598,14 @@ def _run_main(argv, *, responses, entered=KEY, stdin=None): class CommandTest(unittest.TestCase): + def test_loopback_refuses_before_reading_a_key_without_exact_confirmation(self): + with mock.patch.object(authoring_context, "_verify_pinned_release"), \ + mock.patch("builtins.input", return_value="yes"), \ + mock.patch.object(authoring_context, "_read_hidden_runtime_key") as read_key: + self.assertEqual(authoring_context.main(["--bundle-sha", "a" * 40, + "--base-url", "http://127.0.0.1:8123"]), 2) + read_key.assert_not_called() + def test_successful_run_prints_one_json_block(self): with _run_main(["--bundle-sha", "a" * 40], responses=[(200, context())]) as ( code, diff --git a/keel-setup/tests/test_verify_execute.py b/keel-setup/tests/test_verify_execute.py index dffb9ee..e2668ff 100644 --- a/keel-setup/tests/test_verify_execute.py +++ b/keel-setup/tests/test_verify_execute.py @@ -80,7 +80,9 @@ def server(responses): thread = threading.Thread(target=httpd.serve_forever, daemon=True) thread.start() try: - yield f"http://127.0.0.1:{httpd.server_port}" + base = f"http://127.0.0.1:{httpd.server_port}" + with mock.patch("builtins.input", return_value=base): + yield base finally: httpd.shutdown() thread.join() @@ -126,6 +128,14 @@ def test_freshness_replay_auth_and_malformed(self): class ProtocolDoubleTest(unittest.TestCase): + def test_loopback_refuses_before_reading_a_key_without_exact_confirmation(self): + with mock.patch.object(verify_execute, "_verify_pinned_release"), \ + mock.patch("builtins.input", return_value="yes"), \ + mock.patch.object(verify_execute, "_read_hidden_runtime_key") as read_key: + self.assertEqual(verify_execute.main(["--hidden-input", "--bundle-sha", "a" * 40, + "--base-url", "http://127.0.0.1:8123"]), 2) + read_key.assert_not_called() + def test_expected_pair_uses_unique_freshness_and_messages_without_leak(self): allow = {"status": "completed", "governance": {"decision": "allow"}, "output": {"sensitive": "not printed"}} deny = {"status": "denied", "governance": {"decision": "deny"}, "error": {"stage": "permit", "code": "policy.rule_denied"}} diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index e2d01f0..badd295 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "e92db82b378917400c248c24c800b01f8b8d336d1d8b09db86b086174f2fd045" +PRODUCT_SOURCE_SHA256 = "a793c21f90b963f10377bb49f5b673ae58e15d3ef3d3de04a2d7ad94720264d3" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From ed9b413daa5fcb8cd50cf14427511addc473ace8 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:46:22 -0800 Subject: [PATCH 07/22] fix: bound and contain all setup state file operations Addresses occ_57db8fa4159f800d1fb0ab3d with descriptor-relative no-follow regular-file reads, byte and nesting bounds, and contained atomic writes. --- SHA256SUMS | 8 +- SOURCE.json | 2 +- keel-setup/scripts/setup_state.py | 157 +++++++++++++++++++-------- keel-setup/tests/test_setup_state.py | 22 +++- scripts/check_release_bundle.py | 2 +- 5 files changed, 137 insertions(+), 54 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 02bc209..dfe4511 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -8e149d0680ad8d74a9ecd7adc766b8bda06b7a3d1ad82516729e41b240e1f9df SOURCE.json +a1975b15f4c99e81b2b73d805590ef52be2113ca0922167e0ea3b17448320bf7 SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -26,7 +26,7 @@ c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/ref 88d28844fff3cb1984649fafad9cc59950ea6e604adb0a12e98b7039b60b6150 keel-setup/scripts/fast_first_run.py 856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py -7a3b9b74a8a9cf4515990fa3816924244d8d2328b8fbaf33dfeca0efb5ea28c5 keel-setup/scripts/setup_state.py +8e33dafefbf5f60214f93a984f86571e2fd4d4266fcf46fcbf1e08fe31a8e13d keel-setup/scripts/setup_state.py 69694ed9e70702551f98b1906d3596201f3948a230a7b45ce1e93f5672a39110 keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 32873a16506fd78e1099e33c89693855918b4b530f7d7faf74dc96f85ef97f92 keel-setup/tests/test_authoring_context.py @@ -35,10 +35,10 @@ cb78b2d62beefee4aeea712fdcbabb4e0e633eb17c118e6fdbf06809aaa3b214 keel-setup/tes 62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py -87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py +48e55c1043e457873f941c9cf709287b25317553f5dabacb77cc1e2819e54b08 keel-setup/tests/test_setup_state.py 0f02c62545bf5eceeabde3513692f87601f261973b6eae47403fa44b9b1ad698 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -49d1eb244dbb885558d3a6279a62a3876250420744cc379478100d45e7c13d03 scripts/check_release_bundle.py +55eabf1c0914ed694d5e3e55181c8b0fceafdd323b6d5db06b1d86a08bf18580 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index de2a795..5e744b8 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "a793c21f90b963f10377bb49f5b673ae58e15d3ef3d3de04a2d7ad94720264d3", + "product_source_sha256": "5790b14d51e19ef09de41d7266c551a8ad566592dfeb6da7d981e4bfc1f10f9e", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/setup_state.py b/keel-setup/scripts/setup_state.py index d183b5d..8f0dc7c 100644 --- a/keel-setup/scripts/setup_state.py +++ b/keel-setup/scripts/setup_state.py @@ -12,14 +12,16 @@ from __future__ import annotations import argparse +import contextlib import datetime as dt import json import os import pathlib import re +import secrets +import stat import subprocess import sys -import tempfile from typing import Any sys.dont_write_bytecode = True @@ -33,6 +35,8 @@ SCHEMA_VERSION = "1.0" MAX_STRING_LENGTH = 512 +MAX_STATE_BYTES = 32_768 +MAX_STATE_DEPTH = 32 REQUIRED_PRE_GATE_CHECKS = ( "syntax_or_compile", "fail_closed_integration_review", @@ -354,36 +358,93 @@ def is_git_ignored(repo_root: pathlib.Path, relative: pathlib.PurePosixPath) -> return None -def write_state_atomically(state_path: pathlib.Path, state: dict[str, Any]) -> None: +@contextlib.contextmanager +def _state_parent(state_path: pathlib.Path, repo_root: pathlib.Path, *, create: bool = False): + root = repo_root.resolve(strict=True) + lexical_root = pathlib.Path(os.path.abspath(repo_root)) + candidate = state_path if state_path.is_absolute() else lexical_root / state_path + try: + relative = candidate.relative_to(lexical_root) + except ValueError: + relative = candidate.relative_to(root) + if not relative.parts or any(part in {".", ".."} for part in relative.parts): + raise ValueError("state path must be inside the repository") + fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for part in relative.parts[:-1]: + if create: + try: + os.mkdir(part, mode=0o700, dir_fd=fd) + except FileExistsError: + pass + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) + os.close(fd) + fd = child + yield fd, relative.name + finally: + os.close(fd) + + +def read_state(state_path: pathlib.Path, repo_root: pathlib.Path) -> Any: + with _state_parent(state_path, repo_root) as (parent, name): + fd = os.open(name, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, dir_fd=parent) + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_STATE_BYTES: + raise ValueError("state must be a bounded regular file") + raw = stream.read(MAX_STATE_BYTES + 1) + if len(raw) > MAX_STATE_BYTES: + raise ValueError("state exceeds its byte limit") + depth = 0 + quoted = escaped = False + for char in raw.decode("utf-8"): + if quoted: + if escaped: + escaped = False + elif char == "\\": + escaped = True + elif char == '"': + quoted = False + elif char == '"': + quoted = True + elif char in "[{": + depth += 1 + if depth > MAX_STATE_DEPTH: + raise ValueError("state exceeds its nesting limit") + elif char in "]}": + depth -= 1 + return json.loads(raw) + + +def write_state_atomically(state_path: pathlib.Path, state: dict[str, Any], repo_root: pathlib.Path | None = None) -> None: """Persist validated continuity without ever exposing a partial JSON file.""" failures = validate_state(state) if failures: raise ValueError("refusing to persist invalid local setup state: " + "; ".join(failures)) - state_path.parent.mkdir(parents=True, exist_ok=True) - temporary_path: pathlib.Path | None = None - try: - with tempfile.NamedTemporaryFile( - mode="w", - encoding="utf-8", - dir=state_path.parent, - prefix=f".{state_path.name}.", - suffix=".tmp", - delete=False, - ) as handle: - temporary_path = pathlib.Path(handle.name) - os.chmod(temporary_path, 0o600) - json.dump(state, handle, indent=2, sort_keys=True) - handle.write("\n") - handle.flush() - os.fsync(handle.fileno()) - os.replace(temporary_path, state_path) - temporary_path = None - finally: - if temporary_path is not None: + raw = (json.dumps(state, indent=2, sort_keys=True) + "\n").encode() + if len(raw) > MAX_STATE_BYTES: + raise ValueError("state exceeds its byte limit") + with _state_parent(state_path, repo_root or state_path.parent, create=True) as (parent, name): + try: + info = os.stat(name, dir_fd=parent, follow_symlinks=False) + except FileNotFoundError: + pass + else: + if not stat.S_ISREG(info.st_mode): + raise ValueError("state must be a regular nonsymlink file") + temporary_name = f".setup-state-{secrets.token_hex(16)}.tmp" + try: + fd = os.open(temporary_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent) + with os.fdopen(fd, "wb") as handle: + handle.write(raw) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary_name, name, src_dir_fd=parent, dst_dir_fd=parent) + finally: try: - temporary_path.unlink() + os.unlink(temporary_name, dir_fd=parent) except FileNotFoundError: pass @@ -395,30 +456,30 @@ def begin(state_path: pathlib.Path, repo_root: pathlib.Path) -> dict[str, Any]: continuity = "resumed" continuity_reason: str | None = None problems: list[str] = [] + unsafe_file = False try: - raw = state_path.read_text(encoding="utf-8") - except OSError: + loaded = read_state(state_path, repo_root) + except FileNotFoundError: state = initial_state(updated_at=now) continuity = "lost" continuity_reason = "no local state file was readable at this path" + except (OSError, ValueError, UnicodeError, RecursionError) as exc: + unsafe_file = not isinstance(exc, json.JSONDecodeError) + state = initial_state(updated_at=now) + continuity = "lost" + continuity_reason = "local state file was refused" + problems = ["local state must be bounded JSON in a regular repository file"] else: - try: - loaded = json.loads(raw) - except json.JSONDecodeError as exc: + problems = validate_state(loaded) + problems.extend(validate_prepared_paths(loaded, repo_root)) + if problems: state = initial_state(updated_at=now) continuity = "lost" - continuity_reason = f"local state file is not valid JSON: {exc}" + continuity_reason = "local state file was refused; see refusals" else: - problems = validate_state(loaded) - problems.extend(validate_prepared_paths(loaded, repo_root)) - if problems: - state = initial_state(updated_at=now) - continuity = "lost" - continuity_reason = "local state file was refused; see refusals" - else: - state = dict(loaded) - state["invocation_count"] = int(state["invocation_count"]) + 1 - state["updated_at"] = now + state = dict(loaded) + state["invocation_count"] = int(state["invocation_count"]) + 1 + state["updated_at"] = now stage = state.get("stage") relative = state_path @@ -430,9 +491,11 @@ def begin(state_path: pathlib.Path, repo_root: pathlib.Path) -> dict[str, Any]: state_persisted = False persistence_error: str | None = None - if ignored is True: + if unsafe_file: + persistence_error = "unsafe local state path or contents were refused" + elif ignored is True: try: - write_state_atomically(state_path, state) + write_state_atomically(state_path, state, repo_root) except (OSError, ValueError) as exc: persistence_error = f"local state was not persisted: {exc}" else: @@ -478,8 +541,8 @@ def mark_waiting_for_human( """Persist only the local-preparation milestone; never runtime or authority state.""" try: - state = json.loads(state_path.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: + state = read_state(state_path, repo_root) + except (OSError, ValueError, UnicodeError, RecursionError) as exc: return [f"local state must be initialized before recording the human gate: {exc}"] failures = validate_state(state) if failures: @@ -541,7 +604,7 @@ def mark_waiting_for_human( if failures: return failures try: - write_state_atomically(state_path, updated) + write_state_atomically(state_path, updated, repo_root) except (OSError, ValueError) as exc: return [f"local state was not persisted: {exc}"] return [] @@ -603,8 +666,8 @@ def main(argv: list[str] | None = None) -> int: if args.validate_only: try: - state = json.loads(args.state.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: + state = read_state(args.state, args.repo_root) + except (OSError, ValueError, UnicodeError, RecursionError) as exc: print(f"unreadable local state: {exc}", file=sys.stderr) return 1 failures = validate_state(state) diff --git a/keel-setup/tests/test_setup_state.py b/keel-setup/tests/test_setup_state.py index fcb64b7..ea93494 100644 --- a/keel-setup/tests/test_setup_state.py +++ b/keel-setup/tests/test_setup_state.py @@ -59,6 +59,26 @@ def _write_prepared(path: pathlib.Path) -> None: class SchemaTest(unittest.TestCase): + def test_state_reads_refuse_unsafe_files_and_bounded_json(self): + import os + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + path = root / "state.json" + for raw in (b"x" * (setup_state.MAX_STATE_BYTES + 1), b"[" * 40 + b"0" + b"]" * 40): + path.write_bytes(raw) + with self.assertRaises(ValueError): + setup_state.read_state(path, root) + path.unlink() + os.mkfifo(path) + with self.assertRaises(ValueError): + setup_state.read_state(path, root) + path.unlink() + path.symlink_to(root.parent / "outside-state.json") + with self.assertRaises(OSError): + setup_state.read_state(path, root) + with self.assertRaises(ValueError): + setup_state.read_state(root.parent / "outside-state.json", root) + def test_shipped_shape_validates(self): self.assertEqual(setup_state.validate_state(_valid()), []) @@ -584,7 +604,7 @@ def test_validate_only_accepts_the_shipped_shape(self): path = pathlib.Path(directory) / "setup-state.json" path.write_text(json.dumps(_valid())) with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - code = setup_state.main(["--validate-only", "--state", str(path)]) + code = setup_state.main(["--validate-only", "--state", str(path), "--repo-root", directory]) self.assertEqual(code, 0) def test_helper_takes_no_credential_argument(self): diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index badd295..5642ecd 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "a793c21f90b963f10377bb49f5b673ae58e15d3ef3d3de04a2d7ad94720264d3" +PRODUCT_SOURCE_SHA256 = "5790b14d51e19ef09de41d7266c551a8ad566592dfeb6da7d981e4bfc1f10f9e" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 2099ccc2f6d7b603d39490fabac3b5e45086ff81 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:48:15 -0800 Subject: [PATCH 08/22] fix: render only fixed local protocol error codes Addresses occ_6e67eb0f242b4abd6587603e across authoring-context, verification-profile and execute output. Unknown remote tokens cannot be reflected into errors. --- SHA256SUMS | 12 ++++++------ SOURCE.json | 2 +- keel-setup/scripts/authoring_context.py | 8 +++++--- keel-setup/scripts/verify_execute.py | 9 ++++++--- keel-setup/tests/test_authoring_context.py | 6 ++++++ keel-setup/tests/test_verify_execute.py | 6 ++++++ scripts/check_release_bundle.py | 2 +- 7 files changed, 31 insertions(+), 14 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index dfe4511..db1b2cd 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -a1975b15f4c99e81b2b73d805590ef52be2113ca0922167e0ea3b17448320bf7 SOURCE.json +19a8019f7e415ab472b010a3e73c0057cd69c029b63920ecc27fb4d62d865145 SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -22,23 +22,23 @@ d8e9ec03fefe34aca796a2fed4a4506a43acadff68629ab93e74ed309bcbab67 keel-policy/te 9739501499b286d40f356af9c0378bbdcde41a364be083ccbc34adb000575160 keel-setup/reference/setup-state.schema.json 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md -383caedc85b1b2df50860f85dc79331bc811b45388daed62de9640610b4615a8 keel-setup/scripts/authoring_context.py +580edac4805c13a2b88b7dde613bf3a388347c9d00c6f9488c1ceb9e593368d3 keel-setup/scripts/authoring_context.py 88d28844fff3cb1984649fafad9cc59950ea6e604adb0a12e98b7039b60b6150 keel-setup/scripts/fast_first_run.py 856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py 8e33dafefbf5f60214f93a984f86571e2fd4d4266fcf46fcbf1e08fe31a8e13d keel-setup/scripts/setup_state.py -69694ed9e70702551f98b1906d3596201f3948a230a7b45ce1e93f5672a39110 keel-setup/scripts/verify_execute.py +1bc3d136fe06414a090976712c96fef0f46d7922ed3cd5cf502fa174de1aa86d keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py -32873a16506fd78e1099e33c89693855918b4b530f7d7faf74dc96f85ef97f92 keel-setup/tests/test_authoring_context.py +5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py cb78b2d62beefee4aeea712fdcbabb4e0e633eb17c118e6fdbf06809aaa3b214 keel-setup/tests/test_fast_first_run.py 62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py 48e55c1043e457873f941c9cf709287b25317553f5dabacb77cc1e2819e54b08 keel-setup/tests/test_setup_state.py -0f02c62545bf5eceeabde3513692f87601f261973b6eae47403fa44b9b1ad698 keel-setup/tests/test_verify_execute.py +ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -55eabf1c0914ed694d5e3e55181c8b0fceafdd323b6d5db06b1d86a08bf18580 scripts/check_release_bundle.py +51e83b42b8d2b35b5c79e14541bb39ee060991312513105f4d148ad76edf9baf scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index 5e744b8..f6b5dec 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "5790b14d51e19ef09de41d7266c551a8ad566592dfeb6da7d981e4bfc1f10f9e", + "product_source_sha256": "01cd42d1512af95474bcbb20800c77baacea53ebf5153747e60f5b5f3708345d", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/authoring_context.py b/keel-setup/scripts/authoring_context.py index fef0db6..6df464c 100644 --- a/keel-setup/scripts/authoring_context.py +++ b/keel-setup/scripts/authoring_context.py @@ -424,9 +424,11 @@ def _read_bounded(response: Any) -> bytes: def _safe_error_code(value: Any) -> str | None: - """Return one bounded protocol error code, never arbitrary response text.""" - - if not isinstance(value, str) or _SAFE_ERROR_CODE_PATTERN.fullmatch(value) is None: + """Render only a closed local vocabulary, never a remote token.""" + if not isinstance(value, str) or value not in { + "unauthorized", "request_not_fresh", "nonce_reuse", "authoring_context_unavailable", + "rate_limited", "unavailable", "invalid_request", + }: return None return value diff --git a/keel-setup/scripts/verify_execute.py b/keel-setup/scripts/verify_execute.py index c1f99be..5a5e616 100644 --- a/keel-setup/scripts/verify_execute.py +++ b/keel-setup/scripts/verify_execute.py @@ -458,9 +458,12 @@ def _allowlisted_scalar(value: Any, allowed: frozenset[str]) -> str | None: def _safe_error_code(value: Any) -> str | None: - """Return one bounded protocol error code, never arbitrary response text.""" - - if not isinstance(value, str) or _SAFE_ERROR_CODE_PATTERN.fullmatch(value) is None: + """Render only a closed local vocabulary, never a remote token.""" + if not isinstance(value, str) or value not in { + "unauthorized", "request_not_fresh", "nonce_reuse", "policy.rule_denied", + "verification_profile_unavailable", "verification_profile_pending", "provider_refused", + "no_active_policy", "rate_limited", "unavailable", "invalid_request", + }: return None return value diff --git a/keel-setup/tests/test_authoring_context.py b/keel-setup/tests/test_authoring_context.py index a8eccfa..fa2d4ba 100644 --- a/keel-setup/tests/test_authoring_context.py +++ b/keel-setup/tests/test_authoring_context.py @@ -598,6 +598,12 @@ def _run_main(argv, *, responses, entered=KEY, stdin=None): class CommandTest(unittest.TestCase): + def test_error_response_cannot_reflect_the_entered_credential(self): + for reflected in (KEY, KEY.lower(), "opaque_secret"): + with _run_main(["--bundle-sha", "a" * 40], responses=[(401, {"error": {"code": reflected}})]) as (code, out, err): + self.assertEqual(code, 1) + self.assertNotIn(reflected, out + err) + def test_loopback_refuses_before_reading_a_key_without_exact_confirmation(self): with mock.patch.object(authoring_context, "_verify_pinned_release"), \ mock.patch("builtins.input", return_value="yes"), \ diff --git a/keel-setup/tests/test_verify_execute.py b/keel-setup/tests/test_verify_execute.py index e2668ff..0f84f31 100644 --- a/keel-setup/tests/test_verify_execute.py +++ b/keel-setup/tests/test_verify_execute.py @@ -107,6 +107,12 @@ def verification_profile(*, digest: str = "a" * 64): class ClassifierTest(unittest.TestCase): + def test_remote_codes_cannot_reflect_credentials_or_arbitrary_tokens(self): + for value in ("ks_abcdefghijkl", "sk_abcdefghijkl", "opaque_secret", "x" * 128, "policy.arbitrary"): + self.assertIsNone(verify_execute._safe_error_code(value)) + self.assertNotIn(value, json.dumps(verify_execute.classify(401, {"error": {"code": value}}))) + self.assertEqual(verify_execute._safe_error_code("unauthorized"), "unauthorized") + def test_http_403_requires_full_tuple(self): denied = verify_execute.classify( 403, {"status": "denied", "governance": {"decision": "deny"}, "error": {"stage": "permit"}} diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 5642ecd..8f63af8 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "5790b14d51e19ef09de41d7266c551a8ad566592dfeb6da7d981e4bfc1f10f9e" +PRODUCT_SOURCE_SHA256 = "01cd42d1512af95474bcbb20800c77baacea53ebf5153747e60f5b5f3708345d" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 1b39439706418aabe0a6a0c4b53333b6584e98a6 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:48:27 -0800 Subject: [PATCH 09/22] fix: keep source diffs and literal defaults out of setup output Addresses occ_3bc29310300650292c6992a6. Emit path, digest and count metadata; retain exact signature comparison internally and require local human diff inspection. --- SHA256SUMS | 10 +++---- SOURCE.json | 2 +- keel-setup/SKILL.md | 8 +++--- keel-setup/scripts/fast_first_run.py | 38 +++++++------------------ keel-setup/tests/test_fast_first_run.py | 34 +++++++++++----------- scripts/check_release_bundle.py | 2 +- 6 files changed, 40 insertions(+), 54 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index db1b2cd..9934205 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -19a8019f7e415ab472b010a3e73c0057cd69c029b63920ecc27fb4d62d865145 SOURCE.json +6175c4b6e2da861e5e4d39ac83c74c8933f3cea6c482ddef6560ef7f07800032 SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -16,14 +16,14 @@ ebf42588e3aaf8f0a4060567b916bf6eeb06de254564ab0b6806dffc169ec877 keel-policy/sc b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb keel-policy/tests/test_authoring_context_consumption.py 820069a6ce02f74dccc4f57a5788359b1377520330d00ba88471d60fec901f17 keel-policy/tests/test_basic_profile_fields.py d8e9ec03fefe34aca796a2fed4a4506a43acadff68629ab93e74ed309bcbab67 keel-policy/tests/test_validate_enforceability_report.py -80624280a7ec0bd0273fcd37ffc9dec14003bb84b6e470a8b1e7f59f530a825f keel-setup/SKILL.md +383d08c6433e906b3082a9346f81bbc429b08b8124fd00a38ec3bbb9d44d56b4 keel-setup/SKILL.md 2b9c2490e921e83b83372a09e422a30f0f7ee338a2809b8e07edbd381d9eb650 keel-setup/reference/coverage.schema.json 70a69dcab29f61aaa3f96de5f65854fca63c4549ddc20d84ee00e102fc68c691 keel-setup/reference/integration_profiles.v1.json 9739501499b286d40f356af9c0378bbdcde41a364be083ccbc34adb000575160 keel-setup/reference/setup-state.schema.json 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md 580edac4805c13a2b88b7dde613bf3a388347c9d00c6f9488c1ceb9e593368d3 keel-setup/scripts/authoring_context.py -88d28844fff3cb1984649fafad9cc59950ea6e604adb0a12e98b7039b60b6150 keel-setup/scripts/fast_first_run.py +c656d7181745030debfcbed07fb5c05ed59ebd08f4fa9b980b58857ad6ebe896 keel-setup/scripts/fast_first_run.py 856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py 8e33dafefbf5f60214f93a984f86571e2fd4d4266fcf46fcbf1e08fe31a8e13d keel-setup/scripts/setup_state.py @@ -31,14 +31,14 @@ e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scr d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -cb78b2d62beefee4aeea712fdcbabb4e0e633eb17c118e6fdbf06809aaa3b214 keel-setup/tests/test_fast_first_run.py +76f08a63bb9a053c03fc439302b0e15a9235e213582502323cc541a64f69d26e keel-setup/tests/test_fast_first_run.py 62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py 48e55c1043e457873f941c9cf709287b25317553f5dabacb77cc1e2819e54b08 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -51e83b42b8d2b35b5c79e14541bb39ee060991312513105f4d148ad76edf9baf scripts/check_release_bundle.py +a1acef36cc33dc969511eb2f533053ca9d28ca3969a4aff602ab3cb8c1ec6de9 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index f6b5dec..dc9f3fe 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "01cd42d1512af95474bcbb20800c77baacea53ebf5153747e60f5b5f3708345d", + "product_source_sha256": "6752d46d2f807936b0c3639b9af37c6701908df4de0efb1fbc0c865a22c2a76b", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/SKILL.md b/keel-setup/SKILL.md index fd015aa..2fe1012 100644 --- a/keel-setup/SKILL.md +++ b/keel-setup/SKILL.md @@ -217,10 +217,10 @@ inspect bundle history, run the release verifier separately, rediscover the seam contract, regenerate the integration, handle setup state separately, rerun the scanner, repeat validation or tests, or add intermediate narration on a recognized golden path. -When the result is `ready_for_human`, review the bounded unified diff carried in its `diff` result. If -`diff_truncated` is `false`, do not rerun `git diff`. If it is `true`, run exactly one targeted -`git diff` over `validation.changed_paths` before the gate. Do not remove this independent narrow-diff -review. Render the canonical First human gate block verbatim, substituting only the helper-established +When the result is `ready_for_human`, its `diff` result contains only counts and digests. Inspect one +targeted local `git diff` over `validation.changed_paths` before the gate. Keep source hunks and +literal defaults out of model conversation, stdout reports, and logs. Do not remove this independent +local review. Render the canonical First human gate block verbatim, substituting only the helper-established `PATH`, then wait. The deterministic helper's golden path is OpenAI-only; do not reuse its guided dashboard sequence for another provider. The helper result is source-inspected local preparation only; it is not runtime evidence. diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index c437aa8..a62fa21 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -93,7 +93,11 @@ def public(self) -> dict[str, Any]: "path": self.path.as_posix(), "line": self.line, "symbol": self.symbol, - "callable_signature": self.signature, + "callable_signature": {"parameters": [ + {"name": item["name"], "kind": item["kind"], + "default": {"required": isinstance(item["default"], dict) and item["default"].get("required") is True}} + for item in self.signature["parameters"] + ]}, "provider": "openai", "sdk_shape": GOLDEN_SHAPE, "custom_endpoint": False, @@ -996,10 +1000,10 @@ def build_diff_evidence( *, max_bytes: int = MAX_DIFF_BYTES, ) -> dict[str, Any]: - """Return a bounded, source-only unified diff for the exact changed-path allowlist.""" + """Return metadata only; source and literal values stay in the local checkout.""" - sections: list[str] = [] stats: dict[str, dict[str, int]] = {} + digests: dict[str, dict[str, str]] = {} whitespace_only = 0 for relative_text in sorted(allowed_paths): relative = pathlib.PurePosixPath(relative_text) @@ -1014,33 +1018,13 @@ def build_diff_evidence( insertions, deletions, whitespace = _line_change_stats(before, after) stats[relative_text] = {"insertions": insertions, "deletions": deletions} whitespace_only += whitespace - lines = list( - difflib.unified_diff( - before.splitlines(), - after.splitlines(), - fromfile=f"a/{relative_text}", - tofile=f"b/{relative_text}", - lineterm="", - ) - ) - if lines: - sections.append("\n".join(lines) + "\n") - - full_diff = "".join(sections) - if DIFF_CREDENTIAL_SHAPE.search(full_diff): - raise PipelineFailure("validation_failed", "bounded diff may contain credential material") - encoded = full_diff.encode("utf-8") - truncated = len(encoded) > max_bytes - if truncated: - bounded = encoded[:max_bytes].decode("utf-8", errors="ignore") - else: - bounded = full_diff + digests[relative_text] = {"before_sha256": hashlib.sha256(before.encode()).hexdigest(), + "after_sha256": hashlib.sha256(after.encode()).hexdigest()} return { - "unified_diff": bounded, "per_file": stats, + "digests": digests, "whitespace_only_changed_lines": whitespace_only, - "diff_truncated": truncated, - "max_bytes": max_bytes, + "human_review": "Inspect the changed files with local git diff before approval.", } diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index c216d4f..451c8a8 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -345,7 +345,7 @@ def test_client_none_signature_is_preserved(self): self.assertEqual(result["outcome"], "ready_for_human", result) self.assertEqual(fast.callable_signature(before_fn), fast.callable_signature(after_fn)) client = next(item for item in result["seam"]["callable_signature"]["parameters"] if item["name"] == "client") - self.assertEqual(client, {"name": "client", "kind": "keyword_only", "default": None}) + self.assertEqual(client, {"name": "client", "kind": "keyword_only", "default": {"required": False}}) def test_coupled_protocol_double_is_adapted_and_runtime_test_is_deferred(self): root = self._repo() @@ -495,24 +495,16 @@ def test_virtualenv_tests_do_not_consume_coupled_test_budget(self): self.assertEqual(result["outcome"], "ready_for_human", result) self.assertEqual(result["seam"]["directly_coupled_test"], "tests/test_app.py") - def test_ready_result_emits_exact_bounded_diff_and_stats(self): + def test_ready_result_emits_only_local_review_metadata(self): root = self._repo() result = self._run(root) self.assertEqual(result["outcome"], "ready_for_human", result) evidence = result["diff"] - self.assertFalse(evidence["diff_truncated"]) - self.assertLessEqual(len(evidence["unified_diff"].encode("utf-8")), fast.MAX_DIFF_BYTES) + self.assertNotIn("unified_diff", evidence) self.assertIsInstance(evidence["whitespace_only_changed_lines"], int) - checked = subprocess.run( - ["git", "-C", str(root), "apply", "--check", "--reverse", "-"], - input=evidence["unified_diff"], - capture_output=True, - text=True, - check=False, - ) - self.assertEqual(checked.returncode, 0, checked.stderr) + self.assertEqual(set(evidence["digests"]), set(result["validation"]["changed_paths"])) numstat = _git(root, "diff", "--numstat", "--", *result["validation"]["changed_paths"]) expected = { path: {"insertions": int(insertions), "deletions": int(deletions)} @@ -528,7 +520,7 @@ def test_whitespace_only_changed_line_count_is_exact(self): self.assertEqual((insertions, deletions, whitespace_only), (1, 1, 2)) - def test_oversized_diff_is_explicitly_truncated(self): + def test_large_source_is_never_embedded_in_metadata(self): root = self._repo() result = self._run(root) allowed = set(result["validation"]["changed_paths"]) @@ -546,9 +538,19 @@ def test_oversized_diff_is_explicitly_truncated(self): evidence = fast.build_diff_evidence(root, allowed, originals) - self.assertTrue(evidence["diff_truncated"]) - self.assertLessEqual(len(evidence["unified_diff"].encode("utf-8")), fast.MAX_DIFF_BYTES) - self.assertEqual(evidence["max_bytes"], fast.MAX_DIFF_BYTES) + self.assertNotIn("unified_diff", evidence) + self.assertNotIn("bounded-diff-fixture", json.dumps(evidence)) + self.assertLess(len(json.dumps(evidence)), 4096) + + def test_opaque_source_and_literal_defaults_never_leave_the_checkout(self): + sentinel = "unrecognized-opaque-example-93457" + source = fixtures.GOLDEN_APP.replace("model: str | None = None", f"model: str | None = {sentinel!r}") + source = source.replace("source = text.strip()", f"source = text.strip() # {sentinel}") + root = self._repo(source) + result = self._run(root) + self.assertEqual(result["outcome"], "ready_for_human", result) + self.assertNotIn(sentinel, json.dumps(result)) + self.assertIn(sentinel, (root / "app.py").read_text()) def test_custom_base_url_is_safe_fallback(self): root = self._repo(fixtures.CUSTOM_BASE_URL_APP) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 8f63af8..c5b37be 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "01cd42d1512af95474bcbb20800c77baacea53ebf5153747e60f5b5f3708345d" +PRODUCT_SOURCE_SHA256 = "6752d46d2f807936b0c3639b9af37c6701908df4de0efb1fbc0c865a22c2a76b" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 5250a297eff6cedcfe8427a1bef0e0454fa74071 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:50:20 -0800 Subject: [PATCH 10/22] fix: refuse symlink mutation targets before setup edits Addresses occ_7d65273b5dde96252ad42a0a. Capture, atomic write and rollback use repository-relative no-follow descriptors, preserving dangling links and external targets on refusal. --- SHA256SUMS | 8 +-- SOURCE.json | 2 +- keel-setup/scripts/fast_first_run.py | 87 +++++++++++++++++++++---- keel-setup/tests/test_fast_first_run.py | 21 ++++++ scripts/check_release_bundle.py | 2 +- 5 files changed, 100 insertions(+), 20 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 9934205..86f7c70 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -6175c4b6e2da861e5e4d39ac83c74c8933f3cea6c482ddef6560ef7f07800032 SOURCE.json +f636c14e5c3e41b438f4d922882fa7f5d04220c591930e8cf9b747ac4c62a439 SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -23,7 +23,7 @@ d8e9ec03fefe34aca796a2fed4a4506a43acadff68629ab93e74ed309bcbab67 keel-policy/te 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md 580edac4805c13a2b88b7dde613bf3a388347c9d00c6f9488c1ceb9e593368d3 keel-setup/scripts/authoring_context.py -c656d7181745030debfcbed07fb5c05ed59ebd08f4fa9b980b58857ad6ebe896 keel-setup/scripts/fast_first_run.py +c57825f3ecdcf021a7c154d34641381dba2f4e64dbba9015ae52da1aaf4d2a30 keel-setup/scripts/fast_first_run.py 856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py 8e33dafefbf5f60214f93a984f86571e2fd4d4266fcf46fcbf1e08fe31a8e13d keel-setup/scripts/setup_state.py @@ -31,14 +31,14 @@ e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scr d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -76f08a63bb9a053c03fc439302b0e15a9235e213582502323cc541a64f69d26e keel-setup/tests/test_fast_first_run.py +225707bf1699286a8350e22de4c62a7aa72d08f4dd93f86adaa42e72e85208c3 keel-setup/tests/test_fast_first_run.py 62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py 48e55c1043e457873f941c9cf709287b25317553f5dabacb77cc1e2819e54b08 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -a1acef36cc33dc969511eb2f533053ca9d28ca3969a4aff602ab3cb8c1ec6de9 scripts/check_release_bundle.py +068197410520279b3cbd146ca7772d71cb81f97ac0fd8addd14e215f61f34366 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index dc9f3fe..5c86901 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "6752d46d2f807936b0c3639b9af37c6701908df4de0efb1fbc0c865a22c2a76b", + "product_source_sha256": "bb8f62c2b0c44a58dab79e9512a8a0cbf56171c564508c159d67e3518dae5cd0", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index a62fa21..9b8594c 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -11,6 +11,7 @@ import argparse import ast import collections +import contextlib import difflib import importlib.util import hashlib @@ -918,9 +919,60 @@ def validate_patch( } -def _write(path: pathlib.Path, content: str) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(content, encoding="utf-8") +@contextlib.contextmanager +def _mutation_parent(path: pathlib.Path, repo: pathlib.Path): + relative = path.relative_to(repo) + if not relative.parts or ".." in relative.parts: + raise PipelineFailure("validation_failed", "mutation path escapes the repository") + fd = os.open(repo.resolve(), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for part in relative.parts[:-1]: + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) + os.close(fd) + fd = child + yield fd, relative.name + finally: + os.close(fd) + + +def _read_repo_file(path: pathlib.Path, repo: pathlib.Path) -> bytes | None: + with _mutation_parent(path, repo) as (parent, name): + try: + fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + except FileNotFoundError: + return None + with os.fdopen(fd, "rb") as handle: + info = os.fstat(handle.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_SOURCE_BYTES: + raise PipelineFailure("validation_failed", "mutation target is not a bounded regular file") + raw = handle.read(MAX_SOURCE_BYTES + 1) + if len(raw) > MAX_SOURCE_BYTES: + raise PipelineFailure("validation_failed", "mutation target exceeds its byte limit") + return raw + + +def _write(path: pathlib.Path, content: str, repo: pathlib.Path) -> None: + with _mutation_parent(path, repo) as (parent, name): + # Never truncate through an existing link or modify another hardlink. + try: + info = os.stat(name, dir_fd=parent, follow_symlinks=False) + except FileNotFoundError: + mode = 0o644 + else: + if not stat.S_ISREG(info.st_mode): + raise PipelineFailure("validation_failed", "mutation target must be a nonsymlink regular file") + mode = stat.S_IMODE(info.st_mode) + temporary = f".keel-edit-{os.urandom(16).hex()}" + try: + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode, dir_fd=parent) + with os.fdopen(fd, "wb") as handle: + handle.write(content.encode("utf-8")) + os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent) + finally: + try: + os.unlink(temporary, dir_fd=parent) + except FileNotFoundError: + pass def _ensure_state_ignored(repo: pathlib.Path) -> bool: @@ -928,9 +980,9 @@ def _ensure_state_ignored(repo: pathlib.Path) -> bool: if checked.returncode == 0: return False path = repo / ".gitignore" - existing = path.read_text(encoding="utf-8") if path.exists() else "" + existing = (_read_repo_file(path, repo) or b"").decode("utf-8") suffix = "" if not existing or existing.endswith("\n") else "\n" - _write(path, existing + suffix + ".keel/setup-state.json\n") + _write(path, existing + suffix + ".keel/setup-state.json\n", repo) checked = _run(["git", "-c", "core.fsmonitor=false", "-C", str(repo), "check-ignore", "-q", ".keel/setup-state.json"], cwd=repo) if checked.returncode != 0: raise PipelineFailure("validation_failed", "local setup state could not be git-ignored") @@ -941,12 +993,19 @@ def _restore(repo: pathlib.Path, originals: dict[pathlib.PurePosixPath, bytes | for relative, content in originals.items(): path = repo.joinpath(*relative.parts) if content is None: - path.unlink(missing_ok=True) + with _mutation_parent(path, repo) as (parent, name): + try: + os.unlink(name, dir_fd=parent) + except FileNotFoundError: + pass else: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(content) + _write(path, content.decode("utf-8"), repo) state = repo / ".keel" / "setup-state.json" - state.unlink(missing_ok=True) + try: + with _mutation_parent(state, repo) as (parent, name): + os.unlink(name, dir_fd=parent) + except FileNotFoundError: + pass try: state.parent.rmdir() except OSError: @@ -1053,20 +1112,20 @@ def run_pipeline(bundle: pathlib.Path, bundle_sha: str, repo: pathlib.Path) -> d app_path = repo.joinpath(*seam.path.parts) app_before = app_path.read_text(encoding="utf-8") - originals[seam.path] = app_path.read_bytes() + originals[seam.path] = _read_repo_file(app_path, repo) if seam.coupled_test: test_path = repo.joinpath(*seam.coupled_test.parts) - originals[seam.coupled_test] = test_path.read_bytes() + originals[seam.coupled_test] = _read_repo_file(test_path, repo) ignore_relative = pathlib.PurePosixPath(".gitignore") ignore_path = repo / ".gitignore" - originals[ignore_relative] = ignore_path.read_bytes() if ignore_path.exists() else None + originals[ignore_relative] = _read_repo_file(ignore_path, repo) mark = time.perf_counter() app_after, test_after = generate_adapter(repo, seam) edited = True - _write(app_path, app_after) + _write(app_path, app_after, repo) if seam.coupled_test and test_after is not None: - _write(repo.joinpath(*seam.coupled_test.parts), test_after) + _write(repo.joinpath(*seam.coupled_test.parts), test_after, repo) ignore_changed = _ensure_state_ignored(repo) timings["adapter_generation_ms"] = round((time.perf_counter() - mark) * 1000, 3) diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index 451c8a8..8ef2b30 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -347,6 +347,27 @@ def test_client_none_signature_is_preserved(self): client = next(item for item in result["seam"]["callable_signature"]["parameters"] if item["name"] == "client") self.assertEqual(client, {"name": "client", "kind": "keyword_only", "default": {"required": False}}) + def test_dangling_gitignore_is_refused_without_external_write_or_link_removal(self): + for existing in (False, True): + root = self._repo() + with tempfile.TemporaryDirectory() as outside: + destination = pathlib.Path(outside) / "target" + if existing: + destination.write_text("preserve") + ignore = root / ".gitignore" + ignore.unlink() + ignore.symlink_to(destination) + _git(root, "add", ".gitignore") + _git(root, "commit", "-qm", "symlink fixture") + before = (root / "app.py").read_bytes() + result = self._run(root) + self.assertEqual(result["outcome"], "validation_failed", result) + self.assertTrue(ignore.is_symlink()) + self.assertEqual(destination.exists(), existing) + if existing: + self.assertEqual(destination.read_text(), "preserve") + self.assertEqual((root / "app.py").read_bytes(), before) + def test_coupled_protocol_double_is_adapted_and_runtime_test_is_deferred(self): root = self._repo() result = self._run(root) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index c5b37be..e5cca2c 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "6752d46d2f807936b0c3639b9af37c6701908df4de0efb1fbc0c865a22c2a76b" +PRODUCT_SOURCE_SHA256 = "bb8f62c2b0c44a58dab79e9512a8a0cbf56171c564508c159d67e3518dae5cd0" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 382cb65ecf38943b5a1f9e8899225f6a4cf4eea7 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:50:20 -0800 Subject: [PATCH 11/22] fix: reject executable caches in fallback release verification Addresses surviving fallback route of occ_07e8280451318d9bf87c5c7c; isolated Python and disabled cache writes do not prevent reading existing bytecode. --- SHA256SUMS | 6 +++--- SOURCE.json | 2 +- keel-setup/tests/test_fast_first_run.py | 15 +++++++++++++++ scripts/check_release_bundle.py | 10 ++++++---- 4 files changed, 25 insertions(+), 8 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 86f7c70..d44af3e 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -f636c14e5c3e41b438f4d922882fa7f5d04220c591930e8cf9b747ac4c62a439 SOURCE.json +39decb96a10054b84366f739301d981906a028d33cc6b513c1b3a9e1ad5fd090 SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -31,14 +31,14 @@ e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scr d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -225707bf1699286a8350e22de4c62a7aa72d08f4dd93f86adaa42e72e85208c3 keel-setup/tests/test_fast_first_run.py +869fb1e5a18e7c10dddb9414c7fa928971d8b0ecaff7382ae39effc7f6ae99d5 keel-setup/tests/test_fast_first_run.py 62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py 48e55c1043e457873f941c9cf709287b25317553f5dabacb77cc1e2819e54b08 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -068197410520279b3cbd146ca7772d71cb81f97ac0fd8addd14e215f61f34366 scripts/check_release_bundle.py +18a10abb4612a1dd742de10e2d6619f6eca10173a4c73ab192fdc49e4ae81922 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index 5c86901..a59d518 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "bb8f62c2b0c44a58dab79e9512a8a0cbf56171c564508c159d67e3518dae5cd0", + "product_source_sha256": "ce0c7e1e0affcfb30497fab2762e1901ec7f78830b70209b9709a9b88c42e85c", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index 8ef2b30..07caf19 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -41,6 +41,21 @@ def _git(root: pathlib.Path, *args: str) -> str: class DeterministicFastFirstRunTest(unittest.TestCase): + def test_fallback_release_checker_rejects_bytecode_and_cache_entries(self): + checker = _load("fallback_bundle_check", ROOT / "scripts/check_release_bundle.py") + for relative in ("shared/scripts/__pycache__/schema_validation.pyc", "shared/scripts/schema_validation.pyc", + "shared/scripts/__pycache__"): + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + if path.name == "__pycache__": + path.mkdir() + else: + path.write_bytes(b"unmeasured executable cache") + with mock.patch.object(checker, "ROOT", root), self.assertRaisesRegex(ValueError, "caches"): + checker._files() + @classmethod def setUpClass(cls) -> None: cls.bundle_temp = tempfile.TemporaryDirectory() diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index e5cca2c..0f55c8f 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "bb8f62c2b0c44a58dab79e9512a8a0cbf56171c564508c159d67e3518dae5cd0" +PRODUCT_SOURCE_SHA256 = "ce0c7e1e0affcfb30497fab2762e1901ec7f78830b70209b9709a9b88c42e85c" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", @@ -88,12 +88,14 @@ def _files() -> set[str]: result: set[str] = set() for path in ROOT.rglob("*"): - if not path.is_file() or ".git" in path.parts or "__pycache__" in path.parts: - continue - if ".pytest_cache" in path.parts: + if ".git" in path.relative_to(ROOT).parts: continue + if path.name in {"__pycache__", ".pytest_cache"} or path.suffix in {".pyc", ".pyo"}: + raise ValueError("executable caches are not allowed in the release bundle") if path.is_symlink(): raise ValueError(f"symlink is not allowed in the release bundle: {path}") + if not path.is_file(): + continue result.add(path.relative_to(ROOT).as_posix()) return result From 7897ca1ded24b1d00e57f9ee85786e61b819966f Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:52:14 -0800 Subject: [PATCH 12/22] fix: refuse transformations that could discard unrecognized logic Addresses occ_6041c49e8b17de0c7884651d. Require exact adjacent provider AST nodes and the exact published coupled-test fixture before whole-file migration. --- SHA256SUMS | 8 ++++---- SOURCE.json | 2 +- keel-setup/scripts/fast_first_run.py | 12 +++++++++++- keel-setup/tests/test_fast_first_run.py | 22 ++++++++++++++++++++++ scripts/check_release_bundle.py | 2 +- 5 files changed, 39 insertions(+), 7 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index d44af3e..d6b030c 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -39decb96a10054b84366f739301d981906a028d33cc6b513c1b3a9e1ad5fd090 SOURCE.json +c0eb7c4dc5d0d347edfd2830c3686e8fd789046506fca08060faaaff7db910a9 SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -23,7 +23,7 @@ d8e9ec03fefe34aca796a2fed4a4506a43acadff68629ab93e74ed309bcbab67 keel-policy/te 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md 580edac4805c13a2b88b7dde613bf3a388347c9d00c6f9488c1ceb9e593368d3 keel-setup/scripts/authoring_context.py -c57825f3ecdcf021a7c154d34641381dba2f4e64dbba9015ae52da1aaf4d2a30 keel-setup/scripts/fast_first_run.py +0e07379a920870ce7b9e9786ef62ef0feb5e9eff7883a300401a8b381fd6ae58 keel-setup/scripts/fast_first_run.py 856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py 8e33dafefbf5f60214f93a984f86571e2fd4d4266fcf46fcbf1e08fe31a8e13d keel-setup/scripts/setup_state.py @@ -31,14 +31,14 @@ e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scr d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -869fb1e5a18e7c10dddb9414c7fa928971d8b0ecaff7382ae39effc7f6ae99d5 keel-setup/tests/test_fast_first_run.py +953149f85bb446dd622f2d5e4bed57c8b9c58143e68676f60078085f2b008b43 keel-setup/tests/test_fast_first_run.py 62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py 48e55c1043e457873f941c9cf709287b25317553f5dabacb77cc1e2819e54b08 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -18a10abb4612a1dd742de10e2d6619f6eca10173a4c73ab192fdc49e4ae81922 scripts/check_release_bundle.py +7277ea3da785743a557f7e6519e40075f62476b9cf4550b6f61839bc1fec0101 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index a59d518..715426a 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "ce0c7e1e0affcfb30497fab2762e1901ec7f78830b70209b9709a9b88c42e85c", + "product_source_sha256": "8eb606514f426005843af1913d0f736a689d7a6ba72b983d3507fa1bf4afbb4f", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index 9b8594c..824dfb9 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -541,7 +541,7 @@ def discover_golden_seam(repo: pathlib.Path, inventory: Any) -> GoldenSeam: if _attribute_name(call.func) != "client.responses.create": raise PipelineFailure("model_review_required", "Responses call receiver is an unrecognized wrapper") keywords = {keyword.arg: keyword.value for keyword in call.keywords if keyword.arg is not None} - if set(keywords) != {"model", "instructions", "input"} or call.args: + if set(keywords) != {"model", "instructions", "input"} or call.args or len(call.keywords) != 3: raise PipelineFailure("model_review_required", "Responses request arguments do not match the golden shape") try: instructions = ast.literal_eval(keywords["instructions"]) @@ -574,6 +574,12 @@ def discover_golden_seam(repo: pathlib.Path, inventory: Any) -> GoldenSeam: raise PipelineFailure("model_review_required", "provider construction and response mapping do not match the golden shape") if response_name != "response" or summary_name != "summary": raise PipelineFailure("model_review_required", "response variable shape is not recognized") + expected_constructor = ast.parse("if client is None:\n from openai import OpenAI\n client = OpenAI()\n").body[0] + expected_mapping = ast.parse("summary = response.output_text.strip()\n").body[0] + if (response_index != client_if_index + 1 or summary_index != response_index + 1 + or ast.dump(function.body[client_if_index]) != ast.dump(expected_constructor) + or ast.dump(function.body[summary_index]) != ast.dump(expected_mapping)): + raise PipelineFailure("model_review_required", "provider replacement contains additional or unrecognized logic") constructor_calls = [node for node in ast.walk(function.body[client_if_index]) if isinstance(node, ast.Call) and _attribute_name(node.func) == "OpenAI"] if len(constructor_calls) != 1 or constructor_calls[0].args or constructor_calls[0].keywords: raise PipelineFailure("unsupported_shape", "OpenAI client is not using the default official endpoint") @@ -748,6 +754,10 @@ def _generate_coupled_test(repo: pathlib.Path, seam: GoldenSeam) -> str: assert seam.coupled_test is not None path = repo.joinpath(*seam.coupled_test.parts) original = path.read_text(encoding="utf-8") + # This whole-file migration is authorized only for the exact published + # fixture. Any additional test, fixture, hook, or comment requires review. + if hashlib.sha256(original.encode("utf-8")).hexdigest() != "bdb7e770dfe505e3efab6e6852afb70b88b38b2b6222cb451aacf25bef29592b": + raise PipelineFailure("model_review_required", "coupled tests differ from the exact supported fixture") required = ( "class FakeResponses", "class FakeClient", "class SummarizerTests", "test_sends_text_to_the_selected_model", "test_rejects_empty_text_before_calling_the_provider", diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index 07caf19..f00fa0b 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -502,6 +502,28 @@ def test_retained_if_else_block_is_copied_verbatim_and_compiles(self): self.assertIn(retained, after) compile(after, "app.py", "exec") + def test_unrecognized_security_logic_and_extra_tests_are_preserved_by_refusal(self): + for source in ( + fixtures.GOLDEN_APP.replace(" summary = response.output_text.strip()", " audit_request()\n summary = response.output_text.strip()"), + fixtures.GOLDEN_APP.replace(" client = OpenAI()", " authorize_user()\n client = OpenAI()"), + fixtures.GOLDEN_APP.replace(" response = client.responses.create(", " authorize_user()\n response = client.responses.create("), + ): + root = self._repo(source) + result = self._run(root) + self.assertEqual(result["outcome"], "model_review_required", result) + self.assertEqual((root / "app.py").read_text(), source) + self.assertEqual(_git(root, "status", "--porcelain"), "") + root = self._repo() + path = root / "tests/test_app.py" + source = path.read_text() + "\ndef test_extra_authorization():\n assert authorized()\n" + path.write_text(source) + _git(root, "add", ".") + _git(root, "commit", "-qm", "extra test") + result = self._run(root) + self.assertEqual(result["outcome"], "model_review_required", result) + self.assertEqual(path.read_text(), source) + self.assertEqual(_git(root, "status", "--porcelain"), "") + def test_retained_try_except_block_is_copied_verbatim_and_compiles(self): root = self._repo(fixtures.RETAINED_TRY_EXCEPT_APP) retained = ''' try: diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 0f55c8f..74b6ac9 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "ce0c7e1e0affcfb30497fab2762e1901ec7f78830b70209b9709a9b88c42e85c" +PRODUCT_SOURCE_SHA256 = "8eb606514f426005843af1913d0f736a689d7a6ba72b983d3507fa1bf4afbb4f" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From e2decca7477f00e3cffe03210e6f7f0b944a105a Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:52:15 -0800 Subject: [PATCH 13/22] fix: revalidate prepared state against HEAD and every current change Addresses occ_9f0022cd1aa84bf3e56ec4d5. Refuse stale or clean forged milestones, recompile Python source without imports, and inspect all recorded paths. --- SHA256SUMS | 8 ++--- SOURCE.json | 2 +- keel-setup/scripts/setup_state.py | 42 +++++++++++++++++++---- keel-setup/tests/test_setup_state.py | 51 ++++++++++++++++++++++++++-- scripts/check_release_bundle.py | 2 +- 5 files changed, 90 insertions(+), 15 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index d6b030c..0e5fbc5 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -c0eb7c4dc5d0d347edfd2830c3686e8fd789046506fca08060faaaff7db910a9 SOURCE.json +41d8edf2ce9817a3edde84f6606700d08e4a62eb2d69598a0def7fefc4b2fa73 SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -26,7 +26,7 @@ c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/ref 0e07379a920870ce7b9e9786ef62ef0feb5e9eff7883a300401a8b381fd6ae58 keel-setup/scripts/fast_first_run.py 856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py -8e33dafefbf5f60214f93a984f86571e2fd4d4266fcf46fcbf1e08fe31a8e13d keel-setup/scripts/setup_state.py +1502ef6a29d2f70984401e322aa39b5c2695c551e8856e59af7ab350f12ca0dd keel-setup/scripts/setup_state.py 1bc3d136fe06414a090976712c96fef0f46d7922ed3cd5cf502fa174de1aa86d keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py @@ -35,10 +35,10 @@ a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tes 62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py -48e55c1043e457873f941c9cf709287b25317553f5dabacb77cc1e2819e54b08 keel-setup/tests/test_setup_state.py +69cb006cff321b6bb47db4ff0ec42ec6e8f0be2ab624e94b97473add50c26422 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -7277ea3da785743a557f7e6519e40075f62476b9cf4550b6f61839bc1fec0101 scripts/check_release_bundle.py +ee71c4ae55d763f08ed3fc4f9edd15ccfaf97227fae793ab499e4ed0f5f5ad6c scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index 715426a..f5224c0 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "8eb606514f426005843af1913d0f736a689d7a6ba72b983d3507fa1bf4afbb4f", + "product_source_sha256": "0c8d72a1377a2f7eadcfac9faf8d47ddeaea38ceee6902d613c7ccdaca609939", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/setup_state.py b/keel-setup/scripts/setup_state.py index 8f0dc7c..b888b95 100644 --- a/keel-setup/scripts/setup_state.py +++ b/keel-setup/scripts/setup_state.py @@ -208,7 +208,7 @@ def validate_prepared_paths( state: Any, repo_root: pathlib.Path, *, - require_worktree_change: bool = False, + require_worktree_change: bool = True, ) -> list[str]: """Validate the local files underlying a resumable first-human-gate milestone.""" @@ -220,6 +220,9 @@ def validate_prepared_paths( failures: list[str] = [] root = repo_root.resolve() + revision = current_revision(root) + if revision is None or state.get("application_revision") != revision: + failures.append("prepared application revision does not match current HEAD") integration_marker_found = False for index, raw_path in enumerate(changed_paths): if not isinstance(raw_path, str): @@ -269,16 +272,42 @@ def validate_prepared_paths( if lowered_parts & NON_PRODUCTION_PATH_PARTS or test_filename: continue try: - integration_marker_found = b"/v1/execute" in resolved.read_bytes() - except OSError: + raw = _read_bounded_repository_source(candidate, root) + if resolved.suffix.lower() == ".py": + compile(raw, relative.as_posix(), "exec") + if b"/v1/proxy/" in raw or re.search(rb"(?:from|import)\s+(?:openai|anthropic)\b|\.responses\.create\s*\(", raw): + failures.append(f"changed_paths[{index}] retains a direct provider or proxy path") + integration_marker_found = integration_marker_found or b"/v1/execute" in raw + except (OSError, ValueError, SyntaxError): failures.append(f"changed_paths[{index}] could not be inspected") - if integration_marker_found: - break if not integration_marker_found: failures.append("changed paths do not contain a prepared /v1/execute integration") return failures +def current_revision(root: pathlib.Path) -> str | None: + try: + result = subprocess.run(["git", "--no-replace-objects", "-c", "core.fsmonitor=false", "-C", str(root), + "rev-parse", "HEAD"], capture_output=True, text=True, timeout=5, check=True) + except (OSError, subprocess.SubprocessError): + return None + value = result.stdout.strip() + return value if re.fullmatch(r"[0-9a-f]{40}", value) else None + + +def _read_bounded_repository_source(path: pathlib.Path, root: pathlib.Path) -> bytes: + with _state_parent(path, root) as (parent, name): + fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size > 1_000_000: + raise ValueError("prepared source must be a bounded regular file") + raw = stream.read(1_000_001) + if len(raw) > 1_000_000: + raise ValueError("prepared source exceeds its byte limit") + return raw + + def due_reviews( invocation_count: int, last_drift_audit: int | None = None, @@ -597,8 +626,7 @@ def mark_waiting_for_human( "updated_at": _utc_now(), } ) - if application_revision is not None: - updated["application_revision"] = application_revision + updated["application_revision"] = application_revision or current_revision(repo_root) failures = validate_state(updated) failures.extend(validate_prepared_paths(updated, repo_root, require_worktree_change=True)) if failures: diff --git a/keel-setup/tests/test_setup_state.py b/keel-setup/tests/test_setup_state.py index ea93494..9f8de31 100644 --- a/keel-setup/tests/test_setup_state.py +++ b/keel-setup/tests/test_setup_state.py @@ -226,11 +226,43 @@ def test_stage_selects_earliest_unmet_phase(self): class BeginTest(unittest.TestCase): + def test_clean_or_stale_preparation_cannot_resume_the_human_gate(self): + for stale in (False, True): + with tempfile.TemporaryDirectory() as directory: + root = self._repo(directory) + source = root / "service.py" + _write_prepared(source) + revision = setup_state.current_revision(root) + if stale: + subprocess.run(["git", "-C", str(root), "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "--allow-empty", "-qm", "new head"], check=True, capture_output=True) + else: + subprocess.run(["git", "-C", str(root), "add", "service.py"], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "-qm", "existing route"], check=True, capture_output=True) + revision = setup_state.current_revision(root) + path = root / ".keel/setup-state.json" + path.write_text(json.dumps(_waiting_state(application_revision=revision))) + result = setup_state.begin(path, root) + self.assertEqual(result["continuity"], "lost", result) + self.assertEqual(result["stage"], "discovery") + + def test_every_recorded_path_is_checked_after_the_first_integration_marker(self): + with tempfile.TemporaryDirectory() as directory: + root = self._repo(directory) + _write_prepared(root / "service.py") + state = _waiting_state(application_revision=setup_state.current_revision(root), + changed_paths=["service.py", "missing.py"]) + self.assertTrue(any("does not exist" in error for error in setup_state.validate_prepared_paths(state, root))) + def _repo(self, directory: str) -> pathlib.Path: root = pathlib.Path(directory) (root / ".keel").mkdir() (root / ".gitignore").write_text(".keel/\n") subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "add", "."], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "--allow-empty", "-qm", "baseline"], check=True, capture_output=True) return root def test_missing_file_reports_lost_continuity_and_starts_at_one(self): @@ -294,7 +326,7 @@ def test_waiting_state_resumes_gate_without_first_run_or_drift_work(self): root = self._repo(directory) path = root / ".keel" / "setup-state.json" _write_prepared(root / "service.py") - path.write_text(json.dumps(_waiting_state(invocation_count=19))) + path.write_text(json.dumps(_waiting_state(invocation_count=19, application_revision=setup_state.current_revision(root)))) report = setup_state.begin(path, root) self.assertEqual(report["next_phase"], "first_human_gate") self.assertEqual(report["due"], ["resume_earliest_unmet_milestone"]) @@ -315,7 +347,7 @@ def test_mark_human_gate_persists_only_local_preparation_and_resumes_it(self): root, provider="openai", pinned_skill_ref="a" * 40, - application_revision="b" * 40, + application_revision=setup_state.current_revision(root), changed_paths=["service.py", "tests/test_service.py"], focused_checks=_focused_checks(), ) @@ -532,6 +564,9 @@ def test_untracked_ignore_status_is_reported(self): root = pathlib.Path(directory) (root / ".keel").mkdir() subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "add", "."], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "--allow-empty", "-qm", "baseline"], check=True, capture_output=True) path = root / ".keel" / "setup-state.json" path.write_text(json.dumps(_valid())) report = setup_state.begin(path, root) @@ -548,6 +583,9 @@ def test_main_persists_each_successful_invocation(self): (root / ".keel").mkdir() (root / ".gitignore").write_text(".keel/\n") subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "add", "."], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "--allow-empty", "-qm", "baseline"], check=True, capture_output=True) path = root / ".keel" / "setup-state.json" reports = [] for _ in range(2): @@ -565,6 +603,9 @@ def test_unignored_state_path_exits_nonzero(self): root = pathlib.Path(directory) (root / ".keel").mkdir() subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "add", "."], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "--allow-empty", "-qm", "baseline"], check=True, capture_output=True) path = root / ".keel" / "setup-state.json" path.write_text(json.dumps(_valid())) with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): @@ -577,6 +618,9 @@ def test_write_failure_exits_nonzero_without_claiming_persistence(self): (root / ".keel").mkdir() (root / ".gitignore").write_text(".keel/\n") subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "add", "."], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "--allow-empty", "-qm", "baseline"], check=True, capture_output=True) path = root / ".keel" / "setup-state.json" with ( mock.patch.object( @@ -618,6 +662,9 @@ def test_mark_human_gate_cli_requires_preparation_and_focused_checks(self): (root / ".keel").mkdir() (root / ".gitignore").write_text(".keel/\n") subprocess.run(["git", "init", "-q", str(root)], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "add", "."], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "--allow-empty", "-qm", "baseline"], check=True, capture_output=True) path = root / ".keel" / "setup-state.json" _write_prepared(root / "service.py") setup_state.begin(path, root) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 74b6ac9..27a875b 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "8eb606514f426005843af1913d0f736a689d7a6ba72b983d3507fa1bf4afbb4f" +PRODUCT_SOURCE_SHA256 = "0c8d72a1377a2f7eadcfac9faf8d47ddeaea38ceee6902d613c7ccdaca609939" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 68bc43ed96baf9a6f620197184742f44806c8b3b Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:54:52 -0800 Subject: [PATCH 14/22] fix: validate implicit action facts and fail closed on unpublished capabilities Addresses remaining semantics of occ_4fe6e63cc832a1b2e5f6c542. Model/request-cost facts require unique trusted managed-execute evidence; other runtime-dependent actions remain unqualified without a pinned contract. --- SHA256SUMS | 8 ++--- SOURCE.json | 2 +- .../scripts/validate_enforceability_report.py | 29 +++++++++++++++++++ .../test_validate_enforceability_report.py | 11 +++++++ scripts/check_release_bundle.py | 2 +- 5 files changed, 46 insertions(+), 6 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 0e5fbc5..6699f81 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -41d8edf2ce9817a3edde84f6606700d08e4a62eb2d69598a0def7fefc4b2fa73 SOURCE.json +4b38ffe509d26d57778d932f62ebce830e5edd1cfd76cf90917fbbe1ef988b1e SOURCE.json 75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -12,10 +12,10 @@ b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 54416bf9c9af8f8fb75a9e883aa27aa62ecbcdffc2b1b6698d5fa1479fd6ddda keel-policy/reference/fields.md 5d4e384a5c0047b951569ce8e0956eeef7f233f736adea08c56c5d7f4575c138 keel-policy/reference/policy-document.schema.json 7d662cffa24744af7a26f62d813127b4bc0a44ff62f725c883054165ddec3272 keel-policy/scripts/consume_authoring_context.py -ebf42588e3aaf8f0a4060567b916bf6eeb06de254564ab0b6806dffc169ec877 keel-policy/scripts/validate_enforceability_report.py +715f8ed79a50510a89f23bd3480e1b4e591f5fcbb7cb7211c5e59bf19e830d82 keel-policy/scripts/validate_enforceability_report.py b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb keel-policy/tests/test_authoring_context_consumption.py 820069a6ce02f74dccc4f57a5788359b1377520330d00ba88471d60fec901f17 keel-policy/tests/test_basic_profile_fields.py -d8e9ec03fefe34aca796a2fed4a4506a43acadff68629ab93e74ed309bcbab67 keel-policy/tests/test_validate_enforceability_report.py +5c048ae47dcdbec3f593de75e9aaa7f5446418badea6f5fb7698141c40d2b2d2 keel-policy/tests/test_validate_enforceability_report.py 383d08c6433e906b3082a9346f81bbc429b08b8124fd00a38ec3bbb9d44d56b4 keel-setup/SKILL.md 2b9c2490e921e83b83372a09e422a30f0f7ee338a2809b8e07edbd381d9eb650 keel-setup/reference/coverage.schema.json 70a69dcab29f61aaa3f96de5f65854fca63c4549ddc20d84ee00e102fc68c691 keel-setup/reference/integration_profiles.v1.json @@ -38,7 +38,7 @@ af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tes 69cb006cff321b6bb47db4ff0ec42ec6e8f0be2ab624e94b97473add50c26422 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -ee71c4ae55d763f08ed3fc4f9edd15ccfaf97227fae793ab499e4ed0f5f5ad6c scripts/check_release_bundle.py +20d16bc01cd209c8c2181c5cb506ae4cc33ddb4f5f73c5a3a0b2c665dce55c13 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index f5224c0..d21c491 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "0c8d72a1377a2f7eadcfac9faf8d47ddeaea38ceee6902d613c7ccdaca609939", + "product_source_sha256": "f098aadb088cb63811b0b716fb4cde319215009da84981bcefb959a59f62d1ca", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-policy/scripts/validate_enforceability_report.py b/keel-policy/scripts/validate_enforceability_report.py index 0faf473..3e80ca1 100644 --- a/keel-policy/scripts/validate_enforceability_report.py +++ b/keel-policy/scripts/validate_enforceability_report.py @@ -21,6 +21,26 @@ BOUND_TOOL_NAME = "context._keel.action_envelope.connector.tool_name.value" PROHIBITED_KEYS = {"certified_action_contract_id", "activation", "is_active", "credential", "api_key", "token"} NON_EFFECTING_ACTIONS = {"preview"} +ACTION_DEPENDENCIES: dict[str, tuple[str, ...] | None] = { + "allow": (), "deny": (), "preview": (), "require_human_review": (), + "constrain_max_output_tokens": (), "constrain_permit_lifetime": (), + "deny_if_model_not_in": ("model",), + "deny_if_cost_exceeds": ("estimated_cost_usd_micros", "context._keel.action_envelope.pricing.estimated_cost_usd_micros.state"), + # These handlers consume runtime capabilities/facts for which this bundle + # publishes no independently trusted offline evidence contract. + "deny_if_rate_exceeds": None, "throttle_if_rate_exceeds": None, + "deny_if_spike_detected": None, "deny_if_projected_monthly_ratio_exceeds": None, + "require_budget_envelope": None, "constrain_permit_target": None, + "constrain_work_authority": None, +} + + +def _action_dependencies(rule: dict[str, Any]) -> tuple[str, ...] | None: + action = rule.get("action") + params = rule.get("params") + if action == "deny_if_cost_exceeds" and (not isinstance(params, dict) or params.get("window") != "request"): + return None # Window spend is not a published field/capability contract. + return ACTION_DEPENDENCIES.get(action) def _walk(value: Any): @@ -62,6 +82,8 @@ def validate( failures.append(f"prohibited authority or certified-contract field: {key}") public_fields = set(manifest.get("fields", {}).get("PUBLIC", [])) + if set(ACTION_DEPENDENCIES) != set(manifest.get("actions", {}).get("PUBLIC", [])): + failures.append("action semantics table does not exactly cover the public action set") provenance = provenance_artifact.get("fields", {}) if isinstance(provenance_artifact, dict) else {} if provenance_artifact.get("schema_version") != "1.0" or set(provenance) != public_fields: failures.append("pinned field-provenance artifact does not exactly cover the published field set") @@ -105,6 +127,11 @@ def validate( fields = _condition_fields(rule.get("if")) if rule.get("action") not in NON_EFFECTING_ACTIONS and not fields: failures.append(f"policy.rules[{rule_index}] automatic action requires a trusted condition leaf") + dependencies = _action_dependencies(rule) + if dependencies is None: + failures.append(f"policy.rules[{rule_index}] implicit runtime facts/capabilities have no pinned trusted evidence contract") + dependencies = () + fields = sorted(set(fields) | set(dependencies)) for field in fields: matching = by_field.get(field, []) if not matching: @@ -118,6 +145,8 @@ def validate( failures.append( f"policy.rules[{rule_index}] automatic action uses field {field!r} without independently trusted enforceability[{entry_index}]" ) + if field in dependencies and item.get("surface") != "managed_execute": + failures.append(f"policy.rules[{rule_index}] implicit field {field!r} requires the managed_execute surface") return failures diff --git a/keel-policy/tests/test_validate_enforceability_report.py b/keel-policy/tests/test_validate_enforceability_report.py index 600b8b9..01058e6 100644 --- a/keel-policy/tests/test_validate_enforceability_report.py +++ b/keel-policy/tests/test_validate_enforceability_report.py @@ -47,6 +47,17 @@ def add_policy(candidate, field, action="allow"): class EnforceabilityValidatorTest(unittest.TestCase): + def test_implicit_action_facts_cannot_be_omitted_or_downgraded(self): + candidate = add_policy(report(field="provider", status="trusted", replacement=None), "provider", "deny_if_model_not_in") + candidate["policy"]["rules"][0]["params"] = {"allowed": ["example-model"]} + self.assertTrue(any("model" in error and "no enforceability" in error for error in validate(candidate))) + for action in ("deny_if_rate_exceeds", "throttle_if_rate_exceeds", "deny_if_spike_detected", + "deny_if_projected_monthly_ratio_exceeds", "require_budget_envelope"): + candidate["policy"]["rules"][0]["action"] = action + self.assertTrue(any("no pinned trusted evidence" in error for error in validate(candidate)), action) + candidate["policy"]["rules"][0].update(action="deny_if_cost_exceeds", params={"window": "request", "cap_micros": 100}) + self.assertTrue(any("estimated_cost_usd_micros" in error for error in validate(candidate))) + def test_empty_compounds_cannot_drive_automatic_actions_at_any_depth(self): for condition in ({"all": []}, {"any": []}, {"not": {"all": []}}, {"all": [{"field": "provider", "op": "eq", "value": "openai"}, {"any": []}]}): diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 27a875b..de27d59 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "0c8d72a1377a2f7eadcfac9faf8d47ddeaea38ceee6902d613c7ccdaca609939" +PRODUCT_SOURCE_SHA256 = "f098aadb088cb63811b0b716fb4cde319215009da84981bcefb959a59f62d1ca" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From b4b6520800c9d938d048253e0eafcc5c59833f95 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:56:15 -0800 Subject: [PATCH 15/22] fix: bind enforceability evidence and readback to exact policy rules Addresses occ_92557ebfea9c4d5153638ccc. Require precise per-rule facts and action outcomes, canonical structural readback, and unresolved activation effects without an active-policy baseline. --- SHA256SUMS | 12 ++--- SOURCE.json | 2 +- keel-policy/SKILL.md | 10 +++- .../scripts/validate_enforceability_report.py | 47 +++++++++++++++++-- .../test_authoring_context_consumption.py | 8 ++-- .../test_validate_enforceability_report.py | 29 +++++++++++- scripts/check_release_bundle.py | 2 +- 7 files changed, 93 insertions(+), 17 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 6699f81..9a7bec2 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,8 +2,8 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -4b38ffe509d26d57778d932f62ebce830e5edd1cfd76cf90917fbbe1ef988b1e SOURCE.json -75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md +7e654ae9b125252208070c9f8336a02e14f37065926cb76039b503a5381a1cfc SOURCE.json +1edad0b7e0dcc065d5eca7dcca9ad7218824f62346fe6233e09a8110a9663746 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json 2a52514e8db0901ab73e59b924f195008541d0069ebad9b514bd373cb905e2d2 keel-policy/examples/stripe-refund-approval.json @@ -12,10 +12,10 @@ b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 54416bf9c9af8f8fb75a9e883aa27aa62ecbcdffc2b1b6698d5fa1479fd6ddda keel-policy/reference/fields.md 5d4e384a5c0047b951569ce8e0956eeef7f233f736adea08c56c5d7f4575c138 keel-policy/reference/policy-document.schema.json 7d662cffa24744af7a26f62d813127b4bc0a44ff62f725c883054165ddec3272 keel-policy/scripts/consume_authoring_context.py -715f8ed79a50510a89f23bd3480e1b4e591f5fcbb7cb7211c5e59bf19e830d82 keel-policy/scripts/validate_enforceability_report.py -b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb keel-policy/tests/test_authoring_context_consumption.py +4dfdfbf56fb811a565e5f3c9f28ec3ff137303148fa13a8d29a979ffb95e2d96 keel-policy/scripts/validate_enforceability_report.py +6da76e3ac418a133894d498e0d2afa97b91036a72097f077b9853f6447f6d912 keel-policy/tests/test_authoring_context_consumption.py 820069a6ce02f74dccc4f57a5788359b1377520330d00ba88471d60fec901f17 keel-policy/tests/test_basic_profile_fields.py -5c048ae47dcdbec3f593de75e9aaa7f5446418badea6f5fb7698141c40d2b2d2 keel-policy/tests/test_validate_enforceability_report.py +607da38ca6191c555bfcf5d8e595a845b605ed106180e293b3d5669f9bc41800 keel-policy/tests/test_validate_enforceability_report.py 383d08c6433e906b3082a9346f81bbc429b08b8124fd00a38ec3bbb9d44d56b4 keel-setup/SKILL.md 2b9c2490e921e83b83372a09e422a30f0f7ee338a2809b8e07edbd381d9eb650 keel-setup/reference/coverage.schema.json 70a69dcab29f61aaa3f96de5f65854fca63c4549ddc20d84ee00e102fc68c691 keel-setup/reference/integration_profiles.v1.json @@ -38,7 +38,7 @@ af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tes 69cb006cff321b6bb47db4ff0ec42ec6e8f0be2ab624e94b97473add50c26422 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -20d16bc01cd209c8c2181c5cb506ae4cc33ddb4f5f73c5a3a0b2c665dce55c13 scripts/check_release_bundle.py +5e17a3bb516d12070f97c4502d431220b46da6cab7b467150a496e808bbd48eb scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index d21c491..0e66c90 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "f098aadb088cb63811b0b716fb4cde319215009da84981bcefb959a59f62d1ca", + "product_source_sha256": "359893551444fdc05b9b411ad88fefc5455dcdffe6353abf59b4730f46225204", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-policy/SKILL.md b/keel-policy/SKILL.md index d503a05..f23ec71 100644 --- a/keel-policy/SKILL.md +++ b/keel-policy/SKILL.md @@ -88,7 +88,15 @@ Choose one explicit mode and keep one intent ledger across it: Each handoff contains: the human intent, policy JSON when one can be drafted faithfully, an evaluation-order readback, an enforceability report, the activation effect (`narrows`, `widens`, `ambiguous`, `unchanged`, or `unresolved`), blocked requests, and the exact human next step. Validate an -enforceability report with `scripts/validate_enforceability_report.py`. A blocked report is a successful +enforceability report with `scripts/validate_enforceability_report.py`. For an embedded policy, use +`rules[0]`, `rules[1]`, and so on as exact rule references, with one entry for each fact consumed by +each rule. The machine report's `readback` must equal the validator's `derive_readback(policy)`; +keep any additional friendly explanation outside that validated field. `safe_outcome` must agree +with the referenced action. Keep `activation_effect` as `unresolved` without an authenticated active +policy baseline. Human `intent` remains a declaration for human review, not a proved policy effect. +Actions whose implicit runtime facts or capabilities lack a pinned trusted evidence contract cannot +pass offline enforceability qualification; report the missing contract instead of claiming support. +A blocked report is a successful diagnosis; never change the requested restriction to make validation pass. Every non-null embedded `policy` is validated against the committed diff --git a/keel-policy/scripts/validate_enforceability_report.py b/keel-policy/scripts/validate_enforceability_report.py index 3e80ca1..76d2290 100644 --- a/keel-policy/scripts/validate_enforceability_report.py +++ b/keel-policy/scripts/validate_enforceability_report.py @@ -37,6 +37,8 @@ def _action_dependencies(rule: dict[str, Any]) -> tuple[str, ...] | None: action = rule.get("action") + if not isinstance(action, str): + return None params = rule.get("params") if action == "deny_if_cost_exceeds" and (not isinstance(params, dict) or params.get("window") != "request"): return None # Window spend is not a published field/capability contract. @@ -67,6 +69,23 @@ def _condition_fields(condition: Any) -> list[str]: return fields +def derive_readback(policy: dict[str, Any]) -> list[str]: + """Canonical readback binds every condition, parameter and requirement.""" + return [f"Rule {index + 1}: {json.dumps(rule, sort_keys=True, ensure_ascii=False)}" + for index, rule in enumerate(policy.get("rules", []))] + + +def _safe_outcome(rule: dict[str, Any]) -> str: + action = rule.get("action") + if action == "allow": + return "review" if rule.get("approval_requirement") else "auto_allow" + if action == "require_human_review": + return "review" + if action == "deny" or str(action).startswith("deny_if_"): + return "deny" + return "proposal_only" + + def validate( report: Any, manifest: dict[str, Any], @@ -89,13 +108,15 @@ def validate( failures.append("pinned field-provenance artifact does not exactly cover the published field set") entries = report.get("enforceability") if isinstance(report.get("enforceability"), list) else [] - by_field: dict[str, list[tuple[int, dict[str, Any]]]] = {} + by_rule_field: dict[tuple[str, str], list[tuple[int, dict[str, Any]]]] = {} for index, item in enumerate(entries): if not isinstance(item, dict): continue field = item.get("field") if isinstance(field, str): - by_field.setdefault(field, []).append((index, item)) + reference = item.get("rule_reference") + if isinstance(reference, str): + by_rule_field.setdefault((reference, field), []).append((index, item)) status = item.get("status") pinned_provenance = provenance.get(field) if isinstance(field, str) else None if isinstance(field, str) and field not in public_fields: @@ -120,6 +141,18 @@ def validate( if policy is not None: failures.extend(validate_schema(policy, policy_schema, "$.policy")) rules = policy.get("rules") if isinstance(policy, dict) else [] + if isinstance(policy, dict) and isinstance(rules, list): + if report.get("readback") != derive_readback(policy): + failures.append("readback must exactly match the structurally derived policy rules") + # Without an active-policy baseline or runtime composition, a draft + # cannot establish narrowing, widening, or unchanged activation. + if report.get("activation_effect") != "unresolved": + failures.append("activation_effect must be unresolved without an authenticated active-policy baseline") + expected_refs = {f"rules[{index}]" for index in range(len(rules))} + for entry_index, item in enumerate(entries): + if isinstance(item, dict) and (not isinstance(item.get("rule_reference"), str) + or item["rule_reference"] not in expected_refs): + failures.append(f"enforceability[{entry_index}] must reference exactly one existing rules[index]") if isinstance(rules, list): for rule_index, rule in enumerate(rules): if not isinstance(rule, dict): @@ -132,8 +165,16 @@ def validate( failures.append(f"policy.rules[{rule_index}] implicit runtime facts/capabilities have no pinned trusted evidence contract") dependencies = () fields = sorted(set(fields) | set(dependencies)) + reference = f"rules[{rule_index}]" + for entry_index, item in enumerate(entries): + if not isinstance(item, dict) or item.get("rule_reference") != reference: + continue + if item.get("field") not in fields: + failures.append(f"enforceability[{entry_index}] fact is not consumed by the referenced rule") + if item.get("safe_outcome") != _safe_outcome(rule): + failures.append(f"enforceability[{entry_index}] safe_outcome disagrees with the referenced action") for field in fields: - matching = by_field.get(field, []) + matching = by_rule_field.get((reference, field), []) if not matching: failures.append(f"policy.rules[{rule_index}] field {field!r} has no enforceability entry") continue diff --git a/keel-policy/tests/test_authoring_context_consumption.py b/keel-policy/tests/test_authoring_context_consumption.py index 2e24cd8..cbf2cca 100644 --- a/keel-policy/tests/test_authoring_context_consumption.py +++ b/keel-policy/tests/test_authoring_context_consumption.py @@ -253,12 +253,12 @@ def read(relative): 'schema_version': '1.0', 'intent': ['Only this selected provider/model pair may run in this dedicated summarizer project; accept blocking the old default.'], 'policy': policy, - 'readback': ['Deny other providers first.', 'Then deny models outside the selected list for this provider. The old default is blocked.'], - 'enforceability': [dict(rule_reference='rules 1-2', required_fact=field, + 'readback': validator.derive_readback(policy), + 'enforceability': [dict(rule_reference=f'rules[{index}]', required_fact=field, field=field, surface='managed_execute', provenance='keel_derived', status='trusted', safe_outcome='deny', reason='Published Keel-derived model/provider contract.', replacement_field=None) - for field in ('provider', 'model')], - 'activation_effect': 'narrows', 'blocked_requests': [], + for index, field in ((0, 'provider'), (1, 'provider'), (1, 'model'))], + 'activation_effect': 'unresolved', 'blocked_requests': [], 'human_next_step': out['handoff'], } failures = validator.validate(report, read('tools/public_surface.json'), diff --git a/keel-policy/tests/test_validate_enforceability_report.py b/keel-policy/tests/test_validate_enforceability_report.py index 01058e6..8511b5d 100644 --- a/keel-policy/tests/test_validate_enforceability_report.py +++ b/keel-policy/tests/test_validate_enforceability_report.py @@ -24,7 +24,7 @@ def report(field="action.name", status="untrusted", replacement=validator.BOUND_ "policy": None, "readback": ["The rule requires human review."], "enforceability": [{ - "rule_reference": "rule 1", "required_fact": "exact MCP tool identity", "field": field, + "rule_reference": "rules[0]", "required_fact": "exact MCP tool identity", "field": field, "surface": "managed_mcp", "provenance": PROVENANCE["fields"].get(field, "unresolved"), "status": status, "safe_outcome": "review", "reason": "The caller selects action.name.", "replacement_field": replacement, }], @@ -47,6 +47,33 @@ def add_policy(candidate, field, action="allow"): class EnforceabilityValidatorTest(unittest.TestCase): + def test_rule_effects_readback_and_references_are_structurally_bound(self): + candidate = add_policy(report(field="provider", status="trusted", replacement=None), "provider", "allow") + candidate["enforceability"][0]["safe_outcome"] = "auto_allow" + candidate["readback"] = validator.derive_readback(candidate["policy"]) + self.assertEqual(validate(candidate), []) + for key, value in (("readback", ["Requires review only"]), ("activation_effect", "narrows")): + altered = json.loads(json.dumps(candidate)) + altered[key] = value + self.assertTrue(validate(altered), key) + for key, value in (("safe_outcome", "review"), ("rule_reference", "rules[99]")): + altered = json.loads(json.dumps(candidate)) + altered["enforceability"][0][key] = value + self.assertTrue(validate(altered), key) + candidate["enforceability"].append(dict(candidate["enforceability"][0])) + self.assertTrue(any("duplicate" in error for error in validate(candidate))) + + def test_model_dependency_has_a_positive_control_and_rejects_downgrade(self): + candidate = add_policy(report(field="provider", status="trusted", replacement=None), "provider", "deny_if_model_not_in") + candidate["policy"]["rules"][0]["params"] = {"allowed": ["example-model"]} + entry = candidate["enforceability"][0] + entry.update(surface="managed_execute", safe_outcome="deny") + candidate["enforceability"].append({**entry, "field": "model"}) + candidate["readback"] = validator.derive_readback(candidate["policy"]) + self.assertEqual(validate(candidate), []) + candidate["enforceability"][1]["status"] = "untrusted" + self.assertTrue(any("without independently trusted" in error for error in validate(candidate))) + def test_implicit_action_facts_cannot_be_omitted_or_downgraded(self): candidate = add_policy(report(field="provider", status="trusted", replacement=None), "provider", "deny_if_model_not_in") candidate["policy"]["rules"][0]["params"] = {"allowed": ["example-model"]} diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index de27d59..a17c78f 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "f098aadb088cb63811b0b716fb4cde319215009da84981bcefb959a59f62d1ca" +PRODUCT_SOURCE_SHA256 = "359893551444fdc05b9b411ad88fefc5455dcdffe6353abf59b4730f46225204" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 1e0dfd1a1ea64d1b1d8722b2477c5524e524102f Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:56:17 -0800 Subject: [PATCH 16/22] fix: bound aggregate repository inspection and source comparisons Addresses occ_019cafb0b9459b5b74caf450. Stream bounded directory enumeration, count skipped entries, cap files/bytes/matches/output/depth/time, reject special files, and avoid quadratic large-source comparisons. --- SHA256SUMS | 12 +- SOURCE.json | 2 +- keel-setup/scripts/fast_first_run.py | 97 +++++++++++--- keel-setup/scripts/inventory.py | 164 +++++++++++++++--------- keel-setup/tests/test_fast_first_run.py | 22 ++++ keel-setup/tests/test_inventory.py | 22 +++- scripts/check_release_bundle.py | 2 +- 7 files changed, 234 insertions(+), 87 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 9a7bec2..c8e6ac5 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -7e654ae9b125252208070c9f8336a02e14f37065926cb76039b503a5381a1cfc SOURCE.json +792428e2a43edb5796788dd0de30b3d84aaa47c4a2d4de59859eea82f38abce5 SOURCE.json 1edad0b7e0dcc065d5eca7dcca9ad7218824f62346fe6233e09a8110a9663746 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -23,22 +23,22 @@ b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md 580edac4805c13a2b88b7dde613bf3a388347c9d00c6f9488c1ceb9e593368d3 keel-setup/scripts/authoring_context.py -0e07379a920870ce7b9e9786ef62ef0feb5e9eff7883a300401a8b381fd6ae58 keel-setup/scripts/fast_first_run.py -856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py +3df7e1adb063c4365eefb42edb8b44ed72d6c15c1bdf36ebbe102925c99291af keel-setup/scripts/fast_first_run.py +b095a7c5dd344db6ac71685cbea8146b1b837a5ab3cae42280cf1626cf5addda keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py 1502ef6a29d2f70984401e322aa39b5c2695c551e8856e59af7ab350f12ca0dd keel-setup/scripts/setup_state.py 1bc3d136fe06414a090976712c96fef0f46d7922ed3cd5cf502fa174de1aa86d keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -953149f85bb446dd622f2d5e4bed57c8b9c58143e68676f60078085f2b008b43 keel-setup/tests/test_fast_first_run.py -62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py +0e96cdf4f9133440d52a23e0e3e3f2fc0bf063f0a476cafb787c440f439f3a1b keel-setup/tests/test_fast_first_run.py +305e9fcc3f861809422cf39cf12fd16785d7bcf48eb2f27b140ff009d478ef8b keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py 69cb006cff321b6bb47db4ff0ec42ec6e8f0be2ab624e94b97473add50c26422 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -5e17a3bb516d12070f97c4502d431220b46da6cab7b467150a496e808bbd48eb scripts/check_release_bundle.py +8bc8eeb6763a084468ff18b8b37e7fe90949c05d933829585564b5a2fbee6d06 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index 0e66c90..9c6f89d 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "359893551444fdc05b9b411ad88fefc5455dcdffe6353abf59b4730f46225204", + "product_source_sha256": "8035f9b46298cc7ec560d77dd98172c71058343181cd536482e2bedd7e5bb070", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index 824dfb9..8ed44b1 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -41,6 +41,10 @@ MAX_TEST_FILES = 50 MAX_SOURCE_BYTES = 1_000_000 MAX_DIFF_BYTES = 64 * 1024 +MAX_SCAN_ENTRIES = 10_000 +MAX_SCAN_DIRECTORIES = 512 +MAX_SCAN_DEPTH = 24 +MAX_SCAN_SECONDS = 10 CLASSIFICATION_SKIP_DIRS = { ".git", ".hg", ".svn", ".worktrees", ".tox", ".mypy_cache", ".pytest_cache", "node_modules", "vendor", "dist", "build", ".venv", "venv", "__pycache__", @@ -337,19 +341,38 @@ def verify_release(bundle: pathlib.Path, expected_sha: str) -> dict[str, Any]: } +def bounded_walk(root: pathlib.Path): + """Bound every enumerated entry, including files later skipped by callers.""" + started = time.monotonic() + stack = [(root, 0)] + entries_seen = directories_seen = 0 + while stack: + current, depth = stack.pop() + directories_seen += 1 + if depth > MAX_SCAN_DEPTH or directories_seen > MAX_SCAN_DIRECTORIES: + raise PipelineFailure("model_review_required", "repository exceeds traversal limits") + directories, filenames = [], [] + with os.scandir(current) as entries: + for entry in entries: + entries_seen += 1 + if entries_seen > MAX_SCAN_ENTRIES or time.monotonic() - started > MAX_SCAN_SECONDS: + raise PipelineFailure("model_review_required", "repository exceeds entry or elapsed-time limit") + if entry.is_dir(follow_symlinks=False): + directories.append(entry.name) + else: + filenames.append(entry.name) + directories.sort() + filenames.sort() + yield str(current), directories, filenames + stack.extend((current / name, depth + 1) for name in reversed(directories)) + + def classify_repository(repo: pathlib.Path) -> dict[str, Any]: """Return bounded repository facts without importing or executing application code.""" revision = _git(repo, "rev-parse", "HEAD") if re.fullmatch(r"[0-9a-f]{40}", revision) is None: raise PipelineFailure("model_review_required", "repository has no immutable Git revision") - dirty = _git(repo, "status", "--porcelain=v1", "--untracked-files=all").splitlines() - if dirty: - raise PipelineFailure( - "dirty_checkout", - "Keel will not modify existing uncommitted work automatically. Commit or stash it and retry, " - "use a fresh disposable checkout, or explicitly request deeper model-driven inspection.", - ) instruction_names = {"AGENTS.md", "CLAUDE.md", ".cursorrules", "copilot-instructions.md"} instructions: list[str] = [] @@ -357,7 +380,7 @@ def classify_repository(repo: pathlib.Path) -> dict[str, Any]: if copilot_instructions.is_file(): instructions.append(".github/copilot-instructions.md") files_considered = 0 - for current, directories, filenames in os.walk(repo, topdown=True, followlinks=False): + for current, directories, filenames in bounded_walk(repo): directories[:] = sorted( name for name in directories if name not in CLASSIFICATION_SKIP_DIRS and not name.startswith(".") @@ -375,6 +398,15 @@ def classify_repository(repo: pathlib.Path) -> dict[str, Any]: if len(instructions) > MAX_INSTRUCTION_FILES: raise PipelineFailure("model_review_required", "repository instruction set exceeds the bounded limit") + dirty = _git(repo, "status", "--porcelain=v1", "--untracked-files=all").splitlines() + if dirty: + raise PipelineFailure( + "dirty_checkout", + "Keel will not modify existing uncommitted work automatically. Commit or stash it and retry, " + "use a fresh disposable checkout, or explicitly request deeper model-driven inspection.", + ) + + manifests: list[str] = [] for pattern in ("pyproject.toml", "requirements*.txt", "setup.py", "setup.cfg", "Pipfile"): manifests.extend(path.relative_to(repo).as_posix() for path in sorted(repo.glob(pattern)) if path.is_file()) @@ -387,7 +419,10 @@ def classify_repository(repo: pathlib.Path) -> dict[str, Any]: try: if path.stat().st_size > MAX_SOURCE_BYTES: raise PipelineFailure("model_review_required", "Python dependency manifest exceeds the bounded limit") - content = path.read_text(encoding="utf-8") + raw = _read_repo_file(path, repo) + if raw is None: + raise PipelineFailure("model_review_required", "Python dependency manifest disappeared") + content = raw.decode("utf-8") except (OSError, UnicodeDecodeError) as exc: raise PipelineFailure("model_review_required", "Python dependency manifest could not be inspected") from exc if re.search(r"(?im)^\s*openai(?:\[[^]]+\])?\s*(?:[<>=!~]|$)", content): @@ -464,7 +499,7 @@ def _is_none_default(function: ast.FunctionDef, name: str) -> bool: def _find_coupled_tests(repo: pathlib.Path, symbol: str) -> list[pathlib.PurePosixPath]: matches: list[pathlib.PurePosixPath] = [] considered = 0 - for current, directories, filenames in os.walk(repo, topdown=True, followlinks=False): + for current, directories, filenames in bounded_walk(repo): directories[:] = sorted( name for name in directories if name not in CLASSIFICATION_SKIP_DIRS and not name.startswith(".") @@ -482,7 +517,10 @@ def _find_coupled_tests(repo: pathlib.Path, symbol: str) -> list[pathlib.PurePos try: if path.is_symlink() or path.stat().st_size > MAX_SOURCE_BYTES: continue - tree = ast.parse(path.read_text(encoding="utf-8"), filename=relative.as_posix()) + raw = _read_repo_file(path, repo) + if raw is None: + raise PipelineFailure("model_review_required", "compatibility test disappeared") + tree = ast.parse(raw.decode("utf-8"), filename=relative.as_posix()) except (OSError, UnicodeDecodeError, SyntaxError): raise PipelineFailure("model_review_required", "a candidate compatibility test could not be parsed") for node in ast.walk(tree): @@ -512,7 +550,10 @@ def discover_golden_seam(repo: pathlib.Path, inventory: Any) -> GoldenSeam: relative = pathlib.PurePosixPath(raw_path) path = repo.joinpath(*relative.parts) try: - source = path.read_text(encoding="utf-8") + raw = _read_repo_file(path, repo) + if raw is None: + raise PipelineFailure("model_review_required", "selected source disappeared") + source = raw.decode("utf-8") tree = ast.parse(source, filename=raw_path) except (OSError, UnicodeDecodeError, SyntaxError) as exc: raise PipelineFailure("unsupported_shape", "selected Python source could not be parsed") from exc @@ -664,7 +705,10 @@ def _keel_output_text(body: dict[str, Any]) -> str: def generate_adapter(repo: pathlib.Path, seam: GoldenSeam) -> tuple[str, str | None]: path = repo.joinpath(*seam.path.parts) - source = path.read_text(encoding="utf-8") + raw = _read_repo_file(path, repo) + if raw is None: + raise PipelineFailure("model_review_required", "selected source disappeared") + source = raw.decode("utf-8") tree = ast.parse(source) reserved = { "KEEL_EXECUTE_URL", "KEEL_MAX_RESPONSE_BYTES", "KEEL_REQUEST_TIMEOUT_SECONDS", @@ -753,7 +797,10 @@ def generate_adapter(repo: pathlib.Path, seam: GoldenSeam) -> tuple[str, str | N def _generate_coupled_test(repo: pathlib.Path, seam: GoldenSeam) -> str: assert seam.coupled_test is not None path = repo.joinpath(*seam.coupled_test.parts) - original = path.read_text(encoding="utf-8") + raw = _read_repo_file(path, repo) + if raw is None: + raise PipelineFailure("model_review_required", "compatibility test disappeared") + original = raw.decode("utf-8") # This whole-file migration is authorized only for the exact published # fixture. Any additional test, fixture, hook, or comment requires review. if hashlib.sha256(original.encode("utf-8")).hexdigest() != "bdb7e770dfe505e3efab6e6852afb70b88b38b2b6222cb451aacf25bef29592b": @@ -910,7 +957,7 @@ def validate_patch( # A reduced environment and timeout do not isolate the host. Only compile # here; runtime compatibility requires isolated post-gate execution. try: - compile(repo.joinpath(*seam.coupled_test.parts).read_text(encoding="utf-8"), + compile(_read_repo_file(repo.joinpath(*seam.coupled_test.parts), repo) or b"", seam.coupled_test.as_posix(), "exec") except (OSError, UnicodeError, SyntaxError) as exc: raise PipelineFailure("validation_failed", "generated compatibility test does not compile") from exc @@ -1023,8 +1070,16 @@ def _restore(repo: pathlib.Path, originals: dict[pathlib.PurePosixPath, bytes | def _line_change_stats(before: str, after: str) -> tuple[int, int, int]: + if len(before.encode()) > MAX_SOURCE_BYTES or len(after.encode()) > MAX_SOURCE_BYTES: + raise PipelineFailure("model_review_required", "source comparison exceeds its byte limit") before_lines = before.splitlines() after_lines = after.splitlines() + if len(before_lines) * len(after_lines) > 250_000: + # Large repeated-line inputs use bounded linear multiset statistics. + # These counts describe content changes, not line movement. + removed = collections.Counter(before_lines) - collections.Counter(after_lines) + added = collections.Counter(after_lines) - collections.Counter(before_lines) + return sum(added.values()), sum(removed.values()), 0 matcher = difflib.SequenceMatcher( None, before_lines, @@ -1081,7 +1136,10 @@ def build_diff_evidence( raise PipelineFailure("validation_failed", "diff evidence path was not captured before editing") try: before = original.decode("utf-8") if original is not None else "" - after = repo.joinpath(*relative.parts).read_text(encoding="utf-8") + raw = _read_repo_file(repo.joinpath(*relative.parts), repo) + if raw is None: + raise PipelineFailure("validation_failed", "diff evidence source disappeared") + after = raw.decode("utf-8") except (OSError, UnicodeDecodeError) as exc: raise PipelineFailure("validation_failed", "diff evidence is not bounded UTF-8 text") from exc insertions, deletions, whitespace = _line_change_stats(before, after) @@ -1121,8 +1179,10 @@ def run_pipeline(bundle: pathlib.Path, bundle_sha: str, repo: pathlib.Path) -> d timings["seam_discovery_ms"] = round((time.perf_counter() - mark) * 1000, 3) app_path = repo.joinpath(*seam.path.parts) - app_before = app_path.read_text(encoding="utf-8") originals[seam.path] = _read_repo_file(app_path, repo) + if originals[seam.path] is None: + raise PipelineFailure("validation_failed", "selected source disappeared") + app_before = originals[seam.path].decode("utf-8") if seam.coupled_test: test_path = repo.joinpath(*seam.coupled_test.parts) originals[seam.coupled_test] = _read_repo_file(test_path, repo) @@ -1132,6 +1192,9 @@ def run_pipeline(bundle: pathlib.Path, bundle_sha: str, repo: pathlib.Path) -> d mark = time.perf_counter() app_after, test_after = generate_adapter(repo, seam) + _line_change_stats(app_before, app_after) + if seam.coupled_test and test_after is not None: + _line_change_stats(originals[seam.coupled_test].decode("utf-8"), test_after) edited = True _write(app_path, app_after, repo) if seam.coupled_test and test_after is not None: diff --git a/keel-setup/scripts/inventory.py b/keel-setup/scripts/inventory.py index 9637c7b..ea243bd 100644 --- a/keel-setup/scripts/inventory.py +++ b/keel-setup/scripts/inventory.py @@ -13,6 +13,7 @@ import os import pathlib import re +import stat import subprocess import sys import time @@ -27,6 +28,15 @@ COVERAGE_SCHEMA = ROOT / "keel-setup" / "reference" / "coverage.schema.json" MAX_FILE_BYTES = 1_000_000 +MAX_SCAN_ENTRIES = 10_000 +MAX_SCAN_DIRECTORIES = 512 +MAX_SCAN_DEPTH = 24 +MAX_SCAN_SECONDS = 10 +MAX_SCAN_FILES = 2_000 +MAX_SCAN_BYTES = 16_000_000 +MAX_SCAN_MATCHES = 1_000 +MAX_OUTPUT_BYTES = 512_000 +MAX_SOURCE_LINES = 20_000 FAST_MAX_FILES = 400 FAST_MAX_CANDIDATES = 20 SKIP_DIRS = { @@ -116,45 +126,64 @@ def revision(root: pathlib.Path) -> str | None: return value if re.fullmatch(r"[0-9a-f]{40}", value) else None -def iter_source_files(root: pathlib.Path): - for path in sorted(root.rglob("*")): - try: - relative = path.relative_to(root) - except ValueError: - continue - if any(part in SKIP_DIRS for part in relative.parts) or path.is_symlink() or not path.is_file(): - continue - if path.suffix.lower() not in TEXT_SUFFIXES: - continue - try: - if path.stat().st_size > MAX_FILE_BYTES: +def bounded_walk(root: pathlib.Path): + """Bound every enumerated entry, including files later skipped by callers.""" + started = time.monotonic() + stack = [(root, 0)] + entries_seen = directories_seen = 0 + while stack: + current, depth = stack.pop() + directories_seen += 1 + if depth > MAX_SCAN_DEPTH or directories_seen > MAX_SCAN_DIRECTORIES: + raise ValueError("repository exceeds traversal limits") + directories, filenames = [], [] + with os.scandir(current) as entries: + for entry in entries: + entries_seen += 1 + if entries_seen > MAX_SCAN_ENTRIES or time.monotonic() - started > MAX_SCAN_SECONDS: + raise ValueError("repository exceeds entry or elapsed-time limit") + if entry.is_dir(follow_symlinks=False): + directories.append(entry.name) + else: + filenames.append(entry.name) + directories.sort() + filenames.sort() + yield str(current), directories, filenames + stack.extend((current / name, depth + 1) for name in reversed(directories)) + + +def iter_source_files(root: pathlib.Path, *, fast: bool = False): + total_bytes = 0 + files_seen = 0 + for current, directories, filenames in bounded_walk(root): + directories[:] = [name for name in directories if name not in SKIP_DIRS and (not fast or not name.startswith("."))] + for filename in filenames: + path = pathlib.Path(current) / filename + if path.is_symlink() or path.suffix.lower() not in TEXT_SUFFIXES: continue - except OSError: - continue - yield path, relative + info = path.stat() + if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_FILE_BYTES: + continue + files_seen += 1 + total_bytes += info.st_size + if files_seen > MAX_SCAN_FILES or total_bytes > MAX_SCAN_BYTES: + raise ValueError("repository exceeds aggregate file or byte limit") + yield path, path.relative_to(root) def iter_fast_source_files(root: pathlib.Path): - """Yield shallow-search candidates without materializing the whole tree.""" + yield from iter_source_files(root, fast=True) - for current, directories, filenames in os.walk(root, topdown=True, followlinks=False): - directories[:] = sorted( - name - for name in directories - if name not in SKIP_DIRS and not name.startswith(".") - ) - current_path = pathlib.Path(current) - for filename in sorted(filenames): - path = current_path / filename - if path.is_symlink() or path.suffix.lower() not in TEXT_SUFFIXES: - continue - try: - if path.stat().st_size > MAX_FILE_BYTES: - continue - relative = path.relative_to(root) - except (OSError, ValueError): - continue - yield path, relative + +def _source_text(path: pathlib.Path) -> str: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, "rb") as stream: + if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): + raise ValueError("source must be a regular file") + raw = stream.read(MAX_FILE_BYTES + 1) + if len(raw) > MAX_FILE_BYTES or raw.count(b"\n") > MAX_SOURCE_LINES: + raise ValueError("source exceeds bounded size or line limit") + return raw.decode("utf-8") def _is_test_path(relative: pathlib.PurePath) -> bool: @@ -218,7 +247,7 @@ def _python_custom_base_url_reasons(tree: ast.AST, provider: str) -> list[str]: def _python_candidates(path: pathlib.Path, relative: pathlib.PurePath) -> list[dict[str, Any]]: try: - source = path.read_text(encoding="utf-8") + source = _source_text(path) tree = ast.parse(source, filename=relative.as_posix()) except (OSError, UnicodeDecodeError, SyntaxError): return [] @@ -281,7 +310,7 @@ def _python_candidates(path: pathlib.Path, relative: pathlib.PurePath) -> list[d def _javascript_candidates(path: pathlib.Path, relative: pathlib.PurePath) -> list[dict[str, Any]]: try: - lines = path.read_text(encoding="utf-8").splitlines() + lines = _source_text(path).splitlines() except (OSError, UnicodeDecodeError): return [] source = "\n".join(lines) @@ -337,7 +366,7 @@ def _provider_signal_candidates( """Find bounded raw-provider or import signals omitted by SDK call matching.""" try: - lines = path.read_text(encoding="utf-8").splitlines() + lines = _source_text(path).splitlines() except (OSError, UnicodeDecodeError): return [] source = "\n".join(lines) @@ -401,27 +430,31 @@ def fast_inspect( test_files_skipped = 0 sensitive_paths_skipped = 0 truncated = False - for path, relative in iter_fast_source_files(root): - if SENSITIVE_PATH_PATTERN.search(relative.as_posix()): - sensitive_paths_skipped += 1 - continue - if _is_test_path(relative): - test_files_skipped += 1 - continue - if files_considered >= max_files or len(candidates) >= max_candidates: - truncated = True - break - files_considered += 1 - sdk_candidates: list[dict[str, Any]] = [] - if path.suffix.lower() == ".py": - sdk_candidates = _python_candidates(path, relative) - elif path.suffix.lower() in FAST_SOURCE_SUFFIXES: - sdk_candidates = _javascript_candidates(path, relative) - candidates.extend(sdk_candidates) - candidates.extend(_provider_signal_candidates(path, relative, sdk_candidates)) - if len(candidates) > max_candidates: - truncated = True - break + try: + for path, relative in iter_fast_source_files(root): + if SENSITIVE_PATH_PATTERN.search(relative.as_posix()): + sensitive_paths_skipped += 1 + continue + if _is_test_path(relative): + test_files_skipped += 1 + continue + if files_considered >= max_files or len(candidates) >= max_candidates: + truncated = True + break + files_considered += 1 + sdk_candidates: list[dict[str, Any]] = [] + if path.suffix.lower() == ".py": + sdk_candidates = _python_candidates(path, relative) + elif path.suffix.lower() in FAST_SOURCE_SUFFIXES: + sdk_candidates = _javascript_candidates(path, relative) + candidates.extend(sdk_candidates) + candidates.extend(_provider_signal_candidates(path, relative, sdk_candidates)) + if len(candidates) > max_candidates: + truncated = True + break + + except ValueError: + truncated = True candidates = candidates[:max_candidates] sdk_candidates = [item for item in candidates if item["request_kind"] == "sdk_request"] @@ -473,15 +506,18 @@ def fast_inspect( def inspect(root: pathlib.Path) -> dict[str, Any]: paths: list[dict[str, Any]] = [] + output_bytes = 1024 for path, relative in iter_source_files(root): try: - lines = path.read_text(encoding="utf-8").splitlines() + lines = _source_text(path).splitlines() except (OSError, UnicodeDecodeError): continue for line_number, line in enumerate(lines, 1): for surface, pattern, signal in PATTERNS: if not pattern.search(line): continue + if len(paths) >= MAX_SCAN_MATCHES: + raise ValueError("inventory exceeds its match limit") paths.append( { "path": relative.as_posix(), @@ -494,6 +530,9 @@ def inspect(root: pathlib.Path) -> dict[str, Any]: "uncertainties": ["source signal is not trusted runtime semantics"], } ) + output_bytes += len(json.dumps(paths[-1]).encode("utf-8")) + if output_bytes > MAX_OUTPUT_BYTES: + raise ValueError("inventory exceeds its output limit") return { "schema_version": "1.0", "report_basis": "source_inventory", @@ -574,7 +613,12 @@ def main(argv: list[str] | None = None) -> int: return 1 print(json.dumps(fast_inspect(root, max_files=args.max_files, max_candidates=args.max_candidates), indent=2, sort_keys=True)) return 0 - print(json.dumps(inspect(root), indent=2, sort_keys=True)) + try: + result = inspect(root) + except (OSError, ValueError): + print("inventory refused: repository exceeds bounded inspection limits", file=sys.stderr) + return 1 + print(json.dumps(result, indent=2, sort_keys=True)) return 0 diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index f00fa0b..80560cd 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -578,6 +578,28 @@ def test_whitespace_only_changed_line_count_is_exact(self): self.assertEqual((insertions, deletions, whitespace_only), (1, 1, 2)) + def test_repeated_line_statistics_and_skipped_entries_are_bounded(self): + before = "repeat\n" * 20_000 + after = "repeat\n" * 19_999 + "changed\n" + with mock.patch.object(fast.difflib, "SequenceMatcher", side_effect=AssertionError("quadratic comparison")): + self.assertEqual(fast._line_change_stats(before, after), (1, 1, 0)) + root = self._repo() + for index in range(12): + (root / f"ignored-{index}.bin").write_bytes(b"ignored") + with mock.patch.object(fast, "MAX_SCAN_ENTRIES", 10): + result = self._run(root) + self.assertEqual(result["outcome"], "model_review_required", result) + self.assertEqual((root / "app.py").read_text(), fixtures.GOLDEN_APP) + + def test_ignored_compatibility_fifo_is_refused_without_blocking_or_editing(self): + root = self._repo() + path = root / "tests/test_fifo.py" + os.mkfifo(path) + (root / ".git/info/exclude").write_text("tests/test_fifo.py\n") + result = self._run(root) + self.assertEqual(result["outcome"], "validation_failed", result) + self.assertEqual((root / "app.py").read_text(), fixtures.GOLDEN_APP) + def test_large_source_is_never_embedded_in_metadata(self): root = self._repo() result = self._run(root) diff --git a/keel-setup/tests/test_inventory.py b/keel-setup/tests/test_inventory.py index 71ee90e..8c15cec 100644 --- a/keel-setup/tests/test_inventory.py +++ b/keel-setup/tests/test_inventory.py @@ -11,6 +11,7 @@ import sys import tempfile import unittest +from unittest import mock SCRIPT = pathlib.Path(__file__).parents[1] / "scripts" / "inventory.py" SPEC = importlib.util.spec_from_file_location("inventory", SCRIPT) @@ -47,6 +48,23 @@ def report(): class InventoryTest(unittest.TestCase): + def test_aggregate_limits_count_skipped_files_bytes_and_matches(self): + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + for index in range(12): + (root / f"test_skip_{index}.py").write_text("# skipped test\n") + with mock.patch.object(inventory, "MAX_SCAN_ENTRIES", 10): + result = inventory.fast_inspect(root) + self.assertEqual(result["decision"], "ambiguous_scan_truncated") + self.assertIsNone(result["selected_seam"]) + with mock.patch.object(inventory, "MAX_SCAN_BYTES", 10), self.assertRaises(ValueError): + inventory.inspect(root) + (root / "signals.py").write_text("OpenAI()\n" * 20) + with mock.patch.object(inventory, "MAX_SCAN_MATCHES", 10), self.assertRaises(ValueError): + inventory.inspect(root) + with mock.patch.object(inventory, "MAX_OUTPUT_BYTES", 1100), self.assertRaises(ValueError): + inventory.inspect(root) + def test_inventory_is_source_only_and_reports_limits(self): with tempfile.TemporaryDirectory() as directory: root = pathlib.Path(directory) @@ -403,8 +421,8 @@ def test_deterministic_golden_path_precedes_model_driven_fallback(self): self.assertIn("rediscover the seam", fast[deterministic:fallback]) self.assertIn("handle setup state separately", fast[deterministic:fallback]) self.assertIn("repeat\nvalidation or tests", fast[deterministic:fallback]) - self.assertIn("`diff_truncated` is `false`, do not rerun `git diff`", fast[deterministic:fallback]) - self.assertIn("run exactly one targeted\n`git diff`", fast[deterministic:fallback]) + self.assertIn("contains only counts and digests", fast[deterministic:fallback]) + self.assertIn("targeted local `git diff`", fast[deterministic:fallback]) for outcome in ( "ambiguous", "unsupported_shape", diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index a17c78f..06ba03d 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "359893551444fdc05b9b411ad88fefc5455dcdffe6353abf59b4730f46225204" +PRODUCT_SOURCE_SHA256 = "8035f9b46298cc7ec560d77dd98172c71058343181cd536482e2bedd7e5bb070" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 3c1b2b2a19685329ad986ed1c62de644557d43c3 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:59:45 -0800 Subject: [PATCH 17/22] fix: refuse overlapping source lines during adapter transformation Follow-up for occ_6041c49e8b17de0c7884651d from independent candidate review: semicolon mapping/return nodes must not copy the old provider mapping into the generated adapter. --- SHA256SUMS | 8 ++++---- SOURCE.json | 2 +- keel-setup/scripts/fast_first_run.py | 3 +++ keel-setup/tests/test_fast_first_run.py | 11 +++++++++++ scripts/check_release_bundle.py | 2 +- 5 files changed, 20 insertions(+), 6 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index c8e6ac5..3a83481 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -792428e2a43edb5796788dd0de30b3d84aaa47c4a2d4de59859eea82f38abce5 SOURCE.json +e86dd68d31af4c51e208fc097eb4c2dba561491cdd4bc32cdfadf40437fca940 SOURCE.json 1edad0b7e0dcc065d5eca7dcca9ad7218824f62346fe6233e09a8110a9663746 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -23,7 +23,7 @@ b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md 580edac4805c13a2b88b7dde613bf3a388347c9d00c6f9488c1ceb9e593368d3 keel-setup/scripts/authoring_context.py -3df7e1adb063c4365eefb42edb8b44ed72d6c15c1bdf36ebbe102925c99291af keel-setup/scripts/fast_first_run.py +6057f593b07207d81f3ab1efba774d809034b273648d2a55a75d3f8ddaaabf85 keel-setup/scripts/fast_first_run.py b095a7c5dd344db6ac71685cbea8146b1b837a5ab3cae42280cf1626cf5addda keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py 1502ef6a29d2f70984401e322aa39b5c2695c551e8856e59af7ab350f12ca0dd keel-setup/scripts/setup_state.py @@ -31,14 +31,14 @@ e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scr d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -0e96cdf4f9133440d52a23e0e3e3f2fc0bf063f0a476cafb787c440f439f3a1b keel-setup/tests/test_fast_first_run.py +a08208b325401394192320fd8dc9c8bb22f970579a47cfc9500ecbd4c6a2b961 keel-setup/tests/test_fast_first_run.py 305e9fcc3f861809422cf39cf12fd16785d7bcf48eb2f27b140ff009d478ef8b keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py 69cb006cff321b6bb47db4ff0ec42ec6e8f0be2ab624e94b97473add50c26422 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -8bc8eeb6763a084468ff18b8b37e7fe90949c05d933829585564b5a2fbee6d06 scripts/check_release_bundle.py +ee64fa1dada5909d310cb8c44337f487acd9ebc74b9798b3d64f6a32cc4e915f scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index 9c6f89d..f3d5421 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "8035f9b46298cc7ec560d77dd98172c71058343181cd536482e2bedd7e5bb070", + "product_source_sha256": "a35212a3555180ff7d354257eac68060dc49d6d703ddd53f5301db88721709c7", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index 8ed44b1..0984e58 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -574,6 +574,9 @@ def discover_golden_seam(repo: pathlib.Path, inventory: Any) -> GoldenSeam: function = functions[0] if function.decorator_list: raise PipelineFailure("model_review_required", "decorated callables are outside the golden path") + if any((left.end_lineno or left.lineno) >= right.lineno + for left, right in zip(function.body, function.body[1:])): + raise PipelineFailure("model_review_required", "shared source lines cannot be transformed without changing behavior") signature_line = source.splitlines()[function.lineno - 1] if not signature_line.startswith("def ") or not signature_line.rstrip().endswith(":"): raise PipelineFailure("model_review_required", "multiline or nonstandard callable signatures require model review") diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index 80560cd..cd7b437 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -524,6 +524,17 @@ def test_unrecognized_security_logic_and_extra_tests_are_preserved_by_refusal(se self.assertEqual(path.read_text(), source) self.assertEqual(_git(root, "status", "--porcelain"), "") + def test_same_line_response_mapping_and_return_are_refused_without_changes(self): + source = fixtures.GOLDEN_APP.replace( + ' summary = response.output_text.strip()\n if not summary:\n raise ValueError("The model returned an empty summary.")\n return summary', + ' summary = response.output_text.strip(); return summary', + ) + root = self._repo(source, with_test=False) + result = self._run(root) + self.assertEqual(result["outcome"], "model_review_required", result) + self.assertEqual((root / "app.py").read_text(), source) + self.assertEqual(_git(root, "status", "--porcelain"), "") + def test_retained_try_except_block_is_copied_verbatim_and_compiles(self): root = self._repo(fixtures.RETAINED_TRY_EXCEPT_APP) retained = ''' try: diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 06ba03d..b03109a 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "8035f9b46298cc7ec560d77dd98172c71058343181cd536482e2bedd7e5bb070" +PRODUCT_SOURCE_SHA256 = "a35212a3555180ff7d354257eac68060dc49d6d703ddd53f5301db88721709c7" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 3f428acacfd4531484299d1887f5ca61af215b1a Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:00:11 -0800 Subject: [PATCH 18/22] fix: treat prepared paths as literal filenames during resume Follow-up for occ_9f0022cd1aa84bf3e56ec4d5 from independent review: Git pathspec magic must not borrow an unrelated working-tree change for a clean recorded path. --- SHA256SUMS | 8 ++++---- SOURCE.json | 2 +- keel-setup/scripts/setup_state.py | 2 +- keel-setup/tests/test_setup_state.py | 17 +++++++++++++++++ scripts/check_release_bundle.py | 2 +- 5 files changed, 24 insertions(+), 7 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 3a83481..b6ed699 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -e86dd68d31af4c51e208fc097eb4c2dba561491cdd4bc32cdfadf40437fca940 SOURCE.json +9c04799d78c95409e7e9b3e8dc425b23ae7c4d0cf8e4fbeff949b0c48a79815d SOURCE.json 1edad0b7e0dcc065d5eca7dcca9ad7218824f62346fe6233e09a8110a9663746 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -26,7 +26,7 @@ c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/ref 6057f593b07207d81f3ab1efba774d809034b273648d2a55a75d3f8ddaaabf85 keel-setup/scripts/fast_first_run.py b095a7c5dd344db6ac71685cbea8146b1b837a5ab3cae42280cf1626cf5addda keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py -1502ef6a29d2f70984401e322aa39b5c2695c551e8856e59af7ab350f12ca0dd keel-setup/scripts/setup_state.py +bcbf12085c0776d35189965a1832a0802d782df1d8e918e6166d6eaf36e5a236 keel-setup/scripts/setup_state.py 1bc3d136fe06414a090976712c96fef0f46d7922ed3cd5cf502fa174de1aa86d keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py @@ -35,10 +35,10 @@ a08208b325401394192320fd8dc9c8bb22f970579a47cfc9500ecbd4c6a2b961 keel-setup/tes 305e9fcc3f861809422cf39cf12fd16785d7bcf48eb2f27b140ff009d478ef8b keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py -69cb006cff321b6bb47db4ff0ec42ec6e8f0be2ab624e94b97473add50c26422 keel-setup/tests/test_setup_state.py +f7e0582582c1b6b89a524acf88856557734eb1acb4a123f3729c0762e84926cc keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -ee64fa1dada5909d310cb8c44337f487acd9ebc74b9798b3d64f6a32cc4e915f scripts/check_release_bundle.py +0c2e2e509dff2642ff106a3a9d8580b2e81d9fd306e372c4cdfb2ceb9b7e0b1b scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index f3d5421..c339b24 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "a35212a3555180ff7d354257eac68060dc49d6d703ddd53f5301db88721709c7", + "product_source_sha256": "120062d9e8ce3bcd36fd8746542fd6e6aa79da0bf44ec70c25cd6451c09e4b9d", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/setup_state.py b/keel-setup/scripts/setup_state.py index b888b95..11dbfd4 100644 --- a/keel-setup/scripts/setup_state.py +++ b/keel-setup/scripts/setup_state.py @@ -245,7 +245,7 @@ def validate_prepared_paths( try: status = subprocess.run( [ - "git", "-c", "core.fsmonitor=false", "-C", str(root), "status", "--porcelain=v1", + "git", "--literal-pathspecs", "-c", "core.fsmonitor=false", "-C", str(root), "status", "--porcelain=v1", "--untracked-files=all", "--", raw_path, ], capture_output=True, diff --git a/keel-setup/tests/test_setup_state.py b/keel-setup/tests/test_setup_state.py index 9f8de31..9c3ea13 100644 --- a/keel-setup/tests/test_setup_state.py +++ b/keel-setup/tests/test_setup_state.py @@ -226,6 +226,23 @@ def test_stage_selects_earliest_unmet_phase(self): class BeginTest(unittest.TestCase): + def test_literal_pathspec_filename_cannot_borrow_an_unrelated_change(self): + with tempfile.TemporaryDirectory() as directory: + root = self._repo(directory) + magic = ":(glob)*.py" + (root / magic).write_text("# /v1/execute\n") + (root / "other.py").write_text("# baseline\n") + subprocess.run(["git", "-C", str(root), "add", "."], check=True, capture_output=True) + subprocess.run(["git", "-C", str(root), "-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "-qm", "literal path fixture"], check=True, capture_output=True) + (root / "other.py").write_text("# unrelated edit\n") + state = _waiting_state(application_revision=setup_state.current_revision(root), changed_paths=[magic]) + path = root / ".keel/setup-state.json" + path.write_text(json.dumps(state)) + result = setup_state.begin(path, root) + self.assertEqual(result["continuity"], "lost", result) + self.assertTrue(any("not changed" in error for error in result["refusals"])) + def test_clean_or_stale_preparation_cannot_resume_the_human_gate(self): for stale in (False, True): with tempfile.TemporaryDirectory() as directory: diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index b03109a..278a4da 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "a35212a3555180ff7d354257eac68060dc49d6d703ddd53f5301db88721709c7" +PRODUCT_SOURCE_SHA256 = "120062d9e8ce3bcd36fd8746542fd6e6aa79da0bf44ec70c25cd6451c09e4b9d" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From b4de8f57fbeabdcbb7914745284b4a2be38e2bab Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:01:23 -0800 Subject: [PATCH 19/22] fix: preserve source permissions during no-follow atomic edits Compatibility follow-up for occ_7d65273b5dde96252ad42a0a: an existing source file retains its permission bits even under a restrictive process umask. --- SHA256SUMS | 8 ++++---- SOURCE.json | 2 +- keel-setup/scripts/fast_first_run.py | 1 + keel-setup/tests/test_fast_first_run.py | 11 +++++++++++ scripts/check_release_bundle.py | 2 +- 5 files changed, 18 insertions(+), 6 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index b6ed699..59c573b 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -9c04799d78c95409e7e9b3e8dc425b23ae7c4d0cf8e4fbeff949b0c48a79815d SOURCE.json +5032482d857d5afb328aba1234bfabf6f1959fba1c0b98c16840a8387324470f SOURCE.json 1edad0b7e0dcc065d5eca7dcca9ad7218824f62346fe6233e09a8110a9663746 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -23,7 +23,7 @@ b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md 580edac4805c13a2b88b7dde613bf3a388347c9d00c6f9488c1ceb9e593368d3 keel-setup/scripts/authoring_context.py -6057f593b07207d81f3ab1efba774d809034b273648d2a55a75d3f8ddaaabf85 keel-setup/scripts/fast_first_run.py +e782760ec3132b491b62e4be6bd2c38df328f3782e3f9a6571bfe19daac34b7e keel-setup/scripts/fast_first_run.py b095a7c5dd344db6ac71685cbea8146b1b837a5ab3cae42280cf1626cf5addda keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py bcbf12085c0776d35189965a1832a0802d782df1d8e918e6166d6eaf36e5a236 keel-setup/scripts/setup_state.py @@ -31,14 +31,14 @@ bcbf12085c0776d35189965a1832a0802d782df1d8e918e6166d6eaf36e5a236 keel-setup/scr d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -a08208b325401394192320fd8dc9c8bb22f970579a47cfc9500ecbd4c6a2b961 keel-setup/tests/test_fast_first_run.py +ff46b9b7c6625f3dc2547943dc9e425303c5dcefa100c4ff9246c48d68cf3418 keel-setup/tests/test_fast_first_run.py 305e9fcc3f861809422cf39cf12fd16785d7bcf48eb2f27b140ff009d478ef8b keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py f7e0582582c1b6b89a524acf88856557734eb1acb4a123f3729c0762e84926cc keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -0c2e2e509dff2642ff106a3a9d8580b2e81d9fd306e372c4cdfb2ceb9b7e0b1b scripts/check_release_bundle.py +6c6477bbe0ab76208d1f0b0b9f4b3af2860be82f4aac068ffcad5d6d1fea1693 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index c339b24..eb680b9 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "120062d9e8ce3bcd36fd8746542fd6e6aa79da0bf44ec70c25cd6451c09e4b9d", + "product_source_sha256": "6895c0a0027e26843acbb2f8d08c12b2786b827ec23d8f40491c7f2ca953cdf3", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index 0984e58..eb964eb 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -1026,6 +1026,7 @@ def _write(path: pathlib.Path, content: str, repo: pathlib.Path) -> None: try: fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode, dir_fd=parent) with os.fdopen(fd, "wb") as handle: + os.fchmod(handle.fileno(), mode) handle.write(content.encode("utf-8")) os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent) finally: diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index cd7b437..ed6d7c6 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -383,6 +383,17 @@ def test_dangling_gitignore_is_refused_without_external_write_or_link_removal(se self.assertEqual(destination.read_text(), "preserve") self.assertEqual((root / "app.py").read_bytes(), before) + def test_atomic_mutation_preserves_existing_permissions_under_a_restrictive_umask(self): + root = self._repo() + path = root / "app.py" + path.chmod(0o664) + previous = os.umask(0o077) + try: + fast._write(path, "# changed\n", root) + finally: + os.umask(previous) + self.assertEqual(path.stat().st_mode & 0o777, 0o664) + def test_coupled_protocol_double_is_adapted_and_runtime_test_is_deferred(self): root = self._repo() result = self._run(root) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 278a4da..6b2952d 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "120062d9e8ce3bcd36fd8746542fd6e6aa79da0bf44ec70c25cd6451c09e4b9d" +PRODUCT_SOURCE_SHA256 = "6895c0a0027e26843acbb2f8d08c12b2786b827ec23d8f40491c7f2ca953cdf3" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 4c2cb23cbfbe2bbbe634e00728bdf560bb868d7c Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:03:36 -0800 Subject: [PATCH 20/22] fix: enforce finite numbers for explicit-root validator calls Follow-up for occ_1db50b0180e3b3fd5d56f963: the public validation boundary must reject non-finite numbers when callers provide root_schema, including values in open objects. --- SHA256SUMS | 8 ++--- SOURCE.json | 2 +- scripts/check_release_bundle.py | 2 +- shared/scripts/schema_validation.py | 43 ++++++++++++++---------- shared/scripts/test_schema_validation.py | 1 + 5 files changed, 33 insertions(+), 23 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 59c573b..df8b1c2 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -5032482d857d5afb328aba1234bfabf6f1959fba1c0b98c16840a8387324470f SOURCE.json +90664f46bb2adb12102a833a4dc0b33da973fb3d8bdd6dc29ff0b4958c611279 SOURCE.json 1edad0b7e0dcc065d5eca7dcca9ad7218824f62346fe6233e09a8110a9663746 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -38,12 +38,12 @@ af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tes f7e0582582c1b6b89a524acf88856557734eb1acb4a123f3729c0762e84926cc keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -6c6477bbe0ab76208d1f0b0b9f4b3af2860be82f4aac068ffcad5d6d1fea1693 scripts/check_release_bundle.py +5af9ef892abd0597fb740280be559b8cd9ea0c60b5e88ea780c81761c291ea79 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md -98b38972b470bff93158c8611a4c3d200518c1520e348f144796c3fea314d529 shared/scripts/schema_validation.py -61ba88f8850ed8a962c647fc40bed90d25ba21e7d52c21d6e377967e3b8cd6a5 shared/scripts/test_schema_validation.py +c961bd7f833e3a2d28e72257c99f1451cfe836d6ed3ecf4900215f54103d64b7 shared/scripts/schema_validation.py +7ad917958e9e20d52807951589898016d203d967939c44ba49a5a0c3e6b689e7 shared/scripts/test_schema_validation.py 640051660bb791a90eb67cea54e452e2a07420723df3c31ced71c323a6c28de3 shared/scripts/test_validate_feedback_report.py 658a2253c0aa0c25d9672ecf1e20402c28da475d6270d8770e1f29f31e35b8e0 shared/scripts/validate_feedback_report.py 2d92172fe932ee0a39c7fc97dbd15f579fb21aa93adef40f53899472781481b3 tools/public_surface.json diff --git a/SOURCE.json b/SOURCE.json index eb680b9..235b943 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "6895c0a0027e26843acbb2f8d08c12b2786b827ec23d8f40491c7f2ca953cdf3", + "product_source_sha256": "e309304aeba024135756b81fbe38378c98d7eef49d809ee3abe76b4e3c9956a0", "included_roots": [ "keel-policy", "keel-setup", diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 6b2952d..0af2598 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "6895c0a0027e26843acbb2f8d08c12b2786b827ec23d8f40491c7f2ca953cdf3" +PRODUCT_SOURCE_SHA256 = "e309304aeba024135756b81fbe38378c98d7eef49d809ee3abe76b4e3c9956a0" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", diff --git a/shared/scripts/schema_validation.py b/shared/scripts/schema_validation.py index cdad9ee..b67a4be 100644 --- a/shared/scripts/schema_validation.py +++ b/shared/scripts/schema_validation.py @@ -73,18 +73,27 @@ def validate( *, root_schema: dict[str, Any] | None = None, ) -> list[str]: - if root_schema is None: - # JSON numbers must be finite, including values in open objects and - # overflowed exponents. Check direct library callers as well as JSON. - pending = [(path, instance)] - while pending: - location, value = pending.pop() - if isinstance(value, float) and not math.isfinite(value): - return [f"{location}: number must be finite"] - if isinstance(value, dict): - pending.extend((f"{location}.{key}", child) for key, child in value.items()) - elif isinstance(value, list): - pending.extend((f"{location}[{index}]", child) for index, child in enumerate(value)) + # JSON numbers must be finite, including values in open objects and + # overflowed exponents. Check direct library callers as well as JSON. + pending = [(path, instance)] + while pending: + location, value = pending.pop() + if isinstance(value, float) and not math.isfinite(value): + return [f"{location}: number must be finite"] + if isinstance(value, dict): + pending.extend((f"{location}.{key}", child) for key, child in value.items()) + elif isinstance(value, list): + pending.extend((f"{location}[{index}]", child) for index, child in enumerate(value)) + return _validate(instance, schema, path, root_schema=root_schema) + + +def _validate( + instance: Any, + schema: dict[str, Any], + path: str = "$", + *, + root_schema: dict[str, Any] | None = None, +) -> list[str]: root_schema = schema if root_schema is None else root_schema unknown_keywords = set(schema) - SUPPORTED if unknown_keywords: @@ -95,13 +104,13 @@ def validate( if referenced is None: failures.append(f"{path}: unsupported or missing schema reference {schema['$ref']!r}") else: - failures.extend(validate(instance, referenced, path, root_schema=root_schema)) + failures.extend(_validate(instance, referenced, path, root_schema=root_schema)) if "anyOf" in schema: - branches = [validate(instance, branch, path, root_schema=root_schema) for branch in schema["anyOf"]] + branches = [_validate(instance, branch, path, root_schema=root_schema) for branch in schema["anyOf"]] if not any(not branch for branch in branches): failures.append(f"{path}: value matches no anyOf branch") if "oneOf" in schema: - branches = [validate(instance, branch, path, root_schema=root_schema) for branch in schema["oneOf"]] + branches = [_validate(instance, branch, path, root_schema=root_schema) for branch in schema["oneOf"]] if sum(not branch for branch in branches) != 1: failures.append(f"{path}: value must match exactly one oneOf branch") if "const" in schema and instance != schema["const"]: @@ -125,7 +134,7 @@ def validate( failures.append(f"{path}: unknown property {key!r}") for key, value in instance.items(): if key in properties: - failures.extend(validate(value, properties[key], f"{path}.{key}", root_schema=root_schema)) + failures.extend(_validate(value, properties[key], f"{path}.{key}", root_schema=root_schema)) if isinstance(instance, list): if len(instance) < schema.get("minItems", 0): failures.append(f"{path}: has fewer than {schema['minItems']} items") @@ -138,7 +147,7 @@ def validate( item_schema = schema.get("items") if item_schema: for index, value in enumerate(instance): - failures.extend(validate(value, item_schema, f"{path}[{index}]", root_schema=root_schema)) + failures.extend(_validate(value, item_schema, f"{path}[{index}]", root_schema=root_schema)) if isinstance(instance, str): if len(instance) < schema.get("minLength", 0): failures.append(f"{path}: is shorter than {schema['minLength']} characters") diff --git a/shared/scripts/test_schema_validation.py b/shared/scripts/test_schema_validation.py index 3fa810f..387b06d 100644 --- a/shared/scripts/test_schema_validation.py +++ b/shared/scripts/test_schema_validation.py @@ -42,6 +42,7 @@ def test_nonfinite_numbers_are_rejected_even_in_open_objects(self): ({"open": [value]}, {"type": "object"})): with self.subTest(raw=raw): self.assertTrue(schema_validation.validate(candidate, schema)) + self.assertTrue(schema_validation.validate(candidate, schema, root_schema=schema)) self.assertEqual(schema_validation.validate(0.5, {"type": "number", "exclusiveMinimum": 0}), []) def test_required_types_limits_unknowns_and_uniqueness(self): From 8caea38b101d72fda7a9d94aa7a6383527ca4fc6 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:16:53 -0800 Subject: [PATCH 21/22] test: give fixture commits an explicit git identity Two fast-first-run fixtures committed without -c user.name/user.email, so they passed on machines with a global git identity and failed on CI runners (git commit exit 128). Product digest and SHA256SUMS regenerated. Co-Authored-By: Claude Opus 5.5 --- SHA256SUMS | 6 +++--- SOURCE.json | 2 +- keel-setup/tests/test_fast_first_run.py | 4 ++-- scripts/check_release_bundle.py | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index df8b1c2..12cc268 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -90664f46bb2adb12102a833a4dc0b33da973fb3d8bdd6dc29ff0b4958c611279 SOURCE.json +41de4a7b36b49354d8619debc664f4392251a33ef99f1b6a90fbe64697ed1be8 SOURCE.json 1edad0b7e0dcc065d5eca7dcca9ad7218824f62346fe6233e09a8110a9663746 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -31,14 +31,14 @@ bcbf12085c0776d35189965a1832a0802d782df1d8e918e6166d6eaf36e5a236 keel-setup/scr d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -ff46b9b7c6625f3dc2547943dc9e425303c5dcefa100c4ff9246c48d68cf3418 keel-setup/tests/test_fast_first_run.py +ab23aefa136022abda2e92eaf681052a5b1d7c9c17444241476011d331eb666f keel-setup/tests/test_fast_first_run.py 305e9fcc3f861809422cf39cf12fd16785d7bcf48eb2f27b140ff009d478ef8b keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py f7e0582582c1b6b89a524acf88856557734eb1acb4a123f3729c0762e84926cc keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -5af9ef892abd0597fb740280be559b8cd9ea0c60b5e88ea780c81761c291ea79 scripts/check_release_bundle.py +a710c78049ef434e14fd8675a94233e5e507a6822586b0eb1f03853965c3a66d scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index 235b943..1e05726 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "e309304aeba024135756b81fbe38378c98d7eef49d809ee3abe76b4e3c9956a0", + "product_source_sha256": "9121c2e3aef2356472d8c1eb3bd5bd4cb3bf501e064d629bc124f16758a89ba7", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index ed6d7c6..ee75547 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -373,7 +373,7 @@ def test_dangling_gitignore_is_refused_without_external_write_or_link_removal(se ignore.unlink() ignore.symlink_to(destination) _git(root, "add", ".gitignore") - _git(root, "commit", "-qm", "symlink fixture") + _git(root, "-c", "user.name=Keel Test", "-c", "user.email=keel-test@example.invalid", "commit", "-qm", "symlink fixture") before = (root / "app.py").read_bytes() result = self._run(root) self.assertEqual(result["outcome"], "validation_failed", result) @@ -529,7 +529,7 @@ def test_unrecognized_security_logic_and_extra_tests_are_preserved_by_refusal(se source = path.read_text() + "\ndef test_extra_authorization():\n assert authorized()\n" path.write_text(source) _git(root, "add", ".") - _git(root, "commit", "-qm", "extra test") + _git(root, "-c", "user.name=Keel Test", "-c", "user.email=keel-test@example.invalid", "commit", "-qm", "extra test") result = self._run(root) self.assertEqual(result["outcome"], "model_review_required", result) self.assertEqual(path.read_text(), source) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 0af2598..68b9a35 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "e309304aeba024135756b81fbe38378c98d7eef49d809ee3abe76b4e3c9956a0" +PRODUCT_SOURCE_SHA256 = "9121c2e3aef2356472d8c1eb3bd5bd4cb3bf501e064d629bc124f16758a89ba7" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 6293ea377cdc01a581a908abd67cd7e7947c6df6 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:52:43 -0800 Subject: [PATCH 22/22] fix: sync the bundle with its reviewed source after both security passes The private source now carries every fix from this pull request and from its own security pass, one implementation per file. This commit republishes that source, so the bundle matches it byte for byte again. New from the source pass: bounded descriptor reads (shared/scripts/ bounded_input.py), schema-validation work and complexity budgets, enforceability validation scope and surface availability matrix, the validation_scope and unverified_claims report fields, bounded feedback input, and stricter refusal of rewrites and symlinked .keel paths. Behavior changes from this pull request's head: the deferred focused test is reported as prepared_compatibility_test, and focused_compatibility_test is null. Rollback removes setup state only when this run created it. The inventory charges bytes actually read and budgets printed output. The setup state cap is 1 MB, so schema-valid states persist. The allowlist gains bounded_input.py and its test. The product digest, SOURCE.json and SHA256SUMS are regenerated. Co-Authored-By: Claude Opus 5.5 --- SHA256SUMS | 40 +++++---- SOURCE.json | 2 +- keel-policy/SKILL.md | 28 ++++-- .../enforceability-report.schema.json | 10 ++- .../reference/policy-document.schema.json | 3 +- .../scripts/validate_enforceability_report.py | 34 +++++-- .../test_authoring_context_consumption.py | 2 + .../test_validate_enforceability_report.py | 47 +++++++++- keel-setup/SKILL.md | 27 ++++-- keel-setup/scripts/fast_first_run.py | 44 ++++++--- keel-setup/scripts/inventory.py | 16 +++- keel-setup/scripts/setup_state.py | 4 +- keel-setup/tests/test_fast_first_run.py | 78 +++++++++++++++- keel-setup/tests/test_inventory.py | 70 ++++++++++++++- keel-setup/tests/test_setup_state.py | 45 +++++++++- scripts/check_release_bundle.py | 4 +- shared/scripts/bounded_input.py | 23 +++++ shared/scripts/schema_validation.py | 89 +++++++++++++------ shared/scripts/test_bounded_input.py | 44 +++++++++ shared/scripts/test_schema_validation.py | 5 ++ .../scripts/test_validate_feedback_report.py | 12 +++ shared/scripts/validate_feedback_report.py | 14 +-- 22 files changed, 538 insertions(+), 103 deletions(-) create mode 100644 shared/scripts/bounded_input.py create mode 100644 shared/scripts/test_bounded_input.py diff --git a/SHA256SUMS b/SHA256SUMS index 12cc268..427ac28 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,48 +2,50 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -41de4a7b36b49354d8619debc664f4392251a33ef99f1b6a90fbe64697ed1be8 SOURCE.json -1edad0b7e0dcc065d5eca7dcca9ad7218824f62346fe6233e09a8110a9663746 keel-policy/SKILL.md +dcbb4164927a68d4c0428b2eb4926d7c8b30fd3c986c9acd8bd4d37a51f6fb56 SOURCE.json +227c399c3ab3a7317982f709a151efd7705c4d30ddc96fdf31c62302f0faccd3 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json 2a52514e8db0901ab73e59b924f195008541d0069ebad9b514bd373cb905e2d2 keel-policy/examples/stripe-refund-approval.json -4ba18a72ba701fd0f21c8c341676bbbe823728fa7b286c97109df02b81b47936 keel-policy/reference/enforceability-report.schema.json +49f43e551f32e484e263fa026dfd4fde5a8b50cd462f0f68e06ae371380f3b24 keel-policy/reference/enforceability-report.schema.json 91fa5bbc7696846ec0d0039a88585ac99852b50a73613f92fea552f6931e7c44 keel-policy/reference/field-provenance.json 54416bf9c9af8f8fb75a9e883aa27aa62ecbcdffc2b1b6698d5fa1479fd6ddda keel-policy/reference/fields.md -5d4e384a5c0047b951569ce8e0956eeef7f233f736adea08c56c5d7f4575c138 keel-policy/reference/policy-document.schema.json +9d86eeb4fecf6db831856c0b77b9e83caeb161ec82d046eaf4fc2f8e73d96f27 keel-policy/reference/policy-document.schema.json 7d662cffa24744af7a26f62d813127b4bc0a44ff62f725c883054165ddec3272 keel-policy/scripts/consume_authoring_context.py -4dfdfbf56fb811a565e5f3c9f28ec3ff137303148fa13a8d29a979ffb95e2d96 keel-policy/scripts/validate_enforceability_report.py -6da76e3ac418a133894d498e0d2afa97b91036a72097f077b9853f6447f6d912 keel-policy/tests/test_authoring_context_consumption.py +d8a8ad9886f43efb6b5b7065ef167150b2c8b03f640cc8647f52680ae211e2eb keel-policy/scripts/validate_enforceability_report.py +ff71e2933eb4ab5be18d5fa41eb324a376ffd460c39157ecd6db39bfc016ee44 keel-policy/tests/test_authoring_context_consumption.py 820069a6ce02f74dccc4f57a5788359b1377520330d00ba88471d60fec901f17 keel-policy/tests/test_basic_profile_fields.py -607da38ca6191c555bfcf5d8e595a845b605ed106180e293b3d5669f9bc41800 keel-policy/tests/test_validate_enforceability_report.py -383d08c6433e906b3082a9346f81bbc429b08b8124fd00a38ec3bbb9d44d56b4 keel-setup/SKILL.md +7c061516afc0a8618bf9f3b02bdd907678447047c268f82a2d1579cb3d2bd84c keel-policy/tests/test_validate_enforceability_report.py +5aba155e2711a4bfd0241ce41ca97982effe53473764e669bcdfe9ea47aed4a7 keel-setup/SKILL.md 2b9c2490e921e83b83372a09e422a30f0f7ee338a2809b8e07edbd381d9eb650 keel-setup/reference/coverage.schema.json 70a69dcab29f61aaa3f96de5f65854fca63c4549ddc20d84ee00e102fc68c691 keel-setup/reference/integration_profiles.v1.json 9739501499b286d40f356af9c0378bbdcde41a364be083ccbc34adb000575160 keel-setup/reference/setup-state.schema.json 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md 580edac4805c13a2b88b7dde613bf3a388347c9d00c6f9488c1ceb9e593368d3 keel-setup/scripts/authoring_context.py -e782760ec3132b491b62e4be6bd2c38df328f3782e3f9a6571bfe19daac34b7e keel-setup/scripts/fast_first_run.py -b095a7c5dd344db6ac71685cbea8146b1b837a5ab3cae42280cf1626cf5addda keel-setup/scripts/inventory.py +e7736b2abbb475472befa4a53cd1b7b5dd2c55318645472c74be6e56b43e57c4 keel-setup/scripts/fast_first_run.py +b81c2c37fe70176a006ef5e5b0904d06609d7a4ca8f3cababae652d9f2254a09 keel-setup/scripts/inventory.py e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py -bcbf12085c0776d35189965a1832a0802d782df1d8e918e6166d6eaf36e5a236 keel-setup/scripts/setup_state.py +04f0dd71d74930ccb065202769f01f2afff559f395acc93937813f60a2793558 keel-setup/scripts/setup_state.py 1bc3d136fe06414a090976712c96fef0f46d7922ed3cd5cf502fa174de1aa86d keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 5566957697d9e33782af0ecd1037b0b661a8b32e365939ffb33d72abc93caf10 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -ab23aefa136022abda2e92eaf681052a5b1d7c9c17444241476011d331eb666f keel-setup/tests/test_fast_first_run.py -305e9fcc3f861809422cf39cf12fd16785d7bcf48eb2f27b140ff009d478ef8b keel-setup/tests/test_inventory.py +6cb0fbad8e3e34ca65087c02f5498375cf91be7d86b0697401fcae27af4d89e0 keel-setup/tests/test_fast_first_run.py +9c3b0e8727848dfb52b499236b31c9a43e2a0649452c3df6783207ee12073c92 keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py -f7e0582582c1b6b89a524acf88856557734eb1acb4a123f3729c0762e84926cc keel-setup/tests/test_setup_state.py +c8006372327167f6317d7ae41d79da3c2dd45a7510f1cdc544616facd27d9d83 keel-setup/tests/test_setup_state.py ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -a710c78049ef434e14fd8675a94233e5e507a6822586b0eb1f03853965c3a66d scripts/check_release_bundle.py +964fd01c1ac92ddb340e5afd068647f8f42c2c1c9185af8779c68ad9d7351eba scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md -c961bd7f833e3a2d28e72257c99f1451cfe836d6ed3ecf4900215f54103d64b7 shared/scripts/schema_validation.py -7ad917958e9e20d52807951589898016d203d967939c44ba49a5a0c3e6b689e7 shared/scripts/test_schema_validation.py -640051660bb791a90eb67cea54e452e2a07420723df3c31ced71c323a6c28de3 shared/scripts/test_validate_feedback_report.py -658a2253c0aa0c25d9672ecf1e20402c28da475d6270d8770e1f29f31e35b8e0 shared/scripts/validate_feedback_report.py +378cd5a1c96810c36054553bde92c137deceec890a5c046a8e8d9a7bfecce51b shared/scripts/bounded_input.py +e64ed436bc35d73cdad6366f2dd3f01530426cb529237d2990be07171c93b08c shared/scripts/schema_validation.py +0e15d2320554d19fddd24299afc807317c6313d7cd96c6fe0fd3dbaf25558fad shared/scripts/test_bounded_input.py +4cbb3be5a54865a85549400f7c57610a7284623899674c0902354b870b1980ad shared/scripts/test_schema_validation.py +8f7c8bfd8ec6bc7faab7ea1341365ba67f31846232a2c3acac5f7c4bdaa3c411 shared/scripts/test_validate_feedback_report.py +696a0c609ef7895cfe3737942dc4e32feeeb870bbd23689fbeee965752498587 shared/scripts/validate_feedback_report.py 2d92172fe932ee0a39c7fc97dbd15f579fb21aa93adef40f53899472781481b3 tools/public_surface.json diff --git a/SOURCE.json b/SOURCE.json index 1e05726..fce714d 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "9121c2e3aef2356472d8c1eb3bd5bd4cb3bf501e064d629bc124f16758a89ba7", + "product_source_sha256": "7481bc4de5400d2dd00af9cbe6c449d090dac7806a90fdb7d144e65195bdf293", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-policy/SKILL.md b/keel-policy/SKILL.md index f23ec71..6dc08b7 100644 --- a/keel-policy/SKILL.md +++ b/keel-policy/SKILL.md @@ -87,26 +87,42 @@ Choose one explicit mode and keep one intent ledger across it: Each handoff contains: the human intent, policy JSON when one can be drafted faithfully, an evaluation-order readback, an enforceability report, the activation effect (`narrows`, `widens`, -`ambiguous`, `unchanged`, or `unresolved`), blocked requests, and the exact human next step. Validate an +`ambiguous`, `unchanged`, or `unresolved`), blocked requests, and the exact human next step. Check an enforceability report with `scripts/validate_enforceability_report.py`. For an embedded policy, use `rules[0]`, `rules[1]`, and so on as exact rule references, with one entry for each fact consumed by each rule. The machine report's `readback` must equal the validator's `derive_readback(policy)`; keep any additional friendly explanation outside that validated field. `safe_outcome` must agree -with the referenced action. Keep `activation_effect` as `unresolved` without an authenticated active -policy baseline. Human `intent` remains a declaration for human review, not a proved policy effect. -Actions whose implicit runtime facts or capabilities lack a pinned trusted evidence contract cannot -pass offline enforceability qualification; report the missing contract instead of claiming support. -A blocked report is a successful +with the referenced action. Actions whose implicit runtime facts or capabilities lack a pinned trusted +evidence contract cannot pass offline enforceability qualification; report the missing contract +instead of claiming support. Beyond those structural bindings, this helper checks schema and field +provenance only; it does not verify outcomes, readback meaning, rule ordering, activation deltas, or +runtime enforcement. Every report must set `validation_scope` to `schema_and_field_provenance_only`, +`unverified_claims` to `["safe_outcome", "readback", "rule_order", "activation_effect", "runtime_enforcement"]`, +and `activation_effect` to `unresolved`, because no authenticated active-policy baseline exists offline. +Human `intent` remains a declaration for human review, not a proved policy effect. Treat `safe_outcome` +and readback as unverified author claims. Never use a passing helper result as approval to activate +or as proof a restriction is enforced. A blocked report is a successful diagnosis; never change the requested restriction to make validation pass. Every non-null embedded `policy` is validated against the committed `reference/policy-document.schema.json`; a legacy or approximate `when`/`decision` shape is not a policy proposal and must fail closed before the enforceability cross-check. +Offline report input is limited to a regular file of 1,000,000 bytes, 24 nesting levels, +10,000 nodes, and 1,000 children per container. Schema validation has a 50,000-step +work budget and returns at most 50 schema failures. Split larger proposals before validation. + The validator reads `reference/field-provenance.json`, a release-pinned machine artifact whose field set and provenance values are checked against the published catalog. A report cannot promote a caller- or connector-asserted field to `trusted` by relabelling it. +Report surfaces are closed identifiers: `managed_execute`, `managed_mcp`, `realtime`, or `voice`. +The offline helper conservatively admits trusted `provider` and `model` only on `managed_execute`, +and trusted connector identity/tool name only on `managed_mcp`. Other field/surface combinations +remain unresolved until the pinned availability contract is extended with route evidence. In +particular, connector tool name is unavailable on `realtime` and `voice`; mark it unavailable or +unresolved and block restrictions that depend on it. Provenance alone never establishes availability. + 1. **Get the authoring profile.** With a safe authoring-context v2 JSON block, validate it using the offline intake below and use its `authoring_level`: `template`, `basic`, or `full`. Never ask which policy editor the human sees, ask them to infer their authoring level, or diff --git a/keel-policy/reference/enforceability-report.schema.json b/keel-policy/reference/enforceability-report.schema.json index 8f1fe79..b1d7dbc 100644 --- a/keel-policy/reference/enforceability-report.schema.json +++ b/keel-policy/reference/enforceability-report.schema.json @@ -1,12 +1,14 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://keelapi.com/schemas/enforceability-report.v1.json", - "title": "Keel policy enforceability report", + "title": "Keel policy schema and field-provenance report", "type": "object", "additionalProperties": false, - "required": ["schema_version", "intent", "policy", "readback", "enforceability", "activation_effect", "blocked_requests", "human_next_step"], + "required": ["schema_version", "validation_scope", "unverified_claims", "intent", "policy", "readback", "enforceability", "activation_effect", "blocked_requests", "human_next_step"], "properties": { "schema_version": {"const": "1.0"}, + "validation_scope": {"const": "schema_and_field_provenance_only"}, + "unverified_claims": {"const": ["safe_outcome", "readback", "rule_order", "activation_effect", "runtime_enforcement"]}, "intent": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1, "maxLength": 1000}, "maxItems": 100}, "policy": {"type": ["object", "null"]}, "readback": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1, "maxLength": 2000}, "maxItems": 200}, @@ -21,7 +23,7 @@ "rule_reference": {"type": "string", "minLength": 1, "maxLength": 256}, "required_fact": {"type": "string", "minLength": 1, "maxLength": 512}, "field": {"type": ["string", "null"], "maxLength": 512}, - "surface": {"type": "string", "minLength": 1, "maxLength": 128}, + "surface": {"enum": ["managed_execute", "managed_mcp", "realtime", "voice"]}, "provenance": {"enum": ["keel_derived", "connector_asserted", "caller_asserted", "human_asserted", "unavailable", "unresolved"]}, "status": {"enum": ["trusted", "untrusted", "unavailable", "unresolved"]}, "safe_outcome": {"enum": ["auto_allow", "review", "deny", "proposal_only", "blocked"]}, @@ -30,7 +32,7 @@ } } }, - "activation_effect": {"enum": ["narrows", "widens", "ambiguous", "unchanged", "unresolved"]}, + "activation_effect": {"const": "unresolved"}, "blocked_requests": { "type": "array", "maxItems": 200, diff --git a/keel-policy/reference/policy-document.schema.json b/keel-policy/reference/policy-document.schema.json index 27422f1..ac331ec 100644 --- a/keel-policy/reference/policy-document.schema.json +++ b/keel-policy/reference/policy-document.schema.json @@ -140,8 +140,7 @@ }, "external_workflow": { "type": "null", - "default": null, - "description": "No closed external workflow contract is published in this offline bundle." + "default": null }, "group_id": { "anyOf": [ diff --git a/keel-policy/scripts/validate_enforceability_report.py b/keel-policy/scripts/validate_enforceability_report.py index 76d2290..f0c2462 100644 --- a/keel-policy/scripts/validate_enforceability_report.py +++ b/keel-policy/scripts/validate_enforceability_report.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Offline validator for Keel policy enforceability reports.""" +"""Offline schema and field-provenance checks; no policy-outcome certification.""" from __future__ import annotations import argparse @@ -12,15 +12,27 @@ ROOT = pathlib.Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "shared" / "scripts")) -from schema_validation import validate as validate_schema # noqa: E402 +from bounded_input import read_bytes +from schema_validation import complexity_failures, validate as validate_schema # noqa: E402 MANIFEST = ROOT / "tools" / "public_surface.json" SCHEMA = ROOT / "keel-policy" / "reference" / "enforceability-report.schema.json" PROVENANCE = ROOT / "keel-policy" / "reference" / "field-provenance.json" POLICY_SCHEMA = ROOT / "keel-policy" / "reference" / "policy-document.schema.json" +MAX_REPORT_BYTES = 1_000_000 BOUND_TOOL_NAME = "context._keel.action_envelope.connector.tool_name.value" PROHIBITED_KEYS = {"certified_action_contract_id", "activation", "is_active", "credential", "api_key", "token"} NON_EFFECTING_ACTIONS = {"preview"} +# Conservative positive availability contract. Other derived fields require a +# future source-backed matrix update; global provenance alone is insufficient. +SURFACE_FIELDS = { + "managed_execute": {"provider", "model"}, + "managed_mcp": { + "context._keel.action_envelope.connector.identity.value", BOUND_TOOL_NAME, + }, + "realtime": set(), + "voice": set(), +} ACTION_DEPENDENCIES: dict[str, tuple[str, ...] | None] = { "allow": (), "deny": (), "preview": (), "require_human_review": (), "constrain_max_output_tokens": (), "constrain_permit_lifetime": (), @@ -93,6 +105,9 @@ def validate( schema: dict[str, Any], policy_schema: dict[str, Any], ) -> list[str]: + limits = complexity_failures(report, max_nodes=10_000, max_items=1_000, max_text=1_000_000) + if limits: + return limits failures = validate_schema(report, schema) if not isinstance(report, dict): return failures @@ -119,6 +134,13 @@ def validate( by_rule_field.setdefault((reference, field), []).append((index, item)) status = item.get("status") pinned_provenance = provenance.get(field) if isinstance(field, str) else None + surface = item.get("surface") + if not isinstance(surface, str) or surface not in SURFACE_FIELDS: + failures.append(f"enforceability[{index}] unsupported execution surface") + elif status == "trusted" and field not in SURFACE_FIELDS[surface]: + failures.append(f"enforceability[{index}] field availability is not established on {surface}; use unavailable or unresolved") + if field == BOUND_TOOL_NAME and surface in {"realtime", "voice"} and status not in {"unavailable", "unresolved"}: + failures.append(f"enforceability[{index}] connector tool name is unavailable on {surface}") if isinstance(field, str) and field not in public_fields: if status != "unresolved": failures.append(f"enforceability[{index}] unpublished field must be unresolved") @@ -188,7 +210,7 @@ def validate( ) if field in dependencies and item.get("surface") != "managed_execute": failures.append(f"policy.rules[{rule_index}] implicit field {field!r} requires the managed_execute surface") - return failures + return failures[:100] def main(argv: list[str] | None = None) -> int: @@ -196,12 +218,12 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("report", type=pathlib.Path) args = parser.parse_args(argv) try: - report = json.loads(args.report.read_text(encoding="utf-8")) + report = json.loads(read_bytes(args.report, MAX_REPORT_BYTES)) manifest = json.loads(MANIFEST.read_text(encoding="utf-8")) provenance = json.loads(PROVENANCE.read_text(encoding="utf-8")) schema = json.loads(SCHEMA.read_text(encoding="utf-8")) policy_schema = json.loads(POLICY_SCHEMA.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as exc: + except (OSError, ValueError, RecursionError) as exc: print(f"invalid input: {exc}", file=sys.stderr) return 1 failures = validate(report, manifest, provenance, schema, policy_schema) @@ -209,7 +231,7 @@ def main(argv: list[str] | None = None) -> int: for failure in failures: print(failure, file=sys.stderr) return 1 - print("valid enforceability report") + print("schema and field-provenance checks passed; outcomes, readback, rule order, activation effect, and runtime enforcement remain unverified") return 0 diff --git a/keel-policy/tests/test_authoring_context_consumption.py b/keel-policy/tests/test_authoring_context_consumption.py index cbf2cca..31ed90c 100644 --- a/keel-policy/tests/test_authoring_context_consumption.py +++ b/keel-policy/tests/test_authoring_context_consumption.py @@ -259,6 +259,8 @@ def read(relative): status='trusted', safe_outcome='deny', reason='Published Keel-derived model/provider contract.', replacement_field=None) for index, field in ((0, 'provider'), (1, 'provider'), (1, 'model'))], 'activation_effect': 'unresolved', 'blocked_requests': [], + 'validation_scope': 'schema_and_field_provenance_only', + 'unverified_claims': ['safe_outcome', 'readback', 'rule_order', 'activation_effect', 'runtime_enforcement'], 'human_next_step': out['handoff'], } failures = validator.validate(report, read('tools/public_surface.json'), diff --git a/keel-policy/tests/test_validate_enforceability_report.py b/keel-policy/tests/test_validate_enforceability_report.py index 8511b5d..c6ba879 100644 --- a/keel-policy/tests/test_validate_enforceability_report.py +++ b/keel-policy/tests/test_validate_enforceability_report.py @@ -3,6 +3,8 @@ import importlib.util import json import pathlib +import os +import tempfile import unittest SCRIPT = pathlib.Path(__file__).parents[1] / "scripts" / "validate_enforceability_report.py" @@ -20,6 +22,8 @@ def report(field="action.name", status="untrusted", replacement=validator.BOUND_TOOL_NAME): return { "schema_version": "1.0", + "validation_scope": "schema_and_field_provenance_only", + "unverified_claims": ["safe_outcome", "readback", "rule_order", "activation_effect", "runtime_enforcement"], "intent": ["Require review for this exact MCP tool."], "policy": None, "readback": ["The rule requires human review."], @@ -47,9 +51,50 @@ def add_policy(candidate, field, action="allow"): class EnforceabilityValidatorTest(unittest.TestCase): + def test_deep_and_wide_reports_refuse_before_recursive_validation(self): + candidate = report() + value = {} + for _ in range(100): + value = {"not": value} + candidate["policy"] = value + self.assertTrue(any("nesting limit" in item for item in validate(candidate))) + candidate["policy"] = {"rules": [{}] * 1001} + self.assertTrue(any("item limit" in item for item in validate(candidate))) + + def test_cli_refuses_oversize_fifo_and_parser_recursion(self): + with tempfile.TemporaryDirectory() as directory: + path = pathlib.Path(directory) / "input" + for content in (b"x" * (validator.MAX_REPORT_BYTES + 1), b"[" * 2000 + b"]" * 2000): + path.write_bytes(content) + self.assertEqual(validator.main([str(path)]), 1) + path.unlink() + os.mkfifo(path) + self.assertEqual(validator.main([str(path)]), 1) + + def test_report_cannot_claim_semantic_certification_or_activation_delta(self): + candidate = report() + candidate["activation_effect"] = "narrows" + self.assertTrue(validate(candidate)) + + def test_trust_requires_availability_on_a_closed_execution_surface(self): + for surface in ("realtime", "voice", "arbitrary_route"): + candidate = report(field=validator.BOUND_TOOL_NAME, status="trusted", replacement=None) + candidate["enforceability"][0]["surface"] = surface + self.assertTrue(validate(candidate), surface) + candidate = report(field=validator.BOUND_TOOL_NAME, status="trusted", replacement=None) + self.assertEqual(validate(candidate), []) + candidate["enforceability"][0].update(surface="voice", status="unavailable", safe_outcome="blocked") + self.assertEqual(validate(candidate), []) + candidate = report() + candidate["unverified_claims"] = [] + self.assertTrue(validate(candidate)) + candidate = report() + candidate["validation_scope"] = "certified_enforceable" + self.assertTrue(validate(candidate)) def test_rule_effects_readback_and_references_are_structurally_bound(self): candidate = add_policy(report(field="provider", status="trusted", replacement=None), "provider", "allow") - candidate["enforceability"][0]["safe_outcome"] = "auto_allow" + # Trusted provider is available only on managed_execute (surface matrix). + candidate["enforceability"][0].update(safe_outcome="auto_allow", surface="managed_execute") candidate["readback"] = validator.derive_readback(candidate["policy"]) self.assertEqual(validate(candidate), []) for key, value in (("readback", ["Requires review only"]), ("activation_effect", "narrows")): diff --git a/keel-setup/SKILL.md b/keel-setup/SKILL.md index 2fe1012..1b3ae7e 100644 --- a/keel-setup/SKILL.md +++ b/keel-setup/SKILL.md @@ -209,7 +209,7 @@ It supports exactly one clean Python application shape: one non-streaming offici recognized `client=None` injection hook and, at most, one directly coupled test file. It verifies the official immutable bundle, classifies the repository without importing it, reuses the bounded fast scanner, preserves the callable signature, generates the fixed `/v1/execute` adapter and coupled -test when required, validates the narrow patch, and persists `waiting_for_human` only on a complete +test when required, compiles it without execution, validates the narrow patch, and persists `waiting_for_human` only on a complete pass. It reads no credential and grants no authority. Do not search the web, consult or cite saved memory, enumerate bundle files, inspect verifier source, @@ -217,10 +217,13 @@ inspect bundle history, run the release verifier separately, rediscover the seam contract, regenerate the integration, handle setup state separately, rerun the scanner, repeat validation or tests, or add intermediate narration on a recognized golden path. -When the result is `ready_for_human`, its `diff` result contains only counts and digests. Inspect one -targeted local `git diff` over `validation.changed_paths` before the gate. Keep source hunks and -literal defaults out of model conversation, stdout reports, and logs. Do not remove this independent -local review. Render the canonical First human gate block verbatim, substituting only the helper-established +When the result is `ready_for_human`, its `diff` result contains only counts and digests: inspect the +helper's diff digest and per-file statistics. The helper deliberately omits source text because source +diffs can contain credentials. Have the human review the exact local diff in their editor, or with one +targeted local `git diff` over `validation.changed_paths` in their own terminal, before continuing. +Keep source hunks and literal defaults out of model conversation, stdout reports, and logs; do not +print or copy that source into the chat. Do not remove this independent narrow-diff review. +Render the canonical First human gate block verbatim, substituting only the helper-established `PATH`, then wait. The deterministic helper's golden path is OpenAI-only; do not reuse its guided dashboard sequence for another provider. The helper result is source-inspected local preparation only; it is not runtime evidence. @@ -271,9 +274,11 @@ allows it; never broaden the helper's claimed support from resemblance alone. `summarize(text, *, model=None)` merely because the implementation no longer uses the injected provider client internally. Compatibility must not preserve a hook that can bypass Keel: when an existing provider-client hook is used by a directly relevant caller or test and cannot safely keep - its behavior through Keel, inspect the directly relevant caller/test statically before the gate. - Defer runtime compatibility checks until isolated post-gate validation. If static review shows a - callable contract change is necessary, stop for explicit human direction instead of recording + its behavior through Keel, prepare and compile that one focused test without importing the + application or invoking it, and inspect the directly relevant caller/test statically before the gate. + Defer runtime compatibility checks until isolated post-gate validation; runtime compatibility remains + unverified before the gate. If static review shows a callable contract change is necessary, + stop for explicit human direction instead of recording `waiting_for_human`. Before the first gate, modify only the production integration path and an unavoidable dependency manifest when the existing runtime has no suitable HTTP facility. Do not add or edit application @@ -776,6 +781,12 @@ python3 -I "$BUNDLE/keel-setup/scripts/inventory.py" --root . Cover model SDKs and direct HTTP calls, MCP servers/clients/tool registrations/handlers, background work, nested calls, direct handler paths, streaming, credentials, and egress signals. +The inventory caps traversal at 10,000 entries, 512 directories, 24 directory levels, 2,000 files, +16 MB read, 20,000 lines per file, 1,000 matches, ten seconds, and 512 KB of output. Skipped +dependency/build trees are pruned. When any cap is reached the helper refuses with a nonzero exit +instead of emitting a partial inventory; a refusal establishes no discovery. Inspect smaller roots +to continue and carry the refusal into the handoff. + Update application setup documentation here when the repository needs it. Protocol-double and documentation work remain required assurance where relevant; only their ordering moved. diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index eb964eb..15e6318 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -373,6 +373,8 @@ def classify_repository(repo: pathlib.Path) -> dict[str, Any]: revision = _git(repo, "rev-parse", "HEAD") if re.fullmatch(r"[0-9a-f]{40}", revision) is None: raise PipelineFailure("model_review_required", "repository has no immutable Git revision") + if (repo / ".keel").is_symlink() or (repo / ".keel" / "setup-state.json").is_symlink(): + raise PipelineFailure("model_review_required", "local setup paths must not be symlinks") instruction_names = {"AGENTS.md", "CLAUDE.md", ".cursorrules", "copilot-instructions.md"} instructions: list[str] = [] @@ -974,8 +976,10 @@ def validate_patch( "freshness_at_request_time": True, "credential_value_absent": True, "changed_paths": sorted(allowed_paths), - "focused_compatibility_test": focused_test, + "focused_compatibility_test": None, "focused_compatibility_test_status": "deferred_requires_isolation" if focused_test else "not_applicable", + "prepared_compatibility_test": focused_test, + "runtime_compatibility": "not_executed_before_human_gate", } @@ -1050,7 +1054,7 @@ def _ensure_state_ignored(repo: pathlib.Path) -> bool: return True -def _restore(repo: pathlib.Path, originals: dict[pathlib.PurePosixPath, bytes | None]) -> None: +def _restore(repo: pathlib.Path, originals: dict[pathlib.PurePosixPath, bytes | None], *, remove_state: bool = False) -> None: for relative, content in originals.items(): path = repo.joinpath(*relative.parts) if content is None: @@ -1061,16 +1065,28 @@ def _restore(repo: pathlib.Path, originals: dict[pathlib.PurePosixPath, bytes | pass else: _write(path, content.decode("utf-8"), repo) - state = repo / ".keel" / "setup-state.json" + if not remove_state: + return + # Remove only state this run created: no-follow descriptors, regular file only. + parent = os.open(repo, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) try: - with _mutation_parent(state, repo) as (parent, name): - os.unlink(name, dir_fd=parent) - except FileNotFoundError: - pass - try: - state.parent.rmdir() - except OSError: - pass + try: + local = os.open(".keel", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + except OSError: + return + try: + if stat.S_ISREG(os.stat("setup-state.json", dir_fd=local, follow_symlinks=False).st_mode): + os.unlink("setup-state.json", dir_fd=local) + except OSError: + pass + finally: + os.close(local) + try: + os.rmdir(".keel", dir_fd=parent) + except OSError: + pass + finally: + os.close(parent) def _line_change_stats(before: str, after: str) -> tuple[int, int, int]: @@ -1164,6 +1180,7 @@ def run_pipeline(bundle: pathlib.Path, bundle_sha: str, repo: pathlib.Path) -> d timings: dict[str, float] = {} originals: dict[pathlib.PurePosixPath, bytes | None] = {} edited = False + state_created = False try: bundle = bundle.resolve() mark = time.perf_counter() @@ -1222,6 +1239,7 @@ def run_pipeline(bundle: pathlib.Path, bundle_sha: str, repo: pathlib.Path) -> d initialized = setup_state.begin(state_path, repo) if not initialized.get("state_persisted"): raise PipelineFailure("validation_failed", "setup state initialization failed") + state_created = True failures = setup_state.mark_waiting_for_human( state_path, repo, @@ -1250,7 +1268,7 @@ def run_pipeline(bundle: pathlib.Path, bundle_sha: str, repo: pathlib.Path) -> d } except PipelineFailure as exc: if edited: - _restore(repo, originals) + _restore(repo, originals, remove_state=state_created) timings["total_ms"] = round((time.perf_counter() - started) * 1000, 3) return { "schema_version": "1.0", @@ -1263,7 +1281,7 @@ def run_pipeline(bundle: pathlib.Path, bundle_sha: str, repo: pathlib.Path) -> d } except (OSError, UnicodeError, json.JSONDecodeError) as exc: if edited: - _restore(repo, originals) + _restore(repo, originals, remove_state=state_created) timings["total_ms"] = round((time.perf_counter() - started) * 1000, 3) return { "schema_version": "1.0", diff --git a/keel-setup/scripts/inventory.py b/keel-setup/scripts/inventory.py index ea243bd..49f9879 100644 --- a/keel-setup/scripts/inventory.py +++ b/keel-setup/scripts/inventory.py @@ -175,12 +175,18 @@ def iter_fast_source_files(root: pathlib.Path): yield from iter_source_files(root, fast=True) -def _source_text(path: pathlib.Path) -> str: +def _source_text(path: pathlib.Path, read_budget: list[int] | None = None) -> str: fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) with os.fdopen(fd, "rb") as stream: if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): raise ValueError("source must be a regular file") raw = stream.read(MAX_FILE_BYTES + 1) + if read_budget is not None: + # Charge bytes actually read, so files that grow after stat() cannot + # exceed the aggregate bound. + read_budget[0] -= len(raw) + if read_budget[0] < 0: + raise ValueError("repository exceeds aggregate read limit") if len(raw) > MAX_FILE_BYTES or raw.count(b"\n") > MAX_SOURCE_LINES: raise ValueError("source exceeds bounded size or line limit") return raw.decode("utf-8") @@ -506,10 +512,12 @@ def fast_inspect( def inspect(root: pathlib.Path) -> dict[str, Any]: paths: list[dict[str, Any]] = [] - output_bytes = 1024 + # Budget the printed (indented) form, with headroom for the envelope. + output_bytes = 4096 + read_budget = [MAX_SCAN_BYTES] for path, relative in iter_source_files(root): try: - lines = _source_text(path).splitlines() + lines = _source_text(path, read_budget).splitlines() except (OSError, UnicodeDecodeError): continue for line_number, line in enumerate(lines, 1): @@ -530,7 +538,7 @@ def inspect(root: pathlib.Path) -> dict[str, Any]: "uncertainties": ["source signal is not trusted runtime semantics"], } ) - output_bytes += len(json.dumps(paths[-1]).encode("utf-8")) + output_bytes += len(json.dumps(paths[-1], indent=2, sort_keys=True).encode("utf-8")) + 100 if output_bytes > MAX_OUTPUT_BYTES: raise ValueError("inventory exceeds its output limit") return { diff --git a/keel-setup/scripts/setup_state.py b/keel-setup/scripts/setup_state.py index 11dbfd4..df97fe0 100644 --- a/keel-setup/scripts/setup_state.py +++ b/keel-setup/scripts/setup_state.py @@ -35,7 +35,7 @@ SCHEMA_VERSION = "1.0" MAX_STRING_LENGTH = 512 -MAX_STATE_BYTES = 32_768 +MAX_STATE_BYTES = 1_000_000 MAX_STATE_DEPTH = 32 REQUIRED_PRE_GATE_CHECKS = ( "syntax_or_compile", @@ -644,7 +644,7 @@ def main(argv: list[str] | None = None) -> int: "--state", type=pathlib.Path, default=pathlib.Path(str(DEFAULT_STATE_PATH)), - help="path to the local, git-ignored continuity file", + help="path inside repo-root to the git-ignored continuity file; relative paths use repo-root", ) parser.add_argument("--repo-root", type=pathlib.Path, default=pathlib.Path.cwd()) parser.add_argument( diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index ee75547..9fe44d8 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -41,6 +41,8 @@ def _git(root: pathlib.Path, *args: str) -> str: class DeterministicFastFirstRunTest(unittest.TestCase): + @unittest.skipUnless((ROOT / "scripts/check_release_bundle.py").is_file(), + "the release checker is a publication-layer file of the public bundle") def test_fallback_release_checker_rejects_bytecode_and_cache_entries(self): checker = _load("fallback_bundle_check", ROOT / "scripts/check_release_bundle.py") for relative in ("shared/scripts/__pycache__/schema_validation.pyc", "shared/scripts/schema_validation.pyc", @@ -69,6 +71,7 @@ def setUpClass(cls) -> None: "keel-policy/scripts/consume_authoring_context.py", "keel-policy/scripts/validate_enforceability_report.py", "shared/scripts/schema_validation.py", + "shared/scripts/bounded_input.py", "shared/scripts/validate_feedback_report.py", ): target = cls.bundle / relative @@ -200,6 +203,56 @@ def test_dirty_checkout_stops_before_discovery_or_edits(self): self.assertEqual(_git(root, "status", "--porcelain=v1", "--untracked-files=all"), before) self.assertIn("total_ms", result["timings"]) + def test_dangling_external_state_link_is_untouched_by_preparation_and_rollback(self): + root = self._repo() + with tempfile.TemporaryDirectory() as directory: + external = pathlib.Path(directory) + state = external / "setup-state.json" + state.symlink_to(external / "does-not-exist") + (root / ".keel").symlink_to(external, target_is_directory=True) + _git(root, "add", ".keel") + _git(root, "-c", "user.name=Keel Test", "-c", "user.email=keel-test@example.invalid", "commit", "-qm", "state link") + result = self._run(root) + self.assertEqual(result["outcome"], "model_review_required", result) + self.assertTrue(state.is_symlink()) + fast._restore(root, {}, remove_state=True) + self.assertTrue(state.is_symlink()) + self.assertEqual((root / "app.py").read_text(), fixtures.GOLDEN_APP) + + def test_tracked_gitignore_symlink_refuses_without_touching_external_file(self): + root = self._repo() + with tempfile.TemporaryDirectory() as directory: + external = pathlib.Path(directory) / "external" + external.write_text("external content\n") + (root / ".gitignore").unlink() + (root / ".gitignore").symlink_to(external) + _git(root, "add", ".gitignore") + _git(root, "-c", "user.name=Keel Test", "-c", "user.email=keel-test@example.invalid", "commit", "-qm", "link") + before = external.stat() + result = self._run(root) + self.assertEqual(result["outcome"], "validation_failed", result) + self.assertEqual(external.read_text(), "external content\n") + self.assertEqual(external.stat().st_mtime_ns, before.st_mtime_ns) + self.assertEqual((root / "app.py").read_text(), fixtures.GOLDEN_APP) + # Rollback refuses to replace the link and never writes through it. + with self.assertRaises(fast.PipelineFailure): + fast._restore(root, {pathlib.PurePosixPath(".gitignore"): b"restored\n"}) + self.assertEqual(external.read_text(), "external content\n") + self.assertTrue((root / ".gitignore").is_symlink()) + + def test_extra_statements_in_replaced_span_force_refusal_without_edits(self): + variants = [ + fixtures.GOLDEN_APP.replace(" response = client.responses.create(", " authorize_user()\n response = client.responses.create("), + fixtures.GOLDEN_APP.replace(" summary = response.output_text.strip()", " audit_response(response)\n summary = response.output_text.strip()"), + fixtures.GOLDEN_APP.replace(" client = OpenAI()", " cleanup()\n client = OpenAI()"), + fixtures.GOLDEN_APP.replace(" if client is None:", " if client is None or needs_refresh():"), + ] + for source in variants: + root = self._repo(source) + result = self._run(root) + self.assertEqual(result["outcome"], "model_review_required", result) + self.assertEqual((root / "app.py").read_text(), source) + self.assertEqual(_git(root, "status", "--porcelain=v1"), "") def test_pre_gate_validation_does_not_execute_target_initialization(self): for entrypoint in ("tests/__init__.py", "app.py", "sitecustomize.py"): with self.subTest(entrypoint=entrypoint): @@ -404,10 +457,23 @@ def test_coupled_protocol_double_is_adapted_and_runtime_test_is_deferred(self): self.assertIn("FakeClient", test_source) self.assertIn("https://api.keelapi.com/v1/execute", test_source) self.assertEqual( - result["validation"]["focused_compatibility_test"], + result["validation"]["prepared_compatibility_test"], "tests.test_app.SummarizerTests.test_sends_text_to_the_selected_model", ) + def test_automatic_preparation_never_runs_customer_initializers_or_callable(self): + source = fixtures.GOLDEN_APP.replace("import os", "import os\nfrom pathlib import Path\nPath('module-sentinel').touch()") + source = source.replace(" source = text.strip()", " Path('call-sentinel').touch()\n source = text.strip()") + root = self._repo(source) + (root / "tests/__init__.py").write_text("from pathlib import Path\nPath('package-sentinel').touch()\n") + _git(root, "add", ".") + _git(root, "-c", "user.name=Keel Test", "-c", "user.email=keel-test@example.invalid", "commit", "-qm", "sentinels") + result = self._run(root) + self.assertEqual(result["outcome"], "ready_for_human", result) + self.assertIsNone(result["validation"]["focused_compatibility_test"]) + for name in ("module-sentinel", "package-sentinel", "call-sentinel"): + self.assertFalse((root / name).exists(), name) + def test_regression_generated_adapter_accepts_normalized_execute_text(self): root = self._repo() result = self._run(root) @@ -654,6 +720,16 @@ def test_opaque_source_and_literal_defaults_never_leave_the_checkout(self): self.assertNotIn(sentinel, json.dumps(result)) self.assertIn(sentinel, (root / "app.py").read_text()) + def test_source_credentials_never_appear_in_structured_output(self): + samples = ["Authorization: Bearer synthetic-bearer-value", "github_pat_synthetic_example_123456789", + "-----BEGIN PRIVATE KEY-----synthetic-----END PRIVATE KEY-----", + "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJleGFtcGxlIn0.synthetic_signature"] + for value in samples: + root = self._repo(fixtures.GOLDEN_APP.replace(" response =", f" # {value}\n response =")) + result = self._run(root) + self.assertEqual(result["outcome"], "ready_for_human", result) + self.assertNotIn(value, json.dumps(result)) + def test_custom_base_url_is_safe_fallback(self): root = self._repo(fixtures.CUSTOM_BASE_URL_APP) result = self._run(root) diff --git a/keel-setup/tests/test_inventory.py b/keel-setup/tests/test_inventory.py index 8c15cec..139dc2c 100644 --- a/keel-setup/tests/test_inventory.py +++ b/keel-setup/tests/test_inventory.py @@ -1,6 +1,8 @@ from __future__ import annotations +import contextlib import importlib.util +import io import json import os import pathlib @@ -48,6 +50,62 @@ def report(): class InventoryTest(unittest.TestCase): + def test_skipped_tree_is_pruned_before_enumeration(self): + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + (root / "node_modules").mkdir() + (root / "server.py").write_text("OpenAI()") + original = inventory.os.scandir + def checked(path): + self.assertNotIn("node_modules", pathlib.Path(path).parts) + return original(path) + with mock.patch.object(inventory.os, "scandir", side_effect=checked): + self.assertEqual([item["path"] for item in inventory.inspect(root)["paths"]], ["server.py"]) + + def test_oversized_files_are_skipped_before_read_and_reads_are_charged(self): + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + for index in range(10): + (root / f"file{index}.py").write_bytes(b"x" * 20) + with mock.patch.object(inventory, "MAX_FILE_BYTES", 5), \ + mock.patch.object(inventory, "_source_text", wraps=inventory._source_text) as read: + self.assertEqual(inventory.inspect(root)["paths"], []) + read.assert_not_called() + # Bytes actually read are charged, so growth after stat() cannot exceed the bound. + budget = [30] + inventory._source_text(root / "file0.py", budget) + self.assertEqual(budget, [10]) + with self.assertRaises(ValueError): + inventory._source_text(root / "file1.py", budget) + + def test_maximum_emitted_inventory_still_passes_coverage_validation(self): + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + (root / "server.py").write_text("OpenAI()\n" * inventory.MAX_SCAN_MATCHES) + result = inventory.inspect(root) + self.assertEqual(len(result["paths"]), inventory.MAX_SCAN_MATCHES) + self.assertEqual(inventory.validate_coverage(result), []) + self.assertLessEqual(len(json.dumps(result, indent=2, sort_keys=True).encode()), inventory.MAX_OUTPUT_BYTES) + (root / "server.py").write_text("OpenAI()\n" * (inventory.MAX_SCAN_MATCHES + 1)) + with self.assertRaises(ValueError): + inventory.inspect(root) + + def test_aggregate_limits_refuse_instead_of_emitting_a_partial_inventory(self): + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + (root / "server.py").write_text("OpenAI()\n" * 20) + (root / "nested").mkdir() + for constant, limit in (("MAX_SCAN_MATCHES", 2), ("MAX_SCAN_ENTRIES", 0), ("MAX_SCAN_FILES", 0), + ("MAX_SCAN_BYTES", 5), ("MAX_SCAN_SECONDS", -1), ("MAX_OUTPUT_BYTES", 4100), + ("MAX_SCAN_DEPTH", 0), ("MAX_SCAN_DIRECTORIES", 0)): + with self.subTest(constant=constant), mock.patch.object(inventory, constant, limit): + with self.assertRaises(ValueError): + inventory.inspect(root) + with contextlib.redirect_stdout(io.StringIO()) as stdout, \ + contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(inventory.main(["--root", str(root)]), 1) + self.assertEqual(stdout.getvalue(), "") + def test_aggregate_limits_count_skipped_files_bytes_and_matches(self): with tempfile.TemporaryDirectory() as directory: root = pathlib.Path(directory) @@ -398,6 +456,7 @@ def test_fast_first_run_preserves_client_hook_callable_contract(self): self.assertIn("`summarize(text, *, model=None)`", fast) self.assertIn("must not silently become", fast) self.assertIn("compatibility of the recorded callable parameters and defaults", fast) + self.assertIn("prepare and compile that one focused test without importing", fast) self.assertIn("There is no pre-gate target execution exception", fast) self.assertIn("Defer runtime compatibility checks until isolated post-gate validation", fast) self.assertIn("stop for explicit human direction", fast) @@ -421,6 +480,8 @@ def test_deterministic_golden_path_precedes_model_driven_fallback(self): self.assertIn("rediscover the seam", fast[deterministic:fallback]) self.assertIn("handle setup state separately", fast[deterministic:fallback]) self.assertIn("repeat\nvalidation or tests", fast[deterministic:fallback]) + self.assertIn("diff digest and per-file statistics", fast[deterministic:fallback]) + self.assertIn("human review the exact local diff in their editor", fast[deterministic:fallback]) self.assertIn("contains only counts and digests", fast[deterministic:fallback]) self.assertIn("targeted local `git diff`", fast[deterministic:fallback]) for outcome in ( @@ -718,7 +779,14 @@ def test_all_published_helper_commands_use_the_authenticated_root(self): for line in text.splitlines(): if line.strip().startswith("python3 "): self.assertRegex(line.strip(), r'^python3 -I "\$BUNDLE/[^" ]+\.py"(?: |$)') - for document in SKILL.parents[1].rglob("*.md"): + # Scan the published product roots, plus the public README in the release + # bundle (marked by SOURCE.json); private source specs are never published. + bundle_root = SKILL.parents[1] + documents = [document for top in ("keel-setup", "keel-policy", "shared") + for document in (bundle_root / top).rglob("*.md")] + if (bundle_root / "SOURCE.json").is_file(): + documents.append(bundle_root / "README.md") + for document in documents: for line in document.read_text().splitlines(): if line.strip().startswith("python3 ") and ".py" in line: self.assertTrue(line.strip().startswith("python3 -I "), diff --git a/keel-setup/tests/test_setup_state.py b/keel-setup/tests/test_setup_state.py index 9c3ea13..4cda68a 100644 --- a/keel-setup/tests/test_setup_state.py +++ b/keel-setup/tests/test_setup_state.py @@ -296,6 +296,22 @@ def test_missing_file_reports_lost_continuity_and_starts_at_one(self): self.assertIn("prior_run_success", report["does_not_establish"]) self.assertEqual(report["evidence_level"], "unresolved") + def test_schema_valid_large_state_round_trips_through_writer_and_reader(self): + with tempfile.TemporaryDirectory() as directory: + root = self._repo(directory) + path = root / ".keel/setup-state.json" + state = setup_state.initial_state() + state["discovered_mcp_source_identifiers"] = [f"source-{index:03d}-" + "x" * 190 for index in range(400)] + self.assertEqual(setup_state.validate_state(state), []) + setup_state.write_state_atomically(path, state, root) + self.assertGreater(path.stat().st_size, 65_536) + self.assertEqual(setup_state.begin(path, root)["continuity"], "resumed") + before = path.read_bytes() + with mock.patch.object(setup_state, "MAX_STATE_BYTES", 100): + with self.assertRaises(ValueError): + setup_state.write_state_atomically(path, state, root) + self.assertEqual(path.read_bytes(), before) + def test_invalid_json_reports_lost_continuity_without_inferring_success(self): with tempfile.TemporaryDirectory() as directory: root = self._repo(directory) @@ -594,6 +610,33 @@ def test_untracked_ignore_status_is_reported(self): class CommandLineTest(unittest.TestCase): + def test_relative_state_is_anchored_to_repo_from_another_cwd(self): + with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) + (root / ".gitignore").write_text(".keel/\n") + subprocess.run(["git", "init", "-q", str(root)], check=True) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(setup_state.main(["--repo-root", str(root)]), 0) + self.assertTrue((root / ".keel/setup-state.json").is_file()) + + def test_outside_and_symlink_paths_refuse_before_read_or_write(self): + with tempfile.TemporaryDirectory() as directory: + base = pathlib.Path(directory) + root = base / "repo" + root.mkdir() + outside = base / "external" + outside.write_text("unchanged") + (root / "link").symlink_to(base, target_is_directory=True) + for path in (outside, pathlib.Path("../external"), pathlib.Path("link/external")): + with self.subTest(path=path): + report = setup_state.begin(path, root) + self.assertEqual(report["continuity"], "lost") + self.assertFalse(report["state_persisted"]) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(setup_state.main(["--state", str(path), "--repo-root", str(root)]), 1) + self.assertEqual(outside.read_text(), "unchanged") + self.assertEqual(sorted(item.name for item in base.iterdir()), ["external", "repo"]) + def test_main_persists_each_successful_invocation(self): with tempfile.TemporaryDirectory() as directory: root = pathlib.Path(directory) @@ -657,7 +700,7 @@ def test_validate_only_rejects_a_refused_file(self): path = pathlib.Path(directory) / "setup-state.json" path.write_text(json.dumps(_valid(active_mapping_hash="abc"))) with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - code = setup_state.main(["--validate-only", "--state", str(path)]) + code = setup_state.main(["--validate-only", "--state", str(path), "--repo-root", directory]) self.assertEqual(code, 1) def test_validate_only_accepts_the_shipped_shape(self): diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 68b9a35..f2045e1 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "9121c2e3aef2356472d8c1eb3bd5bd4cb3bf501e064d629bc124f16758a89ba7" +PRODUCT_SOURCE_SHA256 = "7481bc4de5400d2dd00af9cbe6c449d090dac7806a90fdb7d144e65195bdf293" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", @@ -70,7 +70,9 @@ "shared/CONSTITUTION.md", "shared/feedback-report.schema.json", "shared/feedback-report.template.md", + "shared/scripts/bounded_input.py", "shared/scripts/schema_validation.py", + "shared/scripts/test_bounded_input.py", "shared/scripts/test_schema_validation.py", "shared/scripts/test_validate_feedback_report.py", "shared/scripts/validate_feedback_report.py", diff --git a/shared/scripts/bounded_input.py b/shared/scripts/bounded_input.py new file mode 100644 index 0000000..63334b3 --- /dev/null +++ b/shared/scripts/bounded_input.py @@ -0,0 +1,23 @@ +"""Bound local input reads on the opened descriptor, including replacement races.""" +from __future__ import annotations + +import os +import pathlib +import stat + + +def read_bytes(path: pathlib.Path, maximum: int) -> bytes: + # Nonblocking open lets us reject FIFOs before waiting for a writer. + descriptor = os.open(path, os.O_RDONLY | os.O_NONBLOCK) + try: + if not stat.S_ISREG(os.fstat(descriptor).st_mode): + raise ValueError("input must be a regular file") + with os.fdopen(descriptor, "rb") as handle: + descriptor = -1 + raw = handle.read(maximum + 1) + if len(raw) > maximum: + raise ValueError(f"input exceeds {maximum} bytes") + return raw + finally: + if descriptor != -1: + os.close(descriptor) diff --git a/shared/scripts/schema_validation.py b/shared/scripts/schema_validation.py index b67a4be..6e0ca2a 100644 --- a/shared/scripts/schema_validation.py +++ b/shared/scripts/schema_validation.py @@ -66,34 +66,17 @@ def _resolve_ref(reference: str, root_schema: dict[str, Any]) -> dict[str, Any] return current if isinstance(current, dict) else None -def validate( - instance: Any, - schema: dict[str, Any], - path: str = "$", - *, - root_schema: dict[str, Any] | None = None, -) -> list[str]: - # JSON numbers must be finite, including values in open objects and - # overflowed exponents. Check direct library callers as well as JSON. - pending = [(path, instance)] - while pending: - location, value = pending.pop() - if isinstance(value, float) and not math.isfinite(value): - return [f"{location}: number must be finite"] - if isinstance(value, dict): - pending.extend((f"{location}.{key}", child) for key, child in value.items()) - elif isinstance(value, list): - pending.extend((f"{location}[{index}]", child) for index, child in enumerate(value)) - return _validate(instance, schema, path, root_schema=root_schema) - - def _validate( instance: Any, schema: dict[str, Any], path: str = "$", *, root_schema: dict[str, Any] | None = None, + budget: list[int], ) -> list[str]: + budget[0] -= 1 + if budget[0] < 0: + raise ValueError("schema validation work limit exceeded") root_schema = schema if root_schema is None else root_schema unknown_keywords = set(schema) - SUPPORTED if unknown_keywords: @@ -104,13 +87,13 @@ def _validate( if referenced is None: failures.append(f"{path}: unsupported or missing schema reference {schema['$ref']!r}") else: - failures.extend(_validate(instance, referenced, path, root_schema=root_schema)) + failures.extend(_validate(instance, referenced, path, root_schema=root_schema, budget=budget)) if "anyOf" in schema: - branches = [_validate(instance, branch, path, root_schema=root_schema) for branch in schema["anyOf"]] + branches = [_validate(instance, branch, path, root_schema=root_schema, budget=budget) for branch in schema["anyOf"]] if not any(not branch for branch in branches): failures.append(f"{path}: value matches no anyOf branch") if "oneOf" in schema: - branches = [_validate(instance, branch, path, root_schema=root_schema) for branch in schema["oneOf"]] + branches = [_validate(instance, branch, path, root_schema=root_schema, budget=budget) for branch in schema["oneOf"]] if sum(not branch for branch in branches) != 1: failures.append(f"{path}: value must match exactly one oneOf branch") if "const" in schema and instance != schema["const"]: @@ -123,7 +106,7 @@ def _validate( expected_types = [expected_types] if not any(_type_matches(instance, item) for item in expected_types): failures.append(f"{path}: expected type {' or '.join(expected_types)}") - return failures + return failures[:50] if isinstance(instance, dict): required = set(schema.get("required", [])) for key in sorted(required - set(instance)): @@ -134,7 +117,7 @@ def _validate( failures.append(f"{path}: unknown property {key!r}") for key, value in instance.items(): if key in properties: - failures.extend(_validate(value, properties[key], f"{path}.{key}", root_schema=root_schema)) + failures.extend(_validate(value, properties[key], f"{path}.{key}", root_schema=root_schema, budget=budget)) if isinstance(instance, list): if len(instance) < schema.get("minItems", 0): failures.append(f"{path}: has fewer than {schema['minItems']} items") @@ -147,7 +130,7 @@ def _validate( item_schema = schema.get("items") if item_schema: for index, value in enumerate(instance): - failures.extend(_validate(value, item_schema, f"{path}[{index}]", root_schema=root_schema)) + failures.extend(_validate(value, item_schema, f"{path}[{index}]", root_schema=root_schema, budget=budget)) if isinstance(instance, str): if len(instance) < schema.get("minLength", 0): failures.append(f"{path}: is shorter than {schema['minLength']} characters") @@ -164,4 +147,54 @@ def _validate( failures.append(f"{path}: is above maximum {schema['maximum']}") if "exclusiveMinimum" in schema and instance <= schema["exclusiveMinimum"]: failures.append(f"{path}: is not above exclusive minimum {schema['exclusiveMinimum']}") - return failures + return failures[:50] + + +def complexity_failures(instance: Any, *, max_nodes: int = 50_000, + max_items: int = 2_000, max_text: int = 2_000_000) -> list[str]: + """Reject excessive structure before recursive schema/semantic traversal.""" + pending = [(instance, 0)] + nodes = text_size = 0 + while pending: + value, depth = pending.pop() + nodes += 1 + if nodes > max_nodes or depth > 24: + return ["input exceeds node or nesting limit"] + if isinstance(value, (dict, list)): + if len(value) > max_items: + return ["input exceeds container item limit"] + if isinstance(value, dict): + text_size += sum(len(str(key)) for key in value) + children = value.values() + else: + children = value + pending.extend((child, depth + 1) for child in children) + elif isinstance(value, str): + text_size += len(value) + if len(value) > 65_536: + return ["input exceeds string limit"] + if text_size > max_text: + return ["input exceeds total text limit"] + return [] + + +def validate(instance: Any, schema: dict[str, Any], path: str = "$", *, + root_schema: dict[str, Any] | None = None) -> list[str]: + failures = complexity_failures(instance) + if failures: + return failures + # JSON numbers must be finite, including values in open objects and + # overflowed exponents. Check direct library callers as well as JSON. + pending = [(path, instance)] + while pending: + location, value = pending.pop() + if isinstance(value, float) and not math.isfinite(value): + return [f"{location}: number must be finite"] + if isinstance(value, dict): + pending.extend((f"{location}.{key}", child) for key, child in value.items()) + elif isinstance(value, list): + pending.extend((f"{location}[{index}]", child) for index, child in enumerate(value)) + try: + return _validate(instance, schema, path, root_schema=root_schema, budget=[50_000])[:50] + except (RecursionError, ValueError): + return ["schema validation resource limit exceeded"] diff --git a/shared/scripts/test_bounded_input.py b/shared/scripts/test_bounded_input.py new file mode 100644 index 0000000..ffcb0ef --- /dev/null +++ b/shared/scripts/test_bounded_input.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +import os +import pathlib +import tempfile +import unittest +from unittest import mock + +from bounded_input import read_bytes + + +class BoundedInputTest(unittest.TestCase): + def test_regular_file_and_oversize(self): + with tempfile.TemporaryDirectory() as directory: + path = pathlib.Path(directory) / "input" + path.write_bytes(b"good") + self.assertEqual(read_bytes(path, 4), b"good") + with self.assertRaisesRegex(ValueError, "exceeds"): + read_bytes(path, 3) + + def test_fifo_is_refused_without_waiting_for_writer(self): + with tempfile.TemporaryDirectory() as directory: + path = pathlib.Path(directory) / "fifo" + os.mkfifo(path) + with self.assertRaisesRegex(ValueError, "regular file"): + read_bytes(path, 10) + + def test_read_is_bounded_on_opened_file_after_path_replacement(self): + with tempfile.TemporaryDirectory() as directory: + path = pathlib.Path(directory) / "input" + path.write_bytes(b"0123456789") + opened = os.open + def replace_after_open(*args): + descriptor = opened(*args) + path.unlink() + os.mkfifo(path) + return descriptor + with mock.patch("bounded_input.os.open", side_effect=replace_after_open): + with self.assertRaisesRegex(ValueError, "exceeds"): + read_bytes(path, 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/shared/scripts/test_schema_validation.py b/shared/scripts/test_schema_validation.py index 387b06d..304e1e0 100644 --- a/shared/scripts/test_schema_validation.py +++ b/shared/scripts/test_schema_validation.py @@ -8,6 +8,11 @@ class SchemaSubsetValidatorTest(unittest.TestCase): + def test_recursive_schema_and_failure_output_are_bounded(self): + schema = {"$ref": "#/$defs/cycle", "$defs": {"cycle": {"$ref": "#/$defs/cycle"}}} + self.assertTrue(schema_validation.validate({}, schema)) + errors = schema_validation.validate(["wrong"] * 1000, {"type": "array", "items": {"type": "integer"}}) + self.assertEqual(len(errors), 50) def test_approval_selectors_are_closed_and_bound_to_their_type(self): root = pathlib.Path(__file__).resolve().parents[2] policy_schema = json.loads((root / "keel-policy/reference/policy-document.schema.json").read_text()) diff --git a/shared/scripts/test_validate_feedback_report.py b/shared/scripts/test_validate_feedback_report.py index c9be444..18eaf26 100644 --- a/shared/scripts/test_validate_feedback_report.py +++ b/shared/scripts/test_validate_feedback_report.py @@ -4,6 +4,7 @@ import contextlib import io import json +import os import pathlib import tempfile import unittest @@ -35,6 +36,17 @@ def report(): class FeedbackValidatorTest(unittest.TestCase): + def test_deep_structure_refuses_before_semantic_walk(self): + value = {} + for _ in range(100): + value = {"child": value} + self.assertTrue(validator.validate(value, set(), None)) + + def test_fifo_input_is_refused_without_blocking(self): + with tempfile.TemporaryDirectory() as directory: + path = pathlib.Path(directory) / "fifo" + os.mkfifo(path) + self.assertEqual(validator.main([str(path)]), 1) def test_array_strings_receive_all_detectors_and_portable_path_checks(self): for sample in ("Bearer example-sensitive", "token=opaque-value", "API_TOKEN=opaque-value", "```source```", "/outside/file.py", "C:/project/file.py", "C:relative.py", diff --git a/shared/scripts/validate_feedback_report.py b/shared/scripts/validate_feedback_report.py index 70f6eca..8e43c6b 100644 --- a/shared/scripts/validate_feedback_report.py +++ b/shared/scripts/validate_feedback_report.py @@ -11,7 +11,8 @@ sys.dont_write_bytecode = True sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from schema_validation import validate as validate_schema +from schema_validation import complexity_failures, validate as validate_schema +from bounded_input import read_bytes MAX_BYTES = 16_384 TOP_FIELDS = { @@ -48,6 +49,9 @@ def _walk(value: Any, path: str = ""): def validate(report: Any, approved_context: set[str], channel: str | None) -> list[str]: + limits = complexity_failures(report) + if limits: + return limits schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8")) failures = validate_schema(report, schema) if not isinstance(report, dict): @@ -109,16 +113,16 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--preview", action="store_true", help="print the exact validated payload for human review") args = parser.parse_args(argv) try: - raw = args.report.read_bytes() - except OSError: - print("feedback report could not be read", file=sys.stderr) + raw = read_bytes(args.report, MAX_BYTES) + except (OSError, ValueError): + print("feedback report must be a regular file within the byte limit", file=sys.stderr) return 1 if len(raw) > MAX_BYTES: print(f"feedback report exceeds {MAX_BYTES} bytes", file=sys.stderr) return 1 try: report = json.loads(raw) - except (UnicodeDecodeError, json.JSONDecodeError): + except (UnicodeDecodeError, json.JSONDecodeError, RecursionError): print("feedback report is not valid UTF-8 JSON", file=sys.stderr) return 1 failures = validate(report, set(args.approve_context), args.channel)