diff --git a/SHA256SUMS b/SHA256SUMS index 57c87f1..427ac28 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,48 +2,50 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -b273423034914ee3c6599e3c780551f70bc8fef51f72a636f839810e82c3bacf SOURCE.json -75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 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 -4be41a65667952df8105e627026a921b66fc4fef19761242efabe69df0bd47cf keel-policy/reference/policy-document.schema.json +9d86eeb4fecf6db831856c0b77b9e83caeb161ec82d046eaf4fc2f8e73d96f27 keel-policy/reference/policy-document.schema.json 7d662cffa24744af7a26f62d813127b4bc0a44ff62f725c883054165ddec3272 keel-policy/scripts/consume_authoring_context.py -188570c6787d720b8811a36382843b09f31bb37da78448c2a905fef2345511c9 keel-policy/scripts/validate_enforceability_report.py -b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb 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 -322b430367e859dae341e9c225be34c6c5272c481074e7b1ae2242db527e1cbe keel-policy/tests/test_validate_enforceability_report.py -80624280a7ec0bd0273fcd37ffc9dec14003bb84b6e470a8b1e7f59f530a825f 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 -4f54094b796b1e58591706a44b54b73626b374a5ce7892f5c8ed0509c8fb2372 keel-setup/scripts/authoring_context.py -88d28844fff3cb1984649fafad9cc59950ea6e604adb0a12e98b7039b60b6150 keel-setup/scripts/fast_first_run.py -856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py +580edac4805c13a2b88b7dde613bf3a388347c9d00c6f9488c1ceb9e593368d3 keel-setup/scripts/authoring_context.py +e7736b2abbb475472befa4a53cd1b7b5dd2c55318645472c74be6e56b43e57c4 keel-setup/scripts/fast_first_run.py +b81c2c37fe70176a006ef5e5b0904d06609d7a4ca8f3cababae652d9f2254a09 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 +04f0dd71d74930ccb065202769f01f2afff559f395acc93937813f60a2793558 keel-setup/scripts/setup_state.py +1bc3d136fe06414a090976712c96fef0f46d7922ed3cd5cf502fa174de1aa86d keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py -89eaed21a48503c3514b2ff336a5112da28ae21203e56d13444f0b79f6f8fcf1 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 +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 -87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py -e759ec5d797ca0101f81cd23e66b63229d0e55da463625b488a12a9a64758716 keel-setup/tests/test_verify_execute.py +c8006372327167f6317d7ae41d79da3c2dd45a7510f1cdc544616facd27d9d83 keel-setup/tests/test_setup_state.py +ea797a44c033a6ce519b82595c858cdb0879868854b949226792f3bffe2d4ba3 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -155a5dbbfe0423bb54ac1fb7d4bb1b1b3f6a91d920221d6d15b205b5689dc93e 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 -82ffbacd09255c9311813cec37bd75d745df16ec21f457542ec5cd3b30739014 shared/scripts/schema_validation.py -7fef855399e1c4b7372d235c1d0fa3567583c4d428e8ee9f5cf122f596dd11e7 shared/scripts/test_schema_validation.py -c7ad8aa74f5325b8bad0a44c979e4089cf3f57da787c209ed5d9cb71c7aaac1d shared/scripts/test_validate_feedback_report.py -ca5cb3890f97d49affc5be7a15ba2c1a1859ca9afd459eeb6358fa27cbb05372 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 470d7e2..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": "513568419e76edf18ee1fa494d7c080ecb8ce96f9dfb9832aed6a1334edfe719", + "product_source_sha256": "7481bc4de5400d2dd00af9cbe6c449d090dac7806a90fdb7d144e65195bdf293", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-policy/SKILL.md b/keel-policy/SKILL.md index d503a05..6dc08b7 100644 --- a/keel-policy/SKILL.md +++ b/keel-policy/SKILL.md @@ -87,18 +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 -enforceability report with `scripts/validate_enforceability_report.py`. A blocked report is a successful +`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. 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 44a68d5..ac331ec 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": [ @@ -137,16 +139,8 @@ "title": "Email" }, "external_workflow": { - "anyOf": [ - { - "type": "object" - }, - { - "type": "null" - } - ], - "default": null, - "title": "External Workflow" + "type": "null", + "default": null }, "group_id": { "anyOf": [ @@ -276,7 +270,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/keel-policy/scripts/validate_enforceability_report.py b/keel-policy/scripts/validate_enforceability_report.py index 92b57f3..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,49 @@ 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": (), + "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") + 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. + return ACTION_DEPENDENCIES.get(action) def _walk(value: Any): @@ -47,6 +81,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], @@ -54,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 @@ -62,20 +116,31 @@ 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") 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 + 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") @@ -98,13 +163,40 @@ 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): 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") + 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)) + 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 @@ -116,7 +208,9 @@ def validate( failures.append( f"policy.rules[{rule_index}] automatic action uses field {field!r} without independently trusted enforceability[{entry_index}]" ) - return failures + 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[:100] def main(argv: list[str] | None = None) -> int: @@ -124,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) @@ -137,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 2e24cd8..31ed90c 100644 --- a/keel-policy/tests/test_authoring_context_consumption.py +++ b/keel-policy/tests/test_authoring_context_consumption.py @@ -253,12 +253,14 @@ 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': [], + '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 da7e437..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,11 +22,13 @@ 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."], "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 +51,92 @@ 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") + # 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")): + 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"]} + 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": []}]}): + 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/keel-setup/SKILL.md b/keel-setup/SKILL.md index fd015aa..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`, 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 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/authoring_context.py b/keel-setup/scripts/authoring_context.py index 7c71832..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 @@ -642,6 +644,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/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index c437aa8..15e6318 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 @@ -40,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__", @@ -93,7 +98,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, @@ -332,19 +341,40 @@ 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.", - ) + 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] = [] @@ -352,7 +382,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(".") @@ -370,6 +400,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()) @@ -382,7 +421,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): @@ -459,7 +501,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(".") @@ -477,7 +519,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): @@ -507,7 +552,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 @@ -528,6 +576,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") @@ -536,7 +587,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"]) @@ -569,6 +620,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") @@ -653,7 +710,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", @@ -742,7 +802,14 @@ 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": + 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", @@ -895,7 +962,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 @@ -909,14 +976,68 @@ 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", } -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: + os.fchmod(handle.fileno(), mode) + 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: @@ -924,34 +1045,61 @@ 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") 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: - 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) - state = repo / ".keel" / "setup-state.json" - state.unlink(missing_ok=True) + _write(path, content.decode("utf-8"), repo) + 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: - 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]: + 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, @@ -996,10 +1144,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) @@ -1008,39 +1156,22 @@ 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) 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.", } @@ -1049,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() @@ -1068,21 +1200,26 @@ 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] = app_path.read_bytes() + 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] = 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) + _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) + _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) @@ -1102,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, @@ -1130,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", @@ -1143,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 9637c7b..49f9879 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,70 @@ 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.""" - - 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 + yield from iter_source_files(root, fast=True) + + +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") def _is_test_path(relative: pathlib.PurePath) -> bool: @@ -218,7 +253,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 +316,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 +372,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 +436,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 +512,20 @@ def fast_inspect( def inspect(root: pathlib.Path) -> dict[str, Any]: paths: list[dict[str, Any]] = [] + # 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 = path.read_text(encoding="utf-8").splitlines() + lines = _source_text(path, read_budget).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 +538,9 @@ def inspect(root: pathlib.Path) -> dict[str, Any]: "uncertainties": ["source signal is not trusted runtime semantics"], } ) + 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 { "schema_version": "1.0", "report_basis": "source_inventory", @@ -574,7 +621,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/scripts/setup_state.py b/keel-setup/scripts/setup_state.py index d183b5d..df97fe0 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 = 1_000_000 +MAX_STATE_DEPTH = 32 REQUIRED_PRE_GATE_CHECKS = ( "syntax_or_compile", "fail_closed_integration_review", @@ -204,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.""" @@ -216,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): @@ -238,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, @@ -265,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, @@ -354,36 +387,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 +485,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 +520,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 +570,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: @@ -534,14 +626,13 @@ 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: 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 [] @@ -553,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( @@ -603,8 +694,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/scripts/verify_execute.py b/keel-setup/scripts/verify_execute.py index 3e166a0..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 @@ -601,6 +604,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..fa2d4ba 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,20 @@ 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"), \ + 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_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index c216d4f..9fe44d8 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -41,6 +41,23 @@ 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", + "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() @@ -54,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 @@ -185,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): @@ -345,7 +413,39 @@ 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_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, "-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) + 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_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() @@ -357,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) @@ -466,6 +579,39 @@ 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, "-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) + 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: @@ -495,24 +641,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 +666,29 @@ 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_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) allowed = set(result["validation"]["changed_paths"]) @@ -546,9 +706,29 @@ 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_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) diff --git a/keel-setup/tests/test_inventory.py b/keel-setup/tests/test_inventory.py index 71ee90e..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 @@ -11,6 +13,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 +50,79 @@ 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) + 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) @@ -380,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) @@ -403,8 +480,10 @@ 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("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 ( "ambiguous", "unsupported_shape", @@ -700,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 fcb64b7..4cda68a 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()), []) @@ -206,11 +226,60 @@ 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: + 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): @@ -227,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) @@ -274,7 +359,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"]) @@ -295,7 +380,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(), ) @@ -512,6 +597,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) @@ -522,12 +610,42 @@ 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) (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): @@ -545,6 +663,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()): @@ -557,6 +678,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( @@ -576,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): @@ -584,7 +708,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): @@ -598,6 +722,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/keel-setup/tests/test_verify_execute.py b/keel-setup/tests/test_verify_execute.py index dffb9ee..0f84f31 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() @@ -105,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"}} @@ -126,6 +134,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 74e7957..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 = "513568419e76edf18ee1fa494d7c080ecb8ce96f9dfb9832aed6a1334edfe719" +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", @@ -88,12 +90,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 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 c537580..6e0ca2a 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 @@ -41,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 @@ -63,13 +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( +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: @@ -80,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"]: @@ -99,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)): @@ -110,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") @@ -123,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") @@ -140,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 26188b1..304e1e0 100644 --- a/shared/scripts/test_schema_validation.py +++ b/shared/scripts/test_schema_validation.py @@ -8,6 +8,48 @@ 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()) + 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", + "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) + 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.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): schema = { "type": "object", diff --git a/shared/scripts/test_validate_feedback_report.py b/shared/scripts/test_validate_feedback_report.py index 2448ed6..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,28 @@ 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", + 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..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 = { @@ -42,10 +43,15 @@ 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]: + 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): @@ -84,7 +90,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") @@ -104,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)