diff --git a/CHANGELOG.md b/CHANGELOG.md index a40e121..d560a09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ ## Unreleased +- **Native YAML form diagnostics (PATCH):** Distinguish invalid or unsupported source forms from verified template absence, check documented required YAML header keys and the supported field subset before recognizing explicit feature/change-request names, and report missing contributor-visible blank-route evidence without using an empty GraphQL template list as a fallback. For the narrow legacy about-for-description defect, verify the authenticated viewer's explicit blank-Issue permission, unrestricted issue-creation policy, source pin, absence of conflicting template/config evidence, and preserve the malformed source form's intent and mandatory fields. Unknown routes remain blocked; no external authority or version bump. + - **Existing-composition check (PATCH, 2026-12-02):** Make the existing native-alternative comparison explicit: determine whether the target function can already be composed without source changes, route conflicting evidence to Index re-review, and isolate only missing links. Motivated by [oi maintainer feedback](https://github.com/egoist/oi/issues/8#issuecomment-7319315786) and [Filament](https://github.com/invertibleMatrix/filament/issues/8#issuecomment-7332496078). No new stage, prototype or mandatory test run. - **Unknown Roadmap target exclusion (PATCH, 2026-12-02):** Require accepted Index re-review before any Roadmap from `?`; exclude unknown target functions from selection and production case/publication preflight, without blocking resolved functions or rewriting historical records. Applies to explicit A/P experimental proposals as well. diff --git a/PROTOCOL.md b/PROTOCOL.md index 52878ac..c8d6bd4 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -49,6 +49,8 @@ Read [docs/FORK_METADATA.md](docs/FORK_METADATA.md) for the initial JSON contrac - **Native Markdown Feature Request section precedence:** When the original first-party template uses mandatory top-level Markdown `##` fields that conflict with the seven OpenSiro original-facing `##` sections, **do not bypass either schema**. Preserve exactly the provider's real `##` fields and fill each meaningfully. Put all seven OpenSiro original-facing evidence sections as ordered `###` subheadings **under the native `## Additional Context`**, without dropping the historical six-function evidence, target, scope or rights. Use `validate_public_issue_payload.py --kind original --native-markdown-template-file /path/to/verified/feature_request.md` for the exact text plus the first-party `preflight_publication_destination.py --kind original_issue` with title/body/source HEAD. This exception is only for verified native Markdown Issue templates whose actual headings are independently checked; YAML Issue Form originals retain the seven-`##` OpenSiro layout. A local template copy does **not** prove the current first-party file or authorize publication. - **Before owner approval:** Run both canonical case validators first, then run the exact payload validator against the complete title/body file bytes, passing `--case-ref` (observed immutable working fork metadata commit) and `--source-head` (observed current original default HEAD). Missing case sections, inconsistent receipt, wrong owner control/fork, template mismatch, missing historic function, unresolved placeholder or unapproved text edit must return `PUBLICATION_BLOCKED_TEMPLATE_MISMATCH` (or the separate source/authority block). Repair before asking for consent. - **Mandatory original-native template preview before asking for publication approval (owner-visible, fail closed):** Read the **current target repository's first-party Issue Form YAML, legacy Markdown Issue template, or the actual permitted Discussion category/rules** at a verified default-branch commit. For each proposed external or public fork Issue, show the owner **(1)** the exact destination and action (`new original Issue`, `fork Issue`, `original Discussion`, or `comment on an existing Issue`), **(2)** a clickable link to the **actual repository-native template at its verified source commit**, plus a live template/channel link where available, **(3)** a concise faithful inventory of required and optional text fields, dropdown options, required checkboxes/human signoffs, advisory default title and labels (do not invent mandatory title prefixes), **(4)** the exact proposed title and **complete public body in the approval request** (immutable draft link and SHA-256 may supplement, **not substitute for** displaying the full text), and **(5)** an explicit field-by-field comparison identifying where each original-required field is filled, missing, incomplete or incompatible, including optional deviations and recommended corrections. For an original Discussion, show the verified category/rules instead of pretending its Issue template applies; for an existing-Issue comment, show the exact existing Issue and any applicable contribution rules. **Do not ask for publication approval while mandatory text fields are missing or native channel/rules are unknown. If a form requires a human-read/endorsement checkbox, show its exact statement for the owner's own review and obtain a separate truthful attestation before POST; never tick it for the human or treat generic consent as proof the owner personally read the proposal.** A generic `PASS` or a validator checking syntax does not establish that the owner saw the template, agreed with its requirements, or personally read the proposal. First-party GitHub form configuration `title` is an advisory prefill, not by itself a mandatory prefix. +- **Malformed or unsupported native forms:** Distinguish checked-in YAML from a verified effective route. Require the documented `name`, `description`, and `body` keys and supported native field requirements before accepting a recognized feature/change-request form; report unsupported/ambiguous schema evidence explicitly. GitHub GraphQL `issueTemplates` can omit YAML forms, so an empty result never licenses ignoring existing form files. Keep the existing verified template-free route unchanged. For the narrow known YAML defect (legacy `about` instead of required `description`), a blank-Issue fallback is permitted only with a unique, readable feature-form intent, all listed templates matching that defect with supported field layouts, no local chooser configuration or legacy templates, no visible owner-default community repository, current pinned original HEAD, and authenticated GitHub GraphQL evidence for the actual publisher: `hasIssuesEnabled=true`, `viewerCanCreateIssues=true`, `isBlankIssuesEnabled=true`, `issueCreationPolicy=ALL`, empty provider template list. The latter is not sufficient by itself. Retain the source form's required fields and human attestation rules, show that it is not a valid native provider form, preview the verified blank route and publisher, and repeat provider/source/payload checks before POST with the same publisher. Unknown/ambiguous forms or restrictions remain blocked. Do not POST to test availability or infer consent from a malformed form. [GitHub schema](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-issue-forms) · [chooser rules](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository). + - **Approval-preview change control:** Keep the same original `issue.md` / `roadmap.md` case identity. If the external draft, destination, chosen channel, template requirements, required checkboxes or proposed title/body changes after preview or consent, re-run source/native-form/dedup/payload checks and **present the revised complete body and comparison for renewed exact current-conversation approval**. Before any approved POST, re-read live first-party source/template and compare the exact outbound title/body hashes with what the owner approved. A commit-pinned template link documents the observed requirements; it does not replace the final live-readback. If the verified first-party repository has **no native Issue template**, explicitly show that verified absence, first-party evidence that a blank Issue is permitted, and that there are no repository-defined mandatory form fields; do not fabricate a form. If native template requirements, the absence of a template/blank-Issue permission, or Discussion category/rules cannot be verified, report `PUBLICATION_BLOCKED_NATIVE_TEMPLATE_UNVERIFIED`; do not guess what the maintainer accepts. - **Before POST and afterward:** Re-run against the same exact title/body bytes that will be sent to GitHub; record title/body SHA-256 and compare to those explicitly approved. Material edits or destination changes require renewed current-conversation approval. Read back GitHub's actual title/body after an approved POST and reconcile the exact content/hash; keep the fork-local publication receipt. A PASS never authorizes publication. - **Decision independence:** A prospective function-specific constructor with `GO / NEEDS_EVIDENCE` needs architectural C sufficiency, lawful rights and falsifiable source-native behavior, **not proven market demand or preexisting maintainer interest**. Maintainer adoption, human S3–S5 governance, product priorities and implementation remain separate decisions. AI researches, reconciles native overlap, prepares the proposal and gives recommendations; the owner decides whether to promote the architectural hypothesis. Do not import the Upgrade implementation material-delta gate into Roadmap publication preparation. No new score, metric, Index grade or compulsory product demand gate is introduced. diff --git a/scripts/preflight_publication_destination.py b/scripts/preflight_publication_destination.py index 61de795..36bae82 100644 --- a/scripts/preflight_publication_destination.py +++ b/scripts/preflight_publication_destination.py @@ -24,7 +24,7 @@ def is_feature_template(entry): return "feature" in name and "request" in name -def route_errors(target, original, kind, purpose, repo, templates=None, config=None, categories=None, verified_blank_issue=False): +def route_errors(target, original, kind, purpose, repo, templates=None, config=None, categories=None, verified_blank_issue=False, malformed_blank=None): """Pure fail-closed route predicate. Pass first-party GitHub snapshots, not guesses.""" errors = [] if not REPO.fullmatch(target) or not REPO.fullmatch(original): @@ -51,6 +51,9 @@ def route_errors(target, original, kind, purpose, repo, templates=None, config=N if kind == "original_issue": if verified_blank_issue is True and not templates and config is None: pass # Verified effective absence, not an unknown response. + elif (malformed_blank and config is None and templates + and malformed_blank.get("status") == "VERIFIED_VIEWER_BLANK_WITH_MALFORMED_FORMS"): + pass # Separately verified provider permission; retain source-form requirements. elif templates is None: errors.append("ISSUE_CHANNEL_EVIDENCE_UNVERIFIED") else: @@ -236,6 +239,32 @@ def resolve_issue_templates(target, source_head): return templates, config, source, ref +def yaml_form_header_errors(text): + """Check a bounded subset of documented required top-level keys. + + This is not a full YAML parser or proof of provider rendering. Ambiguous + syntax is unsupported rather than being treated as an absent form. + """ + allowed = {"name", "description", "body", "title", "labels", "assignees", + "projects", "type"} + fields = {} + errors = [] + for key, raw in re.findall(r"(?m)^([A-Za-z_][A-Za-z0-9_-]*):[ \t]*(.*)$", text): + if key in fields: + errors.append("YAML_FORM_DUPLICATE_TOP_LEVEL_KEY: " + key) + fields[key] = raw.strip() + if key not in allowed: + errors.append("YAML_FORM_UNSUPPORTED_TOP_LEVEL_KEY: " + key) + for key in ("name", "description", "body"): + if key not in fields: + errors.append("YAML_FORM_REQUIRED_KEY_MISSING: " + key) + elif key != "body" and fields[key] in ("", "''", '""', "null", "~"): + errors.append("YAML_FORM_REQUIRED_VALUE_UNVERIFIED: " + key) + if "body" in fields and fields["body"]: + errors.append("YAML_FORM_BODY_LAYOUT_UNSUPPORTED") + return errors + + def classify_issue_templates(templates, source, ref): if templates is None: return None, {} @@ -251,18 +280,28 @@ def classify_issue_templates(templates, source, ref): template = get_optional_file(source, ".github/ISSUE_TEMPLATE/" + name, ref) if template is None: raise RuntimeError("ISSUE_TEMPLATE_CONTENT_UNVERIFIED") - if name.lower().endswith(".md"): + markdown = name.lower().endswith(".md") + if markdown: match = re.match(r"(?s)^---\n(.+?)\n---\n", template) header = match.group(1) if match else "" else: header = template - feature = bool(re.search(r"(?mi)^name:[ \t]*[\"']?feature[ \t]+request[\"']?[ \t]*$", header)) - # Some maintainers call the canonical feature-request form "Idea". - # Require both the verified native form name and conventional filename; - # an arbitrary Idea form or a misleading filename alone is insufficient. - if not feature and re.fullmatch(r"feature[_-]request\.ya?ml", name, re.I): - feature = bool(re.search(r"(?mi)^name:[ \t]*[\"']?idea[\"']?[ \t]*$", header)) - classified.append({**entry, "feature_request": feature}) + candidate = bool(re.search(r"(?mi)^name:[ \t]*[\"']?feature[ \t]+request[\"']?[ \t]*$", header)) + # Recognize these explicit names only on conventional feature-form + # filenames; neither a filename nor a missing API listing is proof. + if not candidate and re.fullmatch(r"feature[_-]request\.ya?ml", name, re.I): + candidate = bool(re.search( + r"(?mi)^name:[ \t]*[\"']?(?:idea|feature[ \t]*/[ \t]*change[ \t]+request)[\"']?[ \t]*$", + header)) + diagnostics = [] if markdown else yaml_form_header_errors(template) + if candidate and not diagnostics and not markdown: + try: + feature_form_requirements(template) + except ValueError as exc: + diagnostics.append(str(exc)) + classified.append({**entry, "feature_request": candidate and not diagnostics, + "feature_candidate": candidate, + "form_diagnostics": diagnostics}) contents[name] = template return classified, contents @@ -295,6 +334,90 @@ def verify_blank_issue_route(target, original_pin, templates, config, source, re and ((repo.get("defaultBranchRef") or {}).get("target") or {}).get("oid") == original_pin) +MALFORMED_ABOUT_ERRORS = { + "YAML_FORM_UNSUPPORTED_TOP_LEVEL_KEY: about", + "YAML_FORM_REQUIRED_KEY_MISSING: description", +} + + +def verify_malformed_form_blank_route(target, pin, raw_templates, templates, contents, + config, source, ref): + """Narrow fallback, not general YAML recovery or authority to publish. + + Only the known about-for-description defect is eligible; preserve the + unique feature form's supported native fields. Any other ambiguity blocks. + GitHub's authenticated viewer-specific flags, not issueTemplates alone, + are the positive evidence of permission to create a blank Issue. + """ + if config is not None or not templates or source != target or ref != pin: + return None + if len(raw_templates or []) != len(templates): + return None + candidates = [e for e in templates if e.get("feature_candidate")] + if len(candidates) != 1: + return None + for entry in templates: + if (not entry["name"].lower().endswith((".yaml", ".yml")) + or set(entry.get("form_diagnostics", [])) != MALFORMED_ABOUT_ERRORS): + return None + try: + feature_form_requirements(contents[entry["name"]]) + except ValueError: + return None + # Do not silently ignore alternate legacy templates, chooser config, + # inherited community rules, or a redirect to another channel. + for path in (".github/ISSUE_TEMPLATE/config.yml", ".github/ISSUE_TEMPLATE/config.yaml", + ".github/ISSUE_TEMPLATE.md", "ISSUE_TEMPLATE.md", "docs/ISSUE_TEMPLATE.md"): + if get_optional_file(target, path, pin) is not None: + return None + defaults = target.split("/", 1)[0] + "/.github" + if defaults == target: + return None + try: + # A visible default community repository requires further review; + # this narrow fallback never assumes its rules are irrelevant. + gh_api("repos/" + defaults) + except RuntimeError as error: + if "404" not in str(error) and "Not Found" not in str(error): + raise + else: + return None + owner, name = target.split("/", 1) + query = ("query($owner:String!,$name:String!){viewer{login}" + "repository(owner:$owner,name:$name){nameWithOwner hasIssuesEnabled " + "isBlankIssuesEnabled viewerCanCreateIssues issueCreationPolicy " + "issueTemplates{name filename} defaultBranchRef{target{oid}}}}") + call = subprocess.run( + ["gh", "api", "graphql", "-f", f"query={query}", + "-f", f"owner={owner}", "-f", f"name={name}"], + text=True, capture_output=True, check=False) + if call.returncode: + raise RuntimeError("VIEWER_BLANK_ISSUE_PERMISSION_READ_FAILED") + result = json.loads(call.stdout) + data = result.get("data") or {} + repo = data.get("repository") or {} + viewer = (data.get("viewer") or {}).get("login") + if result.get("errors") or repo.get("nameWithOwner") != target or not viewer: + raise RuntimeError("VIEWER_BLANK_ISSUE_PERMISSION_UNVERIFIED") + if not (repo.get("hasIssuesEnabled") is True + and repo.get("viewerCanCreateIssues") is True + and repo.get("isBlankIssuesEnabled") is True + and repo.get("issueCreationPolicy") == "ALL" + and repo.get("issueTemplates") == [] + and ((repo.get("defaultBranchRef") or {}).get("target") or {}).get("oid") == pin): + return None + entry = candidates[0] + return {"status": "VERIFIED_VIEWER_BLANK_WITH_MALFORMED_FORMS", + "publisher": viewer, "source_head": pin, "repository": target, + "isBlankIssuesEnabled": True, "viewerCanCreateIssues": True, + "issueCreationPolicy": "ALL", + "graphql_issueTemplates": [], + "source_form": ".github/ISSUE_TEMPLATE/" + entry["name"], + "source_form_requirements": feature_form_requirements(contents[entry["name"]]), + "source_form_not_valid_provider_form": True, + "url": f"https://github.com/{target}/issues/new"} + + def get_categories(repo): owner, name = repo.split("/", 1) query = ("query($owner:String!,$name:String!){repository(owner:$owner,name:$name)" @@ -332,13 +455,18 @@ def main(): repo = gh_api("repos/" + args.target) templates = config = categories = None verified_blank_issue = False + malformed_blank = None if args.kind == "original_issue": original_pin = pinned_head(args.target, repo.get("default_branch")) templates, config, template_repo, ref = resolve_issue_templates( args.target, original_pin) verified_blank_issue = verify_blank_issue_route( args.target, original_pin, templates, config, template_repo, ref) + raw_templates = templates templates, template_contents = classify_issue_templates(templates, template_repo, ref) + malformed_blank = verify_malformed_form_blank_route( + args.target, original_pin, raw_templates, templates, template_contents, + config, template_repo, ref) proof["issue_template_source"] = { "repository": template_repo, "commit": ref, "inherited": template_repo != args.target, @@ -349,7 +477,40 @@ def main(): elif args.kind == "original_discussion": categories = get_categories(args.target) errors = route_errors(args.target, args.original, args.kind, args.purpose, - repo, templates, config, categories, verified_blank_issue) + repo, templates, config, categories, verified_blank_issue, malformed_blank) + if args.kind == "original_issue": + proof["native_form_diagnostics"] = [ + {"path": ".github/ISSUE_TEMPLATE/" + e["name"], + "feature_candidate": e["feature_candidate"], + "errors": e["form_diagnostics"]} + for e in templates or [] if e["form_diagnostics"]] + if not malformed_blank and any(e["feature_candidate"] and e["form_diagnostics"] for e in templates or []): + errors.append("NATIVE_FEATURE_FORM_SCHEMA_UNVERIFIED") + if not malformed_blank and not verified_blank_issue and not any(is_feature_template(e) for e in templates or []): + proof["blank_issue_route"] = { + "status": "NOT_VERIFIED", + "reason": "Existing, invalid, unsupported or restricted template evidence is not absence. " + "GraphQL issueTemplates can omit YAML forms. " + "No eligible authenticated contributor-visible blank route was verified.", + "url": f"https://github.com/{args.target}/issues/new/choose", + "provider_schema": "https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-issue-forms", + "provider_chooser": "https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository"} + if args.kind == "original_issue" and malformed_blank: + proof["blank_issue_route"] = malformed_blank + spec = malformed_blank["source_form_requirements"] + proof["issue_template_source"]["template_url"] = ( + f"https://github.com/{template_repo}/blob/{ref}/" + + malformed_blank["source_form"]) + proof["human_signoff_requires_real_review"] = any( + re.search(r"(?i)human", v) for v in spec["required_checkboxes"]) + if bool(args.title_file) != bool(args.body_file): + errors.append("TITLE_AND_BODY_REQUIRED_TOGETHER") + elif args.title_file and args.body_file: + from pathlib import Path + title, body = Path(args.title_file).read_text(), Path(args.body_file).read_text() + if not title.strip() or not body.strip(): + errors.append("BLANK_ISSUE_TITLE_OR_BODY_MISSING") + errors.extend(feature_form_payload_errors(spec, title, body)) if args.kind == "original_issue" and not errors and verified_blank_issue: proof["native_blank_issue"] = { "url": f"https://github.com/{args.target}/issues/new", @@ -362,7 +523,7 @@ def main(): from pathlib import Path if not Path(args.title_file).read_text().strip() or not Path(args.body_file).read_text().strip(): errors.append("BLANK_ISSUE_TITLE_OR_BODY_MISSING") - if args.kind == "original_issue" and not errors and not verified_blank_issue: + if args.kind == "original_issue" and not errors and not verified_blank_issue and not malformed_blank: form_names = [x.get("name") for x in templates or [] if is_feature_template(x)] if len(form_names) != 1: diff --git a/tests/test_publication_destination.py b/tests/test_publication_destination.py index c27ce11..c197220 100644 --- a/tests/test_publication_destination.py +++ b/tests/test_publication_destination.py @@ -22,12 +22,220 @@ def repo(name, **changes): return data +def valid_form(name="Feature / change request"): + return (f"name: {name}\ndescription: Propose a change\nbody:\n" + " - type: textarea\n id: problem\n attributes:\n" + " label: Problem\n validations:\n required: true\n") + + class PublicationDestinationTests(unittest.TestCase): + def test_feature_change_request_alias_requires_schema_and_native_fields(self): + entries = [{"name": "feature_request.yml", "type": "file"}, + {"name": "other.yml", "type": "file"}] + with patch.object(destination, "get_optional_file", return_value=valid_form()): + classified, contents = destination.classify_issue_templates(entries, AG2, "a"*40) + self.assertTrue(classified[0]["feature_request"]) + self.assertFalse(classified[1]["feature_request"]) + spec = feature_form_requirements(contents["feature_request.yml"]) + self.assertEqual(spec["required_fields"], ["Problem"]) + self.assertEqual(feature_form_payload_errors(spec, "Proposal", "### Problem\nObserved problem"), []) + self.assertIn("NATIVE_FEATURE_REQUIRED_FIELD_MISSING: Problem", + feature_form_payload_errors(spec, "Proposal", "No heading")) + + def test_malformed_yaml_form_not_treated_as_blank_or_feature(self): + entries = [{"name": "feature_request.yml", "type": "file"}] + for name in ("Feature Request", "Feature / change request", "Idea"): + form = valid_form(name).replace("description:", "about:") + with patch.object(destination, "get_optional_file", return_value=form): + classified, _ = destination.classify_issue_templates(entries, AG2, "a"*40) + item = classified[0] + self.assertTrue(item["feature_candidate"]) + self.assertFalse(item["feature_request"]) + self.assertIn("YAML_FORM_REQUIRED_KEY_MISSING: description", item["form_diagnostics"]) + self.assertIn("YAML_FORM_UNSUPPORTED_TOP_LEVEL_KEY: about", item["form_diagnostics"]) + self.assertIn("FEATURE_REQUEST_TEMPLATE_OR_CHANNEL_UNVERIFIED", + route_errors(AG2, AG2, "original_issue", "feature_request", + repo(AG2), classified, None)) + with patch.object(destination.subprocess, "run") as api: + self.assertFalse(destination.verify_blank_issue_route( + AG2, "a"*40, entries, None, AG2, "a"*40)) + api.assert_not_called() + + def test_cli_malformed_form_reports_blocker_not_approval(self): + import contextlib + import io + import json + entries = [{"name": "feature_request.yml", "type": "file"}] + pin = "a"*40 + form = valid_form().replace("description:", "about:") + out = io.StringIO() + with patch.object(sys, "argv", ["preflight", "--target", AG2, + "--original", AG2, "--kind", "original_issue"]), \ + patch.object(destination, "gh_api", return_value=repo(AG2)), \ + patch.object(destination, "pinned_head", return_value=pin), \ + patch.object(destination, "resolve_issue_templates", + return_value=(entries, None, AG2, pin)), \ + patch.object(destination, "get_optional_file", return_value=form), \ + contextlib.redirect_stdout(out): + self.assertEqual(destination.main(), 2) + result = json.loads(out.getvalue()) + self.assertEqual(result["status"], "PUBLICATION_BLOCKED_DESTINATION") + self.assertEqual(result["blank_issue_route"]["status"], "NOT_VERIFIED") + self.assertIn("NATIVE_FEATURE_FORM_SCHEMA_UNVERIFIED", result["errors"]) + self.assertIn("YAML_FORM_REQUIRED_KEY_MISSING: description", + result["native_form_diagnostics"][0]["errors"]) + self.assertNotIn("native_blank_issue", result) + self.assertNotIn("native_feature_form", result) + self.assertEqual(result["approval"], "REQUIRES_EXACT_CURRENT_CONVERSATION_OWNER_CONSENT") + + def test_malformed_blank_requires_positive_viewer_permission_and_current_pin(self): + import json + from types import SimpleNamespace + pin = "a"*40 + entries = [{"name": "feature_request.yml", "type": "file"}, + {"name": "bug_report.yml", "type": "file"}] + forms = [valid_form().replace("description:", "about:"), + valid_form("Bug Report").replace("description:", "about:")] + with patch.object(destination, "get_optional_file", side_effect=forms): + classified, contents = destination.classify_issue_templates(entries, AG2, pin) + good = {"nameWithOwner": AG2, "hasIssuesEnabled": True, + "viewerCanCreateIssues": True, "isBlankIssuesEnabled": True, + "issueCreationPolicy": "ALL", "issueTemplates": [], + "defaultBranchRef": {"target": {"oid": pin}}} + with patch.object(destination, "get_optional_file", return_value=None), patch.object(destination, "gh_api", side_effect=RuntimeError("404 Not Found")), patch.object(destination.subprocess, "run") as api: + for changes, expected in (({}, True), + ({"viewerCanCreateIssues": False}, False), + ({"isBlankIssuesEnabled": False}, False), + ({"isBlankIssuesEnabled": None}, False), + ({"hasIssuesEnabled": False}, False), + ({"issueCreationPolicy": "COLLABORATORS_ONLY"}, False), + ({"issueCreationPolicy": None}, False), + ({"issueTemplates": [{"name": "Feature Request"}]}, False), + ({"defaultBranchRef": {"target": {"oid": "b"*40}}}, False)): + api.return_value = SimpleNamespace(returncode=0, stdout=json.dumps( + {"data": {"viewer": {"login": "contributor"}, + "repository": {**good, **changes}}})) + result = destination.verify_malformed_form_blank_route( + AG2, pin, entries, classified, contents, None, AG2, pin) + self.assertEqual(bool(result), expected, changes) + if expected: + self.assertEqual(result["publisher"], "contributor") + self.assertEqual(result["source_form_requirements"]["required_fields"], ["Problem"]) + self.assertTrue(result["source_form_not_valid_provider_form"]) + self.assertEqual(route_errors(AG2, AG2, "original_issue", "feature_request", + repo(AG2), classified, None, + malformed_blank=result), []) + self.assertIn("ISSUES_DISABLED", route_errors( + AG2, AG2, "original_issue", "feature_request", + repo(AG2, has_issues=False), classified, None, malformed_blank=result)) + api.return_value = SimpleNamespace(returncode=1, stdout="") + with self.assertRaisesRegex(RuntimeError, "VIEWER_BLANK_ISSUE_PERMISSION_READ_FAILED"): + destination.verify_malformed_form_blank_route( + AG2, pin, entries, classified, contents, None, AG2, pin) + for data in ({"repository": good}, + {"viewer": {"login": "contributor"}, "repository": {**good, "nameWithOwner": "other/repo"}}): + api.return_value = SimpleNamespace(returncode=0, stdout=json.dumps({"data": data})) + with self.assertRaisesRegex(RuntimeError, "VIEWER_BLANK_ISSUE_PERMISSION_UNVERIFIED"): + destination.verify_malformed_form_blank_route( + AG2, pin, entries, classified, contents, None, AG2, pin) + + def test_malformed_blank_rejects_configuration_inheritance_and_unknown_forms(self): + pin = "a"*40 + entries = [{"name": "feature_request.yml", "type": "file"}] + malformed = valid_form().replace("description:", "about:") + with patch.object(destination, "get_optional_file", return_value=malformed): + classified, contents = destination.classify_issue_templates(entries, AG2, pin) + with patch.object(destination.subprocess, "run") as api: + for config, source, ref in (("blank_issues_enabled: false", AG2, pin), + ("contact_links: []", AG2, pin), + (None, "ag2ai/.github", pin), + (None, AG2, "b"*40)): + self.assertIsNone(destination.verify_malformed_form_blank_route( + AG2, pin, entries, classified, contents, config, source, ref)) + with patch.object(destination, "get_optional_file", return_value="legacy/config"): + self.assertIsNone(destination.verify_malformed_form_blank_route( + AG2, pin, entries, classified, contents, None, AG2, pin)) + with patch.object(destination, "get_optional_file", return_value=None), patch.object(destination, "gh_api", return_value=repo("ag2ai/.github")): + self.assertIsNone(destination.verify_malformed_form_blank_route( + AG2, pin, entries, classified, contents, None, AG2, pin)) + self.assertIsNone(destination.verify_malformed_form_blank_route( + AG2, pin, entries + [{"name": "other", "type": "dir"}], + classified, contents, None, AG2, pin)) + self.assertIsNone(destination.verify_malformed_form_blank_route( + AG2, pin, entries, classified, + {"feature_request.yml": malformed.replace("textarea", "unknown")}, None, AG2, pin)) + api.assert_not_called() + + def test_cli_malformed_blank_preserves_required_fields_and_attestation(self): + import contextlib + import io + import json + import tempfile + from types import SimpleNamespace + pin = "a"*40 + entries = [{"name": "feature_request.yml", "type": "file"}] + form = (valid_form().replace("description:", "about:") + + " - type: checkboxes\n attributes:\n label: Authorship\n" + " options:\n - label: A human reviewed this issue.\n required: true\n") + good = {"nameWithOwner": AG2, "hasIssuesEnabled": True, "viewerCanCreateIssues": True, + "isBlankIssuesEnabled": True, "issueCreationPolicy": "ALL", "issueTemplates": [], + "defaultBranchRef": {"target": {"oid": pin}}} + def read_file(repo_name, path, ref): + return form if path.endswith("feature_request.yml") else None + def rest(path): + if path == "repos/ag2ai/.github": + raise RuntimeError("404 Not Found") + if "/branches/" in path: + return {"commit": {"sha": pin}} + return repo(AG2) + with tempfile.TemporaryDirectory() as tmp: + title, body = Path(tmp)/"title", Path(tmp)/"body" + title.write_text("Proposal") + for text, expected in (("No required fields", 2), + ("### Problem\nObserved problem\n", 2), + ("### Problem\nObserved problem\n- [x] A human reviewed this issue.\n", 0)): + body.write_text(text) + out = io.StringIO() + with patch.object(sys, "argv", ["preflight", "--target", AG2, "--original", AG2, + "--kind", "original_issue", "--source-head", pin, + "--title-file", str(title), "--body-file", str(body)]), patch.object(destination, "gh_api", side_effect=rest), patch.object(destination, "resolve_issue_templates", return_value=(entries, None, AG2, pin)), patch.object(destination, "get_optional_file", side_effect=read_file), patch.object(destination.subprocess, "run", return_value=SimpleNamespace(returncode=0, stdout=json.dumps({"data": {"viewer": {"login": "contributor"}, "repository": good}}))), contextlib.redirect_stdout(out): + self.assertEqual(destination.main(), expected) + result = json.loads(out.getvalue()) + self.assertTrue(result["human_signoff_requires_real_review"]) + self.assertEqual(result["blank_issue_route"]["publisher"], "contributor") + self.assertEqual(result["approval"], "REQUIRES_EXACT_CURRENT_CONVERSATION_OWNER_CONSENT") + if expected: + self.assertTrue(any("REQUIRED_CHECKBOX" in e for e in result["errors"])) + else: + self.assertEqual(result["status"], "ROUTE_PREFLIGHT_PASS_NOT_PUBLICATION_APPROVAL") + + def test_valid_yaml_omitted_by_graphql_does_not_enable_blank_route(self): + entries = [{"name": "feature_request.yml", "type": "file"}] + with patch.object(destination.subprocess, "run") as api: + self.assertFalse(destination.verify_blank_issue_route( + AG2, "a"*40, entries, None, AG2, "a"*40)) + api.assert_not_called() + + def test_unsupported_native_form_does_not_qualify(self): + entries = [{"name": "feature_request.yml", "type": "file"}] + cases = ( + (valid_form().replace("textarea", "unknown"), "UNRECOGNIZED_FEATURE_FORM_FIELD"), + (valid_form().replace("description:", "unknown:"), "YAML_FORM_UNSUPPORTED_TOP_LEVEL_KEY"), + (valid_form().replace("description: Propose a change", "description: ''"), "YAML_FORM_REQUIRED_VALUE_UNVERIFIED"), + (valid_form() + "name: Feature Request\n", "YAML_FORM_DUPLICATE_TOP_LEVEL_KEY"), + ) + for form, error in cases: + with patch.object(destination, "get_optional_file", return_value=form): + classified, _ = destination.classify_issue_templates(entries, AG2, "a"*40) + self.assertFalse(classified[0]["feature_request"]) + self.assertTrue(any(x.startswith(error) for x in classified[0]["form_diagnostics"])) + + def test_inherited_feature_form_pins_owner_defaults(self): target, defaults = "agent-sh/keel", "agent-sh/.github" head, default_head = "a"*40, "b"*40 entries = [{"name": "feature.yml", "type": "file"}] - form = ("name: Feature Request\nbody:\n - type: textarea\n" + form = ("name: Feature Request\ndescription: Request a feature\nbody:\n - type: textarea\n" " attributes:\n label: Problem\n" " validations:\n required: true\n") def optional_file(repo_name, path, ref): @@ -77,7 +285,7 @@ def test_declared_name_not_filename_and_ambiguous_forms(self): {"name": "01-feature.yml", "type":"file"}, {"name": "02-feature.yml", "type":"file"}] with patch.object(destination,"get_optional_file", - side_effect=["name: Bug Report", "name: Feature Request", "name: Feature request"]): + side_effect=[valid_form("Bug Report"), valid_form("Feature Request"), valid_form("Feature request")]): classified, _ = destination.classify_issue_templates(entries,AG2,"a"*40) self.assertEqual([e["name"] for e in classified if destination.is_feature_template(e)], ["01-feature.yml","02-feature.yml"])