From 30c3b5730b0fda6e2128a1981ad4a1d350e9f720 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:38:28 +0300 Subject: [PATCH 01/14] docs(intake): verify actual license grant before technical candidate work --- docs/ASSESSMENT_CANDIDATE_BATCHES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ASSESSMENT_CANDIDATE_BATCHES.md b/docs/ASSESSMENT_CANDIDATE_BATCHES.md index eb50d4f5..f0017e2f 100644 --- a/docs/ASSESSMENT_CANDIDATE_BATCHES.md +++ b/docs/ASSESSMENT_CANDIDATE_BATCHES.md @@ -10,7 +10,7 @@ Within this expressly selected **#56 experiment**, these commands mean: **comple 1. **Bootstrap:** refresh VSM-OSS `START_HERE.md`, the current Index, this repository's default branch, #56 and #6. Use the **already frozen batch** unless the whole batch is resolved; never silently re-pin historical assessment identities. 2. **Freeze intake before execution:** select a bounded, full cohort (normally **five** assessment records, up to ten) from the canonical *included* Index corpus. Record one exact Index SHA, each assessment path, assessed upstream repo/ref, source-derived question and fixed order. Check for duplicate prior candidates/interventions. This is a **screening cohort**, *not* a claim that five useful patches are known or that five S1 work items are admitted. Never pad with unassessed GitHub favourites. -3. **Screen in order:** for the first `SCREENING` or `ACTIVE` row, independently inspect current upstream source, issue/PR overlap, policy/licensing and native tests; record the four fit gates (`need`, `mechanism`, `counterfactual`, `scope`) and dated primary-source links. A VSM grade alone is not a bug. If fit fails, `CLOSED_NO_CHANGE` with evidence; if insufficient, `BLOCKED_EVIDENCE` with the missing input. +3. **Screen in order — license first:** for the first `SCREENING` or `ACTIVE` row, **before preparing a derivative patch or public fork**, inspect the actual current upstream `LICENSE`/notices (not just GitHub's often-incomplete license label), permission to redistribute the proposed change, and any material license compatibility limit. Record the upstream ref, exact license source/link, SPDX or `UNKNOWN`, and a `LICENSE_ELIGIBLE` / `LICENSE_BLOCKED` / `LICENSE_UNRESOLVED` verdict. If no usable grant is established, do not copy/modify/publish upstream code; record `BLOCKED_EVIDENCE` with the missing permission instead of completing a technical packet. Only **after** this intake gate, inspect source, issue/PR overlap, contributor policy and native tests; record the four fit gates (`need`, `mechanism`, `counterfactual`, `scope`) and dated primary-source links. A VSM grade alone is not a bug. If fit fails, `CLOSED_NO_CHANGE` with evidence; if insufficient, `BLOCKED_EVIDENCE` with the missing input. 4. **Execute a qualified case:** only after four `PASS` gates and a falsifiable source-derived plan, execute relevant **native deterministic scripts** against pinned genuine product code, matched baseline/after and controls. **Never** run live LLM agents, Browser quality trials or provider calls for this experiment. Track origin class separately (`ASSESSMENT_DERIVED`, `ASSESSMENT_INFORMED`, `GENERAL_UPSTREAM`, `INSUFFICIENT`) and never retroactively improve it. 5. **Return then advance:** when a valid local test/patch/handoff is complete and external fork/PR authority is unavailable, mark **`AWAITING_EXTERNAL`** with the precise prepared packet and unexercised right, then immediately continue to the **next** eligible row. `AWAITING_EXTERNAL` is **not** a closed contribution, not a denial and not evidence of external delivery. Revisit it only after a new, attributable grant, a fresh maintainer response, or an explicit targeted command. A genuine unresolvable policy conflict may end in `ESCALATED`, without blocking unrelated candidate screening. 6. **Batch rollover:** only when no eligible rows remain, produce an evidence-backed batch summary and select the next **complete** frozen cohort from fresh canonical Index evidence. Do not reinsert screened or deferred candidates into the new batch without an explicit, documented revisit decision. If there are insufficient eligible assessments, state `NO_ELIGIBLE_ASSESSMENT_CANDIDATE` without a manufactured batch. From 1cfb65d78a13238ce398d3a4f7b1a1db8c0feb97 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:38:30 +0300 Subject: [PATCH 02/14] docs(intake): verify actual license grant before technical candidate work --- docs/ASSESSMENT_TO_IMPROVEMENT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ASSESSMENT_TO_IMPROVEMENT.md b/docs/ASSESSMENT_TO_IMPROVEMENT.md index 42baff88..5edac1dd 100644 --- a/docs/ASSESSMENT_TO_IMPROVEMENT.md +++ b/docs/ASSESSMENT_TO_IMPROVEMENT.md @@ -55,7 +55,7 @@ Do not promote `ASSESSMENT_INFORMED` into `ASSESSMENT_DERIVED` by finding a post 1. **Index-first discovery (positive evidence):** refresh the *current canonical Index default branch*; independently select an included assessment before picking an upstream fix or favorite fork; pin Index commit, assessment path, its assessed target `review_ref`, function and exact source-backed decision/feedback owner/constraint. Preserve dated snapshots; a historical assessment never claims the source is still unchanged. 2. **Function-to-mechanism hypothesis (positive evidence):** identify what operational loop does not close as required, which actor currently makes the decisive decision, the specific mechanism proposed to change behavior, expected native benefit and a plausible failure/null outcome. Explain *why the assessment finding predicts/selects this mechanism*, independently of any prospective VSM grade. -3. **Native need/fit (independent evidence):** inspect current target default branch and its genuine contribution target (which can be a distinct `development` branch), first-party code, maintainer signal/issue/PR overlap, licensing/DCO/CLA rules, product scope and impact. Record `PASS`, `PENDING` or `FAIL` separately for **need, mechanism, counterfactual benefit, scope**. A VSM diagnosis or issue citation alone cannot make these pass. +3. **Native need/fit (independent evidence):** **first check current upstream license text, notices and planned derivative/redistribution compatibility at candidate screening**; missing GitHub license metadata alone is inconclusive, but no actual license grant means no public derivative fork/patch. Then inspect the current target default branch and its genuine contribution target (which can be a distinct `development` branch), first-party code, maintainer signal/issue/PR overlap, DCO/CLA/contributor rules, product scope and impact. Record `PASS`, `PENDING` or `FAIL` separately for **need, mechanism, counterfactual benefit, scope**. A VSM diagnosis or issue citation alone cannot make these pass. 4. **Before/after script protocol (before implementing):** freeze deterministic native test inputs, baseline source SHA, environment, metric/observable, sample or repeated-trial plan, effect threshold or acceptance condition, safety/rollback checks, expected regressions and confounders. Select metrics from the actual function: e.g. preserved concurrent writes, CLI recovery outcome, refusal of unsafe source actions or reliability *where relevant*. Do not impose arbitrary agent autonomy or score-driven targets. 5. **Native scripted test and repair:** demonstrate the pre-change failure/shortfall by executing actual product source through reproducible scripts; implement one scoped upstream-native change; re-run the matched scripted workload against changed code and inspect native regressions. Retain exact code, tests, commands, observations and failed attempts. Do not substitute a mock-only pass for a real product-code path. A green CI alone proves checks ran, **not that a deployed/user benefit was measured**. Do not add live LLM agents as an extra verification step. 6. **Decision and outcome:** compare pre/post observations and evidence limits. State `BENEFIT_SUPPORTED`, `NO_BENEFIT_OBSERVED` or `INCONCLUSIVE`, plus functional mechanism effect and whether any authority/decision owner changed. No self-awarded reclassification of Index grades. If scope/policy is incompatible, return `NO_ELIGIBLE_ASSESSMENT_CANDIDATE` / `BLOCKED_EVIDENCE` instead of swapping to a convenient unrelated issue. From 095e7498e4f4c34c7d4837db342d571d2b7257d2 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:38:32 +0300 Subject: [PATCH 03/14] docs(intake): verify actual license grant before technical candidate work --- docs/CORRECTIVE_PR_PUBLICATION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CORRECTIVE_PR_PUBLICATION.md b/docs/CORRECTIVE_PR_PUBLICATION.md index fd65afef..db8f1466 100644 --- a/docs/CORRECTIVE_PR_PUBLICATION.md +++ b/docs/CORRECTIVE_PR_PUBLICATION.md @@ -14,7 +14,7 @@ This supersedes the prior **human-per-PR publication choice only within the enum ## Before every external write -1. Read the current first-party upstream default/target branch, source commit, `CONTRIBUTING`, issue-assignment/CLA/DCO rules, license, and existing issues/open PRs. Reproduce the bounded original native RED using genuine product code, then apply/adapt the patch and run matched GREEN plus available non-agent first-party tests. If current source already fixes the bug, mark `CLOSED_NO_CHANGE` and do **not** create a redundant PR. Report newly uncovered inconclusive cases as blocked, not as delivered fixes. +1. Reconfirm the **license-first candidate-intake verdict** from [the candidate-batch route](ASSESSMENT_CANDIDATE_BATCHES.md) against current first-party LICENSE/NOTICE text and source commit **before touching derivative code or creating a fork**. For the already-frozen 34, this is a fresh publication preflight, not retroactive alteration of earlier historical fit records. Then read the current default/target branch, `CONTRIBUTING`, issue-assignment/CLA/DCO rules and existing issues/open PRs. Reproduce the bounded original native RED using genuine product code, then apply/adapt the patch and run matched GREEN plus available non-agent first-party tests. If current source already fixes the bug, mark `CLOSED_NO_CHANGE` and do **not** create a redundant PR. Report newly uncovered inconclusive cases as blocked, not as delivered fixes. 2. Verify the **actual authenticated actor**, its organization membership, the ability to create and push a public fork, the exact parent/fork source and branch SHAs. Check connected GitHub tool capabilities at runtime; if no create-fork operation exists, use **only** a preconfigured credential-owning VM/host with authorized `gh` access. Do not ask for or copy the PAT into chat, scrape credentials or bypass a disabled capability. 3. Check the intended `opensiro/` head is not a default/protected branch, the upstream base is correct, the comparison contains only the proposed files, there are no secrets, and no conflicting identical PR exists. Keep the submission as **Draft** unless source policy/maintainer explicitly requires another state and the same mandate permits it. 4. Use the existing [authenticated GET preflight](../scripts/upstream_pr_handoff.py) where available. If it returns `PR_BLOCKED_NO_WRITE`, **stop that case** and preserve a precise blocker. In the presence of an explicit compatible host API, the already-authorized publication may then use the GitHub REST `POST /repos/OWNER/REPO/pulls` with an exact verified organization-fork head. Read back the created PR. No synthetic success receipt is accepted. From 6b06726769264c408a138dd67b097e2d3358115f Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:39:08 +0300 Subject: [PATCH 04/14] docs(publication): separate automatable checks from reserved contributor rights --- docs/CORRECTIVE_PR_PUBLICATION.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/docs/CORRECTIVE_PR_PUBLICATION.md b/docs/CORRECTIVE_PR_PUBLICATION.md index db8f1466..7c59ccab 100644 --- a/docs/CORRECTIVE_PR_PUBLICATION.md +++ b/docs/CORRECTIVE_PR_PUBLICATION.md @@ -20,6 +20,23 @@ This supersedes the prior **human-per-PR publication choice only within the enum 4. Use the existing [authenticated GET preflight](../scripts/upstream_pr_handoff.py) where available. If it returns `PR_BLOCKED_NO_WRITE`, **stop that case** and preserve a precise blocker. In the presence of an explicit compatible host API, the already-authorized publication may then use the GitHub REST `POST /repos/OWNER/REPO/pulls` with an exact verified organization-fork head. Read back the created PR. No synthetic success receipt is accepted. 5. Only after a **real** public PR readback, record its URL/number, base/head SHAs, tests, actual actor, CI and follow-up state in the separate [publication ledger](../data/corrective-publication/2026-10-23-01.json). Do not rewrite frozen Index assessments or claim upstream merge. Then move to the next queued candidate without waiting for external review. +## Automatable publication preflight vs reserved rights + +**Automate routine checks whenever the authorized GitHub/runtime port supports them:** read actual LICENSE and contributor docs, search relevant issue/PRs, detect duplicate fixes, inspect branch naming and target base, run script-only RED/GREEN and static CI-compatible checks, inspect required check timing (before **Draft** vs before **merge**), test repository/fork permissions, and read back publication. Reuse an existing issue when sufficient. Opening a **new** external issue/comment, changing to a non-`opensiro/*` head, or altering a mandated workflow requires the appropriate additional authority; being technically automatable is not permission. + +Classify unmet gates instead of reflexively treating all as final `BLOCKED`: + +| Observation | Action | +| --- | --- | +| Actual license grant missing, incompatible or inconclusive | **Do not create a public derivative**; preserve evidence and block/close as appropriate. | +| Existing required issue, permitted `opensiro/*` branch or check is mechanically satisfiable | Complete that preflight automatically and proceed when the current mandate covers the action. | +| Full integration/model/real-agent testing required only **before merge**, but a bounded Draft is allowed | Submit Draft with truthful *not-run/pending* note; do not run prohibited model/agent tests or claim release readiness. | +| Upstream explicitly requires a branch outside the frozen `opensiro/*` envelope or interactive consent **before any PR** | Preserve `POLICY_CONFLICT`/exact missing right. Propose a separate legitimate scope decision; do not evade the third-party rule. | +| DCO/CLA certifies contributor rights or another human-only declaration | Verify whether a genuine authenticated contributor has made that attestation; **never forge or silently auto-sign** the owner's legal declaration. | +| GitHub 403/protected integration or first-party nonnegotiable stop | Record provider/source readback and stop that write, continuing other queue rows only when the operator has not paused the queue. | + +This is a **procedural triage rule**, not a change to `corrective_publication_queue.py` state enum, a reopening of already-dispositioned cases, or permission to publish an outside-scope candidate. The Organization's cross-repository change routing is tracked by [Organization #285](https://github.com/opensiro/vsm-oss-organization/issues/285). Any automated executor must still enforce the exact mandate and run its own negative-case tests before activation. + ## Operation and feedback The bounded work cycle is **source-first → current fit → first-party native RED/GREEN → authentic actor/permission/fork/branch checks → Draft PR → readback → durable result → next case**. Its technical proof is script-only: **never run LLM agents, mocked model-task episodes, model providers, Browser quality trials or benchmarks** as a condition of acceptance. This does not prevent ChatGPT from coordinating repository inspection and GitHub operations as the delegated contributor. From 6e49aca391cb17128d966134254c01c63c06e93d Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:10:57 +0300 Subject: [PATCH 05/14] feat(intake): add read-only source licensing and policy preflight --- scripts/candidate_intake_preflight.py | 207 ++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 scripts/candidate_intake_preflight.py diff --git a/scripts/candidate_intake_preflight.py b/scripts/candidate_intake_preflight.py new file mode 100644 index 00000000..1c1ee02d --- /dev/null +++ b/scripts/candidate_intake_preflight.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""Read-only first-party upstream candidate intake, before any derivative work. + +This inspector collects license text evidence and contributor/issue/PR hints. +It cannot grant copyright permission, certify DCO/CLA, approve a branch or PR, +or authorize any GitHub write. GitHub observations are potentially incomplete. +""" + +import argparse +import base64 +import binascii +import hashlib +import json +import re +import sys +from urllib.parse import quote + +from fork_public_preflight import ReadOnlyError, public_get +from rest_fork_port import StageBlocked, _branch, _repo + +MAX_TEXT_BYTES = 256 * 1024 +MAX_ITEMS = 100 +LICENSE_NAME = re.compile(r"^(licen[sc]e|copying|unlicense)(\.(md|txt|rst))?$", re.I) +POLICY_NAMES = ("CONTRIBUTING.md", "AGENTS.md", "CLAUDE.md") +TOPIC = re.compile(r"[A-Za-z0-9][A-Za-z0-9 ._-]{2,79}\Z") + + +class IntakeError(ValueError): + """A source fact was unverified; do not treat this as license absence.""" + + +def _get(get, path, *, missing_ok=False, list_ok=False): + if not isinstance(path, str) or not path.startswith("/repos/"): + raise IntakeError("Only fixed repository-scoped GET paths are allowed") + response = get(path) + if (type(response) is not tuple or len(response) != 2 + or type(response[0]) is not int): + raise IntakeError("Unverified GitHub API response") + status, data = response + if status == 404 and missing_ok: + return None + if status in (401, 403, 429): + raise IntakeError("GitHub access denied or rate limited, not license absence") + if status != 200: + raise IntakeError("Unexpected GitHub API status: " + str(status)) + if type(data) is not (list if list_ok else dict): + raise IntakeError("Malformed GitHub API response shape") + return data + + +def _contents_path(source, path, ref): + encoded = "/".join(quote(part, safe="") for part in path.split("/")) + return "/repos/" + source + "/contents/" + encoded + "?ref=" + quote(ref, safe="") + + +def _file_text(get, source, path, ref): + result = _get(get, _contents_path(source, path, ref)) + if (result.get("type") != "file" or result.get("encoding") != "base64" + or not isinstance(result.get("content"), str) + or not isinstance(result.get("size"), int) + or not 0 <= result["size"] <= MAX_TEXT_BYTES): + raise IntakeError("License/policy file is unreadable or too large: " + path) + try: + data = base64.b64decode(result["content"].replace("\n", ""), validate=True) + if len(data) > MAX_TEXT_BYTES or len(data) != result["size"]: + raise IntakeError("File exceeds bounded content limit: " + path) + return data.decode("utf-8") + except (binascii.Error, UnicodeError) as exc: + raise IntakeError("License/policy text could not be verified: " + path) from exc + + +def _matches(items, topic): + if topic is None: + return [] + tokens = topic.casefold().split() + matches = [] + for item in items: + if type(item) is not dict: + raise IntakeError("Malformed issue/PR listing entry") + title = item.get("title", "") + if not isinstance(title, str): + raise IntakeError("Malformed issue/PR title") + if all(token in title.casefold() for token in tokens): + matches.append({"number": item.get("number"), "title": title[:200], + "url": item.get("html_url")}) + return matches[:20] + + +def inspect_candidate(*, source, branch=None, topic=None, get=public_get): + """Fetch only public repository evidence; never output an approval.""" + source = _repo(source) + if branch is not None: + branch = _branch(branch) + if topic is not None and (type(topic) is not str or not TOPIC.fullmatch(topic)): + raise IntakeError("Topic must be 3–80 plain search characters") + + result = { + "status": "INSUFFICIENT_EVIDENCE", "authorization": "READ_ONLY_NO_WRITES", + "source": source, "source_branch": branch, "source_sha": None, + "license": {"verdict": "LICENSE_UNRESOLVED", "spdx_metadata": None, + "path": None, "sha256": None, "review_required": True}, + "contributor_policy": {"paths": [], "hints": [], "review_required": True}, + "overlap": {"topic": topic, "issues": [], "pull_requests": [], + "status": "NOT_SEARCHED"}, + "notes": ["First-party text may contain additional obligations; review is required.", + "No POST, fork, patch, PR, license grant or legal sign-off is possible."], + } + repo = _get(get, "/repos/" + source) + if (repo.get("full_name", "").casefold() != source.casefold() + or repo.get("private") is not False + or repo.get("archived") is not False + or repo.get("disabled") is not False): + raise IntakeError("Public source identity/status is unsuitable") + observed_branch = branch or repo.get("default_branch") + if not isinstance(observed_branch, str): + raise IntakeError("Upstream default branch unavailable") + observed_branch = _branch(observed_branch) + result["source_branch"] = observed_branch + result["license"]["spdx_metadata"] = (repo.get("license") or {}).get("spdx_id") + checked = _get(get, "/repos/" + source + "/branches/" + quote(observed_branch, safe="")) + sha = (checked.get("commit") or {}).get("sha") + if type(sha) is not str or re.fullmatch(r"[0-9a-f]{40}", sha) is None: + raise IntakeError("Source revision cannot be pinned") + result["source_sha"] = sha + + root = _get(get, "/repos/" + source + "/contents?ref=" + + quote(observed_branch, safe=""), list_ok=True) + files = {} + for item in root: + if type(item) is not dict or not isinstance(item.get("name"), str): + raise IntakeError("Malformed root directory listing") + if item.get("type") == "file": + files[item["name"].casefold()] = item["name"] + license_paths = sorted((name for name in files.values() + if LICENSE_NAME.fullmatch(name)), key=lambda p: p.casefold()) + if not license_paths: + result["status"] = "LICENSE_BLOCKED" + result["license"]["verdict"] = "LICENSE_NOT_FOUND_AT_ROOT" + result["notes"].append( + "No root LICENSE/COPYING/UNLICENSE observed; do not create a derivative. " + "Check subdirectory licenses or obtain rights from the holder.") + return result + if len(license_paths) > 1: + result["notes"].append("Multiple root license candidates: manual scope review required") + license_path = license_paths[0] + license_text = _file_text(get, source, license_path, observed_branch) + if not license_text.strip(): + raise IntakeError("Observed license file is empty") + result["license"].update({ + "verdict": "LICENSE_TEXT_PRESENT_REVIEW_REQUIRED", "path": license_path, + "sha256": hashlib.sha256(license_text.encode()).hexdigest(), + "other_root_license_candidates": license_paths[1:], + }) + + for path in POLICY_NAMES: + actual = files.get(path.casefold()) + if not actual: + continue + contents = _file_text(get, source, actual, observed_branch) + result["contributor_policy"]["paths"].append({ + "path": actual, "sha256": hashlib.sha256(contents.encode()).hexdigest()}) + for label, pattern in ( + ("DCO_SIGNOFF_MENTIONED", r"\bDCO\b|Signed-off-by"), + ("CLA_MENTIONED", r"\bCLA\b|contributor license agreement"), + ("ISSUE_WORKFLOW_MENTIONED", r"\bissue\b"), + ("BRANCH_NAMING_MENTIONED", r"\bbranch\b|\bbranches\b"), + ("TEST_OR_CI_GATE_MENTIONED", r"\bCI\b|\btests?\b|\bchecks?\b"), + ("DRAFT_PR_GATE_MENTIONED", r"\bbefore (?:opening|submitting|creating) (?:a )?(?:draft )?(?:PR|pull request)\b"), + ("MERGE_GATE_MENTIONED", r"\bbefore merg(?:e|ing)\b|\bprior to merg(?:e|ing)\b"), + ): + if re.search(pattern, contents, re.I) and label not in result["contributor_policy"]["hints"]: + result["contributor_policy"]["hints"].append(label) + + if topic is not None: + path = "/repos/" + source + issues = _get(get, path + "/issues?state=all&per_page=100", list_ok=True) + prs = _get(get, path + "/pulls?state=open&per_page=100", list_ok=True) + result["overlap"].update({ + "issues": _matches([item for item in issues if "pull_request" not in item], topic), + "pull_requests": _matches(prs, topic), + "status": ("PAGINATION_REQUIRED" if len(issues) >= MAX_ITEMS or len(prs) >= MAX_ITEMS + else "TITLE_HEURISTIC_ONLY_NOT_PROOF_OF_ABSENCE"), + }) + if len(issues) >= MAX_ITEMS or len(prs) >= MAX_ITEMS: + result["notes"].append("Open issue/PR inventory reached page limit; check further pages") + result["status"] = "LICENSE_REVIEW_REQUIRED" + return result + + +def main(argv=None, *, get=public_get): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", required=True, help="owner/repo") + parser.add_argument("--branch", help="default branch when omitted") + parser.add_argument("--topic", help="bounded terms for heuristic issue/PR titles") + args = parser.parse_args(argv) + try: + result = inspect_candidate(source=args.source, branch=args.branch, + topic=args.topic, get=get) + except (IntakeError, ReadOnlyError, StageBlocked) as exc: + result = {"status": "INSUFFICIENT_EVIDENCE", + "authorization": "READ_ONLY_NO_WRITES", "reason": str(exc)} + print(json.dumps(result, indent=2, sort_keys=True)) + return 0 if result["status"] == "LICENSE_REVIEW_REQUIRED" else 2 + + +if __name__ == "__main__": + sys.exit(main()) From 1e6acb7f6448fc27ec3c77f9b25726ef32bbd584 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:11:00 +0300 Subject: [PATCH 06/14] feat(intake): add read-only source licensing and policy preflight --- tests/test_candidate_intake_preflight.py | 177 +++++++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 tests/test_candidate_intake_preflight.py diff --git a/tests/test_candidate_intake_preflight.py b/tests/test_candidate_intake_preflight.py new file mode 100644 index 00000000..4139b488 --- /dev/null +++ b/tests/test_candidate_intake_preflight.py @@ -0,0 +1,177 @@ +"""Deterministic negative and positive checks for GET-only candidate intake.""" +import base64 +from io import StringIO +import json +from pathlib import Path +import subprocess +import sys +import unittest +from unittest.mock import patch + +BASE = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BASE / "scripts")) +from candidate_intake_preflight import IntakeError, inspect_candidate, main +from rest_fork_port import StageBlocked + +SOURCE = "outside/example" +PREFIX = "/repos/" + SOURCE +SHA = "c" * 40 + + +def content(text): + data = text.encode("utf-8") + return {"type": "file", "encoding": "base64", + "content": base64.b64encode(data).decode(), "size": len(data)} + + +class FakeGet: + def __init__(self): + self.calls = [] + self.responses = { + PREFIX: (200, {"full_name": SOURCE, "private": False, "archived": False, + "disabled": False, "default_branch": "main", "license": None}), + PREFIX + "/branches/main": (200, {"commit": {"sha": SHA}}), + PREFIX + "/contents?ref=main": (200, [ + {"name": "LICENSE", "type": "file"}, + {"name": "CONTRIBUTING.md", "type": "file"}, + ]), + PREFIX + "/contents/LICENSE?ref=main": (200, content("MIT License\nPermission is hereby granted")), + PREFIX + "/contents/CONTRIBUTING.md?ref=main": ( + 200, content("DCO Signed-off-by; file an issue before a PR. " + "Use a branch, run CI checks before merging; " + "before submitting a draft PR read the guidelines.")), + PREFIX + "/issues?state=all&per_page=100": (200, []), + PREFIX + "/pulls?state=open&per_page=100": (200, []), + } + + def __call__(self, path): + self.calls.append(path) + if not path.startswith(PREFIX): + raise AssertionError("Unexpected nonrepository GET path") + return self.responses.get(path, (404, {})) + + +class CandidateIntakeTests(unittest.TestCase): + def setUp(self): + self.get = FakeGet() + + def inspect(self, **kwargs): + return inspect_candidate(source=SOURCE, get=self.get, **kwargs) + + def test_actual_license_text_required_even_when_spdx_metadata_missing(self): + result = self.inspect() + self.assertEqual(result["status"], "LICENSE_REVIEW_REQUIRED") + self.assertEqual(result["license"]["verdict"], "LICENSE_TEXT_PRESENT_REVIEW_REQUIRED") + self.assertEqual(result["license"]["spdx_metadata"], None) + self.assertEqual(len(result["license"]["sha256"]), 64) + self.assertEqual(result["source_sha"], SHA) + self.assertEqual(result["authorization"], "READ_ONLY_NO_WRITES") + self.assertIn("MERGE_GATE_MENTIONED", result["contributor_policy"]["hints"]) + self.assertIn("DRAFT_PR_GATE_MENTIONED", result["contributor_policy"]["hints"]) + self.assertIn("DCO_SIGNOFF_MENTIONED", result["contributor_policy"]["hints"]) + self.assertFalse(any("POST" in path for path in self.get.calls)) + + def test_no_root_license_blocks_before_policy_and_overlap(self): + self.get.responses[PREFIX + "/contents?ref=main"] = ( + 200, [{"name": "CONTRIBUTING.md", "type": "file"}]) + result = self.inspect(topic="stale edit ledger") + self.assertEqual(result["status"], "LICENSE_BLOCKED") + self.assertEqual(result["license"]["verdict"], "LICENSE_NOT_FOUND_AT_ROOT") + self.assertEqual(result["overlap"]["status"], "NOT_SEARCHED") + self.assertNotIn(PREFIX + "/contents/CONTRIBUTING.md?ref=main", self.get.calls) + self.assertNotIn(PREFIX + "/issues?state=all&per_page=100", self.get.calls) + + def test_license_spdx_metadata_is_not_a_license_text_substitute(self): + self.get.responses[PREFIX][1]["license"] = {"spdx_id": "MIT"} + self.get.responses[PREFIX + "/contents?ref=main"] = (200, []) + self.assertEqual(self.inspect()["status"], "LICENSE_BLOCKED") + + def test_denial_rate_limit_and_missing_license_content_are_unverified(self): + path = PREFIX + "/contents/LICENSE?ref=main" + for status in (403, 429, 404, 500): + with self.subTest(status=status): + self.get.responses[path] = (status, {}) + with self.assertRaises(IntakeError): + self.inspect() + + def test_invalid_base64_size_and_utf8_fail_closed(self): + path = PREFIX + "/contents/LICENSE?ref=main" + bad = [ + {"type": "file", "encoding": "base64", "content": "!!!", "size": 3}, + {"type": "file", "encoding": "base64", "content": "YQ==", "size": 2}, + {"type": "file", "encoding": "base64", "content": "/w==", "size": 1}, + {"type": "file", "encoding": "base64", "content": "YQ==", "size": 300_000}, + ] + for item in bad: + with self.subTest(content=item): + self.get.responses[path] = (200, item) + with self.assertRaises(IntakeError): + self.inspect() + + def test_malformed_api_shape_sha_and_identity_fail_closed(self): + self.get.responses[PREFIX + "/contents?ref=main"] = (200, {}) + with self.assertRaises(IntakeError): + self.inspect() + self.get = FakeGet() + self.get.responses[PREFIX + "/branches/main"] = ( + 200, {"commit": {"sha": "unknown"}}) + with self.assertRaises(IntakeError): + self.inspect() + self.get = FakeGet() + self.get.responses[PREFIX][1]["full_name"] = "outside/elsewhere" + with self.assertRaises(IntakeError): + self.inspect() + + def test_topic_overlap_is_hint_and_prs_are_not_issues(self): + self.get.responses[PREFIX + "/issues?state=all&per_page=100"] = (200, [ + {"number": 7, "title": "Fix stale edit ledger", "html_url": "https://example/7"}, + {"number": 8, "title": "Stale edit ledger", "pull_request": {}, + "html_url": "https://example/8"}, + ]) + self.get.responses[PREFIX + "/pulls?state=open&per_page=100"] = (200, [ + {"number": 8, "title": "Repair stale edit ledger", "html_url": "https://example/8"}, + ]) + result = self.inspect(topic="stale edit ledger") + self.assertEqual(result["overlap"]["status"], + "TITLE_HEURISTIC_ONLY_NOT_PROOF_OF_ABSENCE") + self.assertEqual([i["number"] for i in result["overlap"]["issues"]], [7]) + self.assertEqual([i["number"] for i in result["overlap"]["pull_requests"]], [8]) + + def test_full_first_page_requires_pagination_and_never_clears_overlap(self): + self.get.responses[PREFIX + "/pulls?state=open&per_page=100"] = ( + 200, [{"number": i, "title": "Another unrelated task"} for i in range(100)]) + result = self.inspect(topic="stale edit ledger") + self.assertEqual(result["overlap"]["status"], "PAGINATION_REQUIRED") + + def test_invalid_inputs_rejected_before_network(self): + for data in ({"source": "outside/../../secret"}, + {"source": "outside/example", "branch": "../main"}, + {"source": "outside/example", "topic": "?test&state=open"}): + with self.subTest(data=data), self.assertRaises((IntakeError, StageBlocked, ValueError)): + inspect_candidate(get=self.get, **data) + self.assertEqual(self.get.calls, []) + + def test_cli_json_status_and_nonzero_for_blocked_or_failed(self): + with patch("sys.stdout", new_callable=StringIO) as output: + self.assertEqual(main(["--source", SOURCE], get=self.get), 0) + self.assertEqual(json.loads(output.getvalue())["status"], "LICENSE_REVIEW_REQUIRED") + self.get.responses[PREFIX + "/contents?ref=main"] = (200, []) + with patch("sys.stdout", new_callable=StringIO) as output: + self.assertEqual(main(["--source", SOURCE], get=self.get), 2) + self.assertEqual(json.loads(output.getvalue())["status"], "LICENSE_BLOCKED") + self.get.responses[PREFIX] = (403, {}) + with patch("sys.stdout", new_callable=StringIO) as output: + self.assertEqual(main(["--source", SOURCE], get=self.get), 2) + self.assertEqual(json.loads(output.getvalue())["status"], "INSUFFICIENT_EVIDENCE") + + def test_cli_has_no_write_mode(self): + process = subprocess.run( + [sys.executable, str(BASE / "scripts" / "candidate_intake_preflight.py"), + "--source", SOURCE, "--execute"], capture_output=True, + text=True, check=False) + self.assertNotEqual(process.returncode, 0) + self.assertIn("unrecognized arguments", process.stderr) + + +if __name__ == "__main__": + unittest.main() From 504cfbb944aa24dcc93f6997525550bed673c411 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:11:02 +0300 Subject: [PATCH 07/14] feat(intake): add read-only source licensing and policy preflight --- docs/CANDIDATE_INTAKE_PREFLIGHT.md | 40 ++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 docs/CANDIDATE_INTAKE_PREFLIGHT.md diff --git a/docs/CANDIDATE_INTAKE_PREFLIGHT.md b/docs/CANDIDATE_INTAKE_PREFLIGHT.md new file mode 100644 index 00000000..82f57e44 --- /dev/null +++ b/docs/CANDIDATE_INTAKE_PREFLIGHT.md @@ -0,0 +1,40 @@ +# Read-only candidate intake preflight + +**Owner:** `opensiro/upstream` / experiment [#56](https://github.com/opensiro/upstream/issues/56). **Organizational route:** [VSM-OSS #285](https://github.com/opensiro/vsm-oss-organization/issues/285). This does not create a new S1 domain, permit publication, or change any VSM classification. + +Use **before preparing a derivative patch, creating a fork or opening an external PR**. Run against the actual third-party upstream repository and pin its reported branch SHA: + +```sh +python3 scripts/candidate_intake_preflight.py --source OWNER/REPO --topic 'bounded candidate description' +``` + +The script makes only unauthenticated, repository-scoped GitHub REST `GET` requests. It does not run an agent, model, Browser test, GitHub write, clone, download a credential, or grant copyright permission. Its deterministic unit tests use a fake GET responder. + +## Evidence and interpretation + +1. Check the public repository identity, default/selected branch and exact source SHA. +2. Enumerate root `LICENSE`/`LICENCE`/`COPYING`/`UNLICENSE` files. Read the **actual content** (not only the often-missing GitHub SPDX metadata) and emit the file path and SHA-256. Multiple license candidates require explicit scope review. Notices, vendored-code licenses, patent/trademark limits and proposed patch compatibility **still require human/source review**. +3. Only if a root license file was verified, read available root `CONTRIBUTING.md`, `AGENTS.md`, `CLAUDE.md` and emit bounded flags for DCO/CLA, issue, branch, testing/CI, before-Draft and before-merge mentions. These are textual hints, not an automatically cleared gate; check relevant `.github` files and first-party policies manually where present. +4. If `--topic` is supplied, inspect the first page of issues and open PRs for title overlaps; filter PR entries out of the issue result. This **cannot prove absence of a duplicate**. A full first page returns `PAGINATION_REQUIRED`, and title-only matching can miss synonyms, changed titles and closed PRs. + +| Machine status | Meaning | Next action | +| --- | --- | --- | +| `LICENSE_REVIEW_REQUIRED` (exit 0) | Public source/ref and **nonempty root license text** verified | Human/operator must still establish applicable grant and compatibility before derivative work; then check notices, full contributor policy, overlap and exact Draft/merge timing | +| `LICENSE_BLOCKED` (exit 2) | No root license file observed | Do not make a derivative; investigate other license locations or obtain rights. **Not** a legal judgment that all use is forbidden | +| `INSUFFICIENT_EVIDENCE` (exit 2) | API denied/rate-limited, malformed, missing required content, SHA unverifiable, etc. | Preserve source error, retry/inspect first-party evidence without treating it as license absence | + +**Never convert `LICENSE_REVIEW_REQUIRED` to `LICENSE_ELIGIBLE` automatically.** Human/legal provenance and context determine eligibility, and an SPDX label or apparent OSS license does not override repository-specific policy. No machine status verifies DCO/CLA attestation, external issue assignment, contributor identity, organization fork-write permission, permitted branch naming, CI gate timing or a right to merge. + +The broader [candidate screening process](ASSESSMENT_CANDIDATE_BATCHES.md) owns the triaged `LICENSE_ELIGIBLE` / `LICENSE_BLOCKED` / `LICENSE_UNRESOLVED` verdict; [Corrective publication](CORRECTIVE_PR_PUBLICATION.md) rechecks it on current third-party sources at the publication stage. The already frozen 34-case queue remains unchanged, and running this preflight alone is **not** a publication attempt. + +## Negative-test contract + +The tests must prove that a metadata-only SPDX label cannot bypass absent root license text; 403/429/404 and malformed content never become eligibility; a 100-item page is not exhaustive; invalid repo/branch/topic input never reaches the network; CLI has no `--execute` or mutation mode. Run: + +```sh +python3 -m unittest discover -s tests -p 'test_candidate_intake_preflight.py' -v +python3 -m unittest discover -s tests -p 'test_fork_public_preflight.py' -v +python3 scripts/corrective_publication_queue.py validate +``` + +This is **phase 1, read-only preflight**. Authenticated issue/workflow gates and publication permission checks must be implemented and verified separately under the [organizational change protocol](https://github.com/opensiro/vsm-oss-organization/pull/286) before any new write automation is enabled. From 0b7d8a03c8958f4c9d1b6682558074e11660fd17 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:11:14 +0300 Subject: [PATCH 08/14] docs(intake): link verifiable preflight to screening and publication --- docs/ASSESSMENT_CANDIDATE_BATCHES.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/ASSESSMENT_CANDIDATE_BATCHES.md b/docs/ASSESSMENT_CANDIDATE_BATCHES.md index f0017e2f..cb5f9ea9 100644 --- a/docs/ASSESSMENT_CANDIDATE_BATCHES.md +++ b/docs/ASSESSMENT_CANDIDATE_BATCHES.md @@ -1,5 +1,7 @@ # Assessment-first upstream candidate batches +**Machine-assisted license-first intake:** use the [read-only candidate preflight](CANDIDATE_INTAKE_PREFLIGHT.md) at the beginning of every new candidate review, before any derivative patch or fork. It captures actual root license text, source SHA, contributor hints and bounded duplicate-title observations. `LICENSE_REVIEW_REQUIRED` is evidence **for** a subsequent license compatibility decision, never an automatic `LICENSE_ELIGIBLE` decision or write authorization. + **Owner:** `opensiro/upstream` [#56](https://github.com/opensiro/upstream/issues/56). **Route:** `test S1 function: upstream contributions`. This is an adjacent Upstream experiment, **not** a fourth admitted VSM-OSS S1 domain; [Organization #274](https://github.com/opensiro/vsm-oss-organization/issues/274) remains unmade. The owner-facing Control Plane is [VSM-OSS](https://github.com/opensiro/vsm-oss-organization/blob/main/docs/AGENT_CONTROL_PLANE.md), but the durable queue and evidence stay here. **Distinct owner-authorized publication route (2026-10-23):** `continue corrective PR publication` processes **only** the 34 already source-tested Corrective cases in the [finite ledger](../data/corrective-publication/2026-10-23-01.json) under the [bounded mandate](CORRECTIVE_PR_PUBLICATION.md). It is separate from generic `continue`, which advances **screening** through the frozen assessment-candidate batches and does not retroactively rewrite their historical `AWAITING_EXTERNAL` entries. Record real new external PR outcomes in the separate ledger; no PR was published merely by creating the ledger. The owner approval covers only public fork/branch/external Draft PR publication for the enumerated rows, not upstream merge, protected writes or new cases. From fee8cd938c22ce89e268554e97c24bbd34f14795 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:11:17 +0300 Subject: [PATCH 09/14] docs(intake): link verifiable preflight to screening and publication --- docs/CORRECTIVE_PR_PUBLICATION.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/CORRECTIVE_PR_PUBLICATION.md b/docs/CORRECTIVE_PR_PUBLICATION.md index 7c59ccab..dd0e7e1d 100644 --- a/docs/CORRECTIVE_PR_PUBLICATION.md +++ b/docs/CORRECTIVE_PR_PUBLICATION.md @@ -1,5 +1,7 @@ # Bounded publication mandate — assessment-informed Corrective PRs +**Pre-publication intake:** the [read-only license/overlap preflight](CANDIDATE_INTAKE_PREFLIGHT.md) collects source license text and policy hints before any derivative patch, fork or Draft PR. A successful machine exit means **manual license applicability and complete contributor-policy review are still pending**; it does not clear a publication gate. The frozen 34-case ledger and owner mandate are unchanged. + **Owning experiment:** [Upstream #56](https://github.com/opensiro/upstream/issues/56), under the Upstream contribution execution route of [#6](https://github.com/opensiro/upstream/issues/6). **Operator decision:** confirmed in the current owner conversation on **2026-10-23** after an explicit question about transferring external-publication rights. **Decision holder:** the OpenSiro owner, `xLagerFeuer` (declared holder; this conversation is not a substitute for authenticated GitHub actor readback). **Mandate:** `CORRECTIVE-PUBLISH-2026-10-23-01`. This supersedes the prior **human-per-PR publication choice only within the enumerated Corrective packet set**. The owner authorizes an assistant operating under a legitimately configured contributor credential to create *public organization forks*, own working branches, push bounded fixes/tests, and open **external Draft PRs without returning for individual routine approvals**. The ordinary preparation and candidate-selection rights stay scoped to the concrete work. Publishing a PR remains distinct from upstream acceptance and merge. From 26dfe62cc658a23c6e3b55826e58fef98650a484 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:49:27 +0300 Subject: [PATCH 10/14] feat(intake): inspect nested policy and paginated closed PRs; reconcile Oblivion receipt --- .../corrective-publication/2026-10-23-01.json | 2 +- docs/CANDIDATE_INTAKE_PREFLIGHT.md | 19 +- scripts/candidate_intake_preflight.py | 175 ++++++++++++++---- tests/test_candidate_intake_preflight.py | 128 +++++++++++-- tests/test_corrective_publication_queue.py | 13 +- 5 files changed, 275 insertions(+), 62 deletions(-) diff --git a/data/corrective-publication/2026-10-23-01.json b/data/corrective-publication/2026-10-23-01.json index 2bece195..5e41952b 100644 --- a/data/corrective-publication/2026-10-23-01.json +++ b/data/corrective-publication/2026-10-23-01.json @@ -8,7 +8,7 @@ "authorized_count": 34, "scope": "Exact native-tested Corrective AWAITING_EXTERNAL cases from batches 01–10 only; external Draft PR creation in public opensiro-contributions direct forks, subject to verified actor and upstream gates; no external merge.", "cases": [ - {"id": "oblivion-agent-tool-loop", "publication": "QUEUED"}, + {"id": "oblivion-agent-tool-loop", "publication": "SUBMITTED", "pr_url": "https://github.com/Rohith-s-hub/Oblivion-agent/pull/1", "actor": "xLagerFeuer", "base_sha": "7c57fd23ddd9abb5a2795788364f5dcdf3ec87cb", "head_sha": "1967f1df19f80cd34d4a4b70756ae1589e075c8c", "native_test_receipt": "pilots/oblivion-batch-edit/scripted_atomicity_replay.py — native RED at 7c57fd2 and GREEN on public opensiro/fix-batch-edit-preflight, both re-run 2026-10-23; positive controls PASS", "external_state": "OPEN_DRAFT", "readback_date": "2026-10-23"}, {"id": "raven-stale-edit-ledger", "publication": "QUEUED"}, {"id": "politik-transaction-denial-return", "publication": "QUEUED"}, {"id": "join-the-team-bootstrap-validation", "publication": "QUEUED"}, diff --git a/docs/CANDIDATE_INTAKE_PREFLIGHT.md b/docs/CANDIDATE_INTAKE_PREFLIGHT.md index 82f57e44..0dc7e75e 100644 --- a/docs/CANDIDATE_INTAKE_PREFLIGHT.md +++ b/docs/CANDIDATE_INTAKE_PREFLIGHT.md @@ -14,12 +14,23 @@ The script makes only unauthenticated, repository-scoped GitHub REST `GET` reque 1. Check the public repository identity, default/selected branch and exact source SHA. 2. Enumerate root `LICENSE`/`LICENCE`/`COPYING`/`UNLICENSE` files. Read the **actual content** (not only the often-missing GitHub SPDX metadata) and emit the file path and SHA-256. Multiple license candidates require explicit scope review. Notices, vendored-code licenses, patent/trademark limits and proposed patch compatibility **still require human/source review**. -3. Only if a root license file was verified, read available root `CONTRIBUTING.md`, `AGENTS.md`, `CLAUDE.md` and emit bounded flags for DCO/CLA, issue, branch, testing/CI, before-Draft and before-merge mentions. These are textual hints, not an automatically cleared gate; check relevant `.github` files and first-party policies manually where present. -4. If `--topic` is supplied, inspect the first page of issues and open PRs for title overlaps; filter PR entries out of the issue result. This **cannot prove absence of a duplicate**. A full first page returns `PAGINATION_REQUIRED`, and title-only matching can miss synonyms, changed titles and closed PRs. +3. Only after verifying root license text, inspect eligible root policies plus `.github/` and `docs/` policy files and `.github/{ISSUE_TEMPLATE,PULL_REQUEST_TEMPLATE}/` text/YAML templates. Pin **all** file reads to the exact observed source commit SHA. Emit content digests and `{path,line,code,stage,excerpt}` evidence. Stage-specific `gates` summarize evidence and unresolved obligations; `NOT_CLEARED` never grants permission to implement, publish, mark ready or merge. This is a bounded enumeration, not proof that no policy exists elsewhere (including linked websites and repository discussions). +4. If `--topic` is supplied, traverse both **open and closed** issues and PRs using `state=all`, up to **30 pages of 100 records per endpoint** (checking the next page after an exactly full page). Search both titles and bodies for normalized topic-token overlaps (including partial similarities); filter PR entries from issue results. `INVENTORY_INCOMPLETE` explicitly records when the bounded limit is hit; a denied page fails closed as `INSUFFICIENT_EVIDENCE`. A complete inventory only establishes bounded lexical overlap, not the absence of semantic duplicates or a fix already merged under a different title. + +## Stage boundaries and machine reasons + +| Stage | Static evidence now gathered | Still required before actual stage transition | +| --- | --- | --- | +| `BEFORE_IMPLEMENTATION` | Source SHA, root license digest, issue/PR inventory, contributor issue/branch hints | Human or first-party-supported license compatibility decision, source-native defect and duplication check, any required issue assignment | +| `BEFORE_DRAFT` | Contributor DCO/CLA and Draft timing text | Genuine actor/authority/fork/branch verification, native RED→GREEN, diff/secret inspection, attestations and any explicit pre-Draft policy | +| `BEFORE_READY` | Ready-for-review and CI/test mentions | Required CI/reviews and author declaration at the applicable time; Draft may remain pending if policy permits | +| `BEFORE_MERGE` | Merge timing hints | Upstream maintainer, branch protection and review/CI gates; this mandate does not authorize merge | + +Every gate contains `status` and `reasons`; clear reason codes include `ROOT_LICENSE_NOT_FOUND`, `SOURCE_EVIDENCE_UNVERIFIED`, `LICENSE_COMPATIBILITY_REVIEW_REQUIRED`, `POTENTIAL_DUPLICATE_REVIEW_REQUIRED` and `DUPLICATE_INVENTORY_INCOMPLETE`. Hints do not determine whether the upstream actually *requires* DCO, CLA, issue assignment or branch syntax. Resolve these using the first-party context and the correct stage; no machine text-match can certify consent. | Machine status | Meaning | Next action | | --- | --- | --- | -| `LICENSE_REVIEW_REQUIRED` (exit 0) | Public source/ref and **nonempty root license text** verified | Human/operator must still establish applicable grant and compatibility before derivative work; then check notices, full contributor policy, overlap and exact Draft/merge timing | +| `LICENSE_REVIEW_REQUIRED` (exit 0) | Public source/ref and **nonempty root license text** verified; bounded policy/overlap evidence gathered | Human/operator must still establish applicable grant and compatibility **before derivative work**; then evaluate the stage-specific gates | | `LICENSE_BLOCKED` (exit 2) | No root license file observed | Do not make a derivative; investigate other license locations or obtain rights. **Not** a legal judgment that all use is forbidden | | `INSUFFICIENT_EVIDENCE` (exit 2) | API denied/rate-limited, malformed, missing required content, SHA unverifiable, etc. | Preserve source error, retry/inspect first-party evidence without treating it as license absence | @@ -29,7 +40,7 @@ The broader [candidate screening process](ASSESSMENT_CANDIDATE_BATCHES.md) owns ## Negative-test contract -The tests must prove that a metadata-only SPDX label cannot bypass absent root license text; 403/429/404 and malformed content never become eligibility; a 100-item page is not exhaustive; invalid repo/branch/topic input never reaches the network; CLI has no `--execute` or mutation mode. Run: +The tests must prove that a metadata-only SPDX label cannot bypass absent root license text; 403/429/404 and malformed content never become eligibility; exact-SHA policy evidence, nested `.github/` discovery and line numbers work; fully paginated open/closed issues and PRs are checked and page-budget exhaustion is reported; invalid repo/branch/topic input never reaches the network; CLI has no `--execute` or mutation mode. Run: ```sh python3 -m unittest discover -s tests -p 'test_candidate_intake_preflight.py' -v diff --git a/scripts/candidate_intake_preflight.py b/scripts/candidate_intake_preflight.py index 1c1ee02d..b700b306 100644 --- a/scripts/candidate_intake_preflight.py +++ b/scripts/candidate_intake_preflight.py @@ -11,6 +11,7 @@ import binascii import hashlib import json +import math import re import sys from urllib.parse import quote @@ -20,10 +21,29 @@ MAX_TEXT_BYTES = 256 * 1024 MAX_ITEMS = 100 +MAX_PAGES = 30 LICENSE_NAME = re.compile(r"^(licen[sc]e|copying|unlicense)(\.(md|txt|rst))?$", re.I) -POLICY_NAMES = ("CONTRIBUTING.md", "AGENTS.md", "CLAUDE.md") +POLICY_NAME = re.compile( + r"^(contributing|agents|claude|development|pull_request_template|codeowners)" + r"(\.(md|txt|rst))?$", re.I) +POLICY_FOLDERS = (".github", "docs") TOPIC = re.compile(r"[A-Za-z0-9][A-Za-z0-9 ._-]{2,79}\Z") +POLICY_PATTERNS = ( + ("DCO_SIGNOFF_MENTIONED", r"\bDCO\b|Signed-off-by", "BEFORE_DRAFT"), + ("CLA_MENTIONED", r"\bCLA\b|contributor license agreement", "BEFORE_DRAFT"), + ("ISSUE_WORKFLOW_MENTIONED", r"\bissue\b|\bassigned\b", "BEFORE_IMPLEMENTATION"), + ("BRANCH_NAMING_MENTIONED", r"\bbranch\b|\bbranches\b", "BEFORE_IMPLEMENTATION"), + ("TEST_OR_CI_GATE_MENTIONED", r"\bCI\b|\btests?\b|\bchecks?\b", "BEFORE_READY"), + ("DRAFT_PR_GATE_MENTIONED", + r"\bbefore (?:opening|submitting|creating) (?:a )?(?:draft )?(?:PR|pull request)\b", + "BEFORE_DRAFT"), + ("READY_PR_GATE_MENTIONED", r"\bready for review\b|\bmark (?:the )?PR ready\b", + "BEFORE_READY"), + ("MERGE_GATE_MENTIONED", r"\bbefore merg(?:e|ing)\b|\bprior to merg(?:e|ing)\b", + "BEFORE_MERGE"), +) + class IntakeError(ValueError): """A source fact was unverified; do not treat this as license absence.""" @@ -49,6 +69,8 @@ def _get(get, path, *, missing_ok=False, list_ok=False): def _contents_path(source, path, ref): + if any(part in ("", ".", "..") for part in path.split("/")): + raise IntakeError("Unsafe path in repository listing") encoded = "/".join(quote(part, safe="") for part in path.split("/")) return "/repos/" + source + "/contents/" + encoded + "?ref=" + quote(ref, safe="") @@ -72,7 +94,7 @@ def _file_text(get, source, path, ref): def _matches(items, topic): if topic is None: return [] - tokens = topic.casefold().split() + tokens = set(re.findall(r"[a-z0-9]+", topic.casefold())) matches = [] for item in items: if type(item) is not dict: @@ -80,10 +102,99 @@ def _matches(items, topic): title = item.get("title", "") if not isinstance(title, str): raise IntakeError("Malformed issue/PR title") - if all(token in title.casefold() for token in tokens): + body = item.get("body") or "" + if not isinstance(body, str): + raise IntakeError("Malformed issue/PR body") + title_tokens = set(re.findall(r"[a-z0-9]+", title.casefold())) + body_tokens = set(re.findall(r"[a-z0-9]+", body.casefold())) + title_hit = tokens <= title_tokens + body_hit = tokens <= body_tokens + matched = tokens & (title_tokens | body_tokens) + threshold = min(len(tokens), max(2, math.ceil(len(tokens) / 2))) + if len(matched) >= threshold: matches.append({"number": item.get("number"), "title": title[:200], - "url": item.get("html_url")}) - return matches[:20] + "url": item.get("html_url"), "state": item.get("state"), + "matched_in": ("title" if title_hit else "body" if body_hit + else "combined"), + "matched_tokens": sorted(matched)}) + return matches + + +def _inventory(get, source, kind): + """Traverse both open and closed records; bound work and disclose truncation.""" + collected = [] + for page in range(1, MAX_PAGES + 1): + path = (f"/repos/{source}/{kind}?state=all&per_page={MAX_ITEMS}&page={page}") + rows = _get(get, path, list_ok=True) + if len(rows) > MAX_ITEMS: + raise IntakeError("GitHub inventory page exceeds advertised page size") + collected.extend(rows) + if len(rows) < MAX_ITEMS: + return collected, True, page + return collected, False, MAX_PAGES + + +def _policy_paths(get, source, root, sha): + """Only bounded first-party paths; templates and nested instructions are not silently ignored.""" + seen = set() + for entry in root: + if entry.get("type") == "file" and POLICY_NAME.fullmatch(entry["name"]): + seen.add(entry["name"]) + for folder in POLICY_FOLDERS: + if not any(e.get("name") == folder and e.get("type") == "dir" for e in root): + continue + entries = _get(get, _contents_path(source, folder, sha), list_ok=True) + for entry in entries: + if (type(entry) is not dict or not isinstance(entry.get("name"), str) + or entry.get("type") not in ("file", "dir")): + raise IntakeError("Malformed contributor policy directory: " + folder) + if entry["type"] == "file" and POLICY_NAME.fullmatch(entry["name"]): + seen.add(folder + "/" + entry["name"]) + if folder == ".github" and entry["type"] == "dir" and entry["name"] in ( + "ISSUE_TEMPLATE", "PULL_REQUEST_TEMPLATE"): + templates = _get(get, _contents_path(source, folder + "/" + entry["name"], sha), + list_ok=True) + for child in templates: + if (type(child) is not dict or not isinstance(child.get("name"), str) + or child.get("type") not in ("file", "dir")): + raise IntakeError("Malformed contributor template directory") + if child["type"] == "file" and child["name"].lower().endswith( + (".md", ".txt", ".rst", ".yml", ".yaml")): + seen.add(folder + "/" + entry["name"] + "/" + child["name"]) + return sorted(seen) + + +def _policy_evidence(contents, path): + observations = [] + for line_number, line in enumerate(contents.splitlines(), 1): + for label, pattern, stage in POLICY_PATTERNS: + if re.search(pattern, line, re.I): + observations.append({"path": path, "line": line_number, "stage": stage, + "code": label, "excerpt": line.strip()[:240]}) + if len(observations) > 250: + raise IntakeError("Contributor policy evidence limit exceeded: " + path) + return observations + + +def _gates(result): + """Stages are evidence summaries, never substituted for real approvals.""" + evidence = result["contributor_policy"]["evidence"] + gates = {} + for stage in ("BEFORE_IMPLEMENTATION", "BEFORE_DRAFT", "BEFORE_READY", "BEFORE_MERGE"): + codes = sorted({e["code"] for e in evidence if e["stage"] == stage}) + gates[stage] = {"status": "NOT_CLEARED", "policy_hints": codes, + "reasons": ["FIRST_PARTY_POLICY_REVIEW_REQUIRED"]} + gates["BEFORE_IMPLEMENTATION"]["reasons"].extend( + ["LICENSE_COMPATIBILITY_REVIEW_REQUIRED", "NATIVE_DEFECT_NOT_VERIFIED"]) + gates["BEFORE_DRAFT"]["reasons"].extend( + ["NATIVE_RED_GREEN_REQUIRED", "FORK_ACTOR_AND_DIFF_REQUIRED", "DCO_CLA_IF_APPLICABLE"]) + gates["BEFORE_READY"]["reasons"].append("REQUIRED_REVIEW_AND_CHECKS_NOT_OBSERVED") + gates["BEFORE_MERGE"]["reasons"].append("UPSTREAM_MAINTAINER_MERGE_RESERVED") + if result["overlap"]["status"] == "INVENTORY_INCOMPLETE": + gates["BEFORE_IMPLEMENTATION"]["reasons"].append("DUPLICATE_INVENTORY_INCOMPLETE") + if result["overlap"]["issues"] or result["overlap"]["pull_requests"]: + gates["BEFORE_IMPLEMENTATION"]["reasons"].append("POTENTIAL_DUPLICATE_REVIEW_REQUIRED") + return gates def inspect_candidate(*, source, branch=None, topic=None, get=public_get): @@ -99,9 +210,11 @@ def inspect_candidate(*, source, branch=None, topic=None, get=public_get): "source": source, "source_branch": branch, "source_sha": None, "license": {"verdict": "LICENSE_UNRESOLVED", "spdx_metadata": None, "path": None, "sha256": None, "review_required": True}, - "contributor_policy": {"paths": [], "hints": [], "review_required": True}, + "contributor_policy": {"paths": [], "hints": [], "evidence": [], + "review_required": True}, "overlap": {"topic": topic, "issues": [], "pull_requests": [], "status": "NOT_SEARCHED"}, + "gates": {}, "reason_codes": ["LICENSE_NOT_VERIFIED"], "notes": ["First-party text may contain additional obligations; review is required.", "No POST, fork, patch, PR, license grant or legal sign-off is possible."], } @@ -124,7 +237,7 @@ def inspect_candidate(*, source, branch=None, topic=None, get=public_get): result["source_sha"] = sha root = _get(get, "/repos/" + source + "/contents?ref=" + - quote(observed_branch, safe=""), list_ok=True) + quote(sha, safe=""), list_ok=True) files = {} for item in root: if type(item) is not dict or not isinstance(item.get("name"), str): @@ -135,6 +248,9 @@ def inspect_candidate(*, source, branch=None, topic=None, get=public_get): if LICENSE_NAME.fullmatch(name)), key=lambda p: p.casefold()) if not license_paths: result["status"] = "LICENSE_BLOCKED" + result["reason_codes"] = ["ROOT_LICENSE_NOT_FOUND"] + result["gates"] = {"BEFORE_IMPLEMENTATION": { + "status": "BLOCKED", "reasons": ["ROOT_LICENSE_NOT_FOUND"]}} result["license"]["verdict"] = "LICENSE_NOT_FOUND_AT_ROOT" result["notes"].append( "No root LICENSE/COPYING/UNLICENSE observed; do not create a derivative. " @@ -143,7 +259,7 @@ def inspect_candidate(*, source, branch=None, topic=None, get=public_get): if len(license_paths) > 1: result["notes"].append("Multiple root license candidates: manual scope review required") license_path = license_paths[0] - license_text = _file_text(get, source, license_path, observed_branch) + license_text = _file_text(get, source, license_path, sha) if not license_text.strip(): raise IntakeError("Observed license file is empty") result["license"].update({ @@ -152,38 +268,30 @@ def inspect_candidate(*, source, branch=None, topic=None, get=public_get): "other_root_license_candidates": license_paths[1:], }) - for path in POLICY_NAMES: - actual = files.get(path.casefold()) - if not actual: - continue - contents = _file_text(get, source, actual, observed_branch) + for actual in _policy_paths(get, source, root, sha): + contents = _file_text(get, source, actual, sha) result["contributor_policy"]["paths"].append({ "path": actual, "sha256": hashlib.sha256(contents.encode()).hexdigest()}) - for label, pattern in ( - ("DCO_SIGNOFF_MENTIONED", r"\bDCO\b|Signed-off-by"), - ("CLA_MENTIONED", r"\bCLA\b|contributor license agreement"), - ("ISSUE_WORKFLOW_MENTIONED", r"\bissue\b"), - ("BRANCH_NAMING_MENTIONED", r"\bbranch\b|\bbranches\b"), - ("TEST_OR_CI_GATE_MENTIONED", r"\bCI\b|\btests?\b|\bchecks?\b"), - ("DRAFT_PR_GATE_MENTIONED", r"\bbefore (?:opening|submitting|creating) (?:a )?(?:draft )?(?:PR|pull request)\b"), - ("MERGE_GATE_MENTIONED", r"\bbefore merg(?:e|ing)\b|\bprior to merg(?:e|ing)\b"), - ): - if re.search(pattern, contents, re.I) and label not in result["contributor_policy"]["hints"]: - result["contributor_policy"]["hints"].append(label) + result["contributor_policy"]["evidence"].extend(_policy_evidence(contents, actual)) + result["contributor_policy"]["hints"] = sorted({ + evidence["code"] for evidence in result["contributor_policy"]["evidence"]}) if topic is not None: - path = "/repos/" + source - issues = _get(get, path + "/issues?state=all&per_page=100", list_ok=True) - prs = _get(get, path + "/pulls?state=open&per_page=100", list_ok=True) + issues, issues_complete, issues_pages = _inventory(get, source, "issues") + prs, prs_complete, prs_pages = _inventory(get, source, "pulls") result["overlap"].update({ "issues": _matches([item for item in issues if "pull_request" not in item], topic), "pull_requests": _matches(prs, topic), - "status": ("PAGINATION_REQUIRED" if len(issues) >= MAX_ITEMS or len(prs) >= MAX_ITEMS - else "TITLE_HEURISTIC_ONLY_NOT_PROOF_OF_ABSENCE"), + "issues_pages": issues_pages, "pull_requests_pages": prs_pages, + "issue_count_examined": len(issues), "pull_request_count_examined": len(prs), + "status": ("TITLE_BODY_HEURISTIC_ONLY_NOT_PROOF_OF_ABSENCE" + if issues_complete and prs_complete else "INVENTORY_INCOMPLETE"), }) - if len(issues) >= MAX_ITEMS or len(prs) >= MAX_ITEMS: - result["notes"].append("Open issue/PR inventory reached page limit; check further pages") + if not issues_complete or not prs_complete: + result["notes"].append("Issue/PR inventory exceeded bounded page budget") result["status"] = "LICENSE_REVIEW_REQUIRED" + result["reason_codes"] = ["LICENSE_COMPATIBILITY_REVIEW_REQUIRED"] + result["gates"] = _gates(result) return result @@ -198,7 +306,10 @@ def main(argv=None, *, get=public_get): topic=args.topic, get=get) except (IntakeError, ReadOnlyError, StageBlocked) as exc: result = {"status": "INSUFFICIENT_EVIDENCE", - "authorization": "READ_ONLY_NO_WRITES", "reason": str(exc)} + "authorization": "READ_ONLY_NO_WRITES", "reason": str(exc), + "reason_codes": ["SOURCE_EVIDENCE_UNVERIFIED"], + "gates": {"BEFORE_IMPLEMENTATION": { + "status": "BLOCKED", "reasons": ["SOURCE_EVIDENCE_UNVERIFIED"]}}} print(json.dumps(result, indent=2, sort_keys=True)) return 0 if result["status"] == "LICENSE_REVIEW_REQUIRED" else 2 diff --git a/tests/test_candidate_intake_preflight.py b/tests/test_candidate_intake_preflight.py index 4139b488..0883138a 100644 --- a/tests/test_candidate_intake_preflight.py +++ b/tests/test_candidate_intake_preflight.py @@ -31,17 +31,17 @@ def __init__(self): PREFIX: (200, {"full_name": SOURCE, "private": False, "archived": False, "disabled": False, "default_branch": "main", "license": None}), PREFIX + "/branches/main": (200, {"commit": {"sha": SHA}}), - PREFIX + "/contents?ref=main": (200, [ + PREFIX + "/contents?ref=" + SHA: (200, [ {"name": "LICENSE", "type": "file"}, {"name": "CONTRIBUTING.md", "type": "file"}, ]), - PREFIX + "/contents/LICENSE?ref=main": (200, content("MIT License\nPermission is hereby granted")), - PREFIX + "/contents/CONTRIBUTING.md?ref=main": ( + PREFIX + "/contents/LICENSE?ref=" + SHA: (200, content("MIT License\nPermission is hereby granted")), + PREFIX + "/contents/CONTRIBUTING.md?ref=" + SHA: ( 200, content("DCO Signed-off-by; file an issue before a PR. " "Use a branch, run CI checks before merging; " "before submitting a draft PR read the guidelines.")), - PREFIX + "/issues?state=all&per_page=100": (200, []), - PREFIX + "/pulls?state=open&per_page=100": (200, []), + PREFIX + "/issues?state=all&per_page=100&page=1": (200, []), + PREFIX + "/pulls?state=all&per_page=100&page=1": (200, []), } def __call__(self, path): @@ -72,22 +72,22 @@ def test_actual_license_text_required_even_when_spdx_metadata_missing(self): self.assertFalse(any("POST" in path for path in self.get.calls)) def test_no_root_license_blocks_before_policy_and_overlap(self): - self.get.responses[PREFIX + "/contents?ref=main"] = ( + self.get.responses[PREFIX + "/contents?ref=" + SHA] = ( 200, [{"name": "CONTRIBUTING.md", "type": "file"}]) result = self.inspect(topic="stale edit ledger") self.assertEqual(result["status"], "LICENSE_BLOCKED") self.assertEqual(result["license"]["verdict"], "LICENSE_NOT_FOUND_AT_ROOT") self.assertEqual(result["overlap"]["status"], "NOT_SEARCHED") - self.assertNotIn(PREFIX + "/contents/CONTRIBUTING.md?ref=main", self.get.calls) - self.assertNotIn(PREFIX + "/issues?state=all&per_page=100", self.get.calls) + self.assertNotIn(PREFIX + "/contents/CONTRIBUTING.md?ref=" + SHA, self.get.calls) + self.assertNotIn(PREFIX + "/issues?state=all&per_page=100&page=1", self.get.calls) def test_license_spdx_metadata_is_not_a_license_text_substitute(self): self.get.responses[PREFIX][1]["license"] = {"spdx_id": "MIT"} - self.get.responses[PREFIX + "/contents?ref=main"] = (200, []) + self.get.responses[PREFIX + "/contents?ref=" + SHA] = (200, []) self.assertEqual(self.inspect()["status"], "LICENSE_BLOCKED") def test_denial_rate_limit_and_missing_license_content_are_unverified(self): - path = PREFIX + "/contents/LICENSE?ref=main" + path = PREFIX + "/contents/LICENSE?ref=" + SHA for status in (403, 429, 404, 500): with self.subTest(status=status): self.get.responses[path] = (status, {}) @@ -95,7 +95,7 @@ def test_denial_rate_limit_and_missing_license_content_are_unverified(self): self.inspect() def test_invalid_base64_size_and_utf8_fail_closed(self): - path = PREFIX + "/contents/LICENSE?ref=main" + path = PREFIX + "/contents/LICENSE?ref=" + SHA bad = [ {"type": "file", "encoding": "base64", "content": "!!!", "size": 3}, {"type": "file", "encoding": "base64", "content": "YQ==", "size": 2}, @@ -109,7 +109,7 @@ def test_invalid_base64_size_and_utf8_fail_closed(self): self.inspect() def test_malformed_api_shape_sha_and_identity_fail_closed(self): - self.get.responses[PREFIX + "/contents?ref=main"] = (200, {}) + self.get.responses[PREFIX + "/contents?ref=" + SHA] = (200, {}) with self.assertRaises(IntakeError): self.inspect() self.get = FakeGet() @@ -123,25 +123,115 @@ def test_malformed_api_shape_sha_and_identity_fail_closed(self): self.inspect() def test_topic_overlap_is_hint_and_prs_are_not_issues(self): - self.get.responses[PREFIX + "/issues?state=all&per_page=100"] = (200, [ + self.get.responses[PREFIX + "/issues?state=all&per_page=100&page=1"] = (200, [ {"number": 7, "title": "Fix stale edit ledger", "html_url": "https://example/7"}, {"number": 8, "title": "Stale edit ledger", "pull_request": {}, "html_url": "https://example/8"}, ]) - self.get.responses[PREFIX + "/pulls?state=open&per_page=100"] = (200, [ + self.get.responses[PREFIX + "/pulls?state=all&per_page=100&page=1"] = (200, [ {"number": 8, "title": "Repair stale edit ledger", "html_url": "https://example/8"}, ]) result = self.inspect(topic="stale edit ledger") self.assertEqual(result["overlap"]["status"], - "TITLE_HEURISTIC_ONLY_NOT_PROOF_OF_ABSENCE") + "TITLE_BODY_HEURISTIC_ONLY_NOT_PROOF_OF_ABSENCE") self.assertEqual([i["number"] for i in result["overlap"]["issues"]], [7]) self.assertEqual([i["number"] for i in result["overlap"]["pull_requests"]], [8]) - def test_full_first_page_requires_pagination_and_never_clears_overlap(self): - self.get.responses[PREFIX + "/pulls?state=open&per_page=100"] = ( + def test_full_first_page_traverses_pagination_and_never_clears_overlap(self): + self.get.responses[PREFIX + "/pulls?state=all&per_page=100&page=1"] = ( 200, [{"number": i, "title": "Another unrelated task"} for i in range(100)]) + self.get.responses[PREFIX + "/pulls?state=all&per_page=100&page=2"] = (200, []) result = self.inspect(topic="stale edit ledger") - self.assertEqual(result["overlap"]["status"], "PAGINATION_REQUIRED") + self.assertEqual(result["overlap"]["status"], + "TITLE_BODY_HEURISTIC_ONLY_NOT_PROOF_OF_ABSENCE") + self.assertEqual(result["overlap"]["pull_requests_pages"], 2) + self.assertIn(PREFIX + "/pulls?state=all&per_page=100&page=2", self.get.calls) + + def test_nested_github_policy_file_and_line_evidence(self): + self.get.responses[PREFIX + "/contents?ref=" + SHA][1].append( + {"name": ".github", "type": "dir"}) + self.get.responses[PREFIX + "/contents/.github?ref=" + SHA] = (200, [ + {"name": "CONTRIBUTING.md", "type": "file"}, + {"name": "PULL_REQUEST_TEMPLATE", "type": "dir"}, + ]) + self.get.responses[PREFIX + "/contents/.github/CONTRIBUTING.md?ref=" + SHA] = ( + 200, content("Review contributor guidelines\nAssign an issue before opening a pull request\n" + "Use a signed-off commit before submitting a draft PR")) + self.get.responses[PREFIX + "/contents/.github/PULL_REQUEST_TEMPLATE?ref=" + SHA] = ( + 200, [{"name": "bugfix.md", "type": "file"}]) + self.get.responses[PREFIX + "/contents/.github/PULL_REQUEST_TEMPLATE/bugfix.md?ref=" + SHA] = ( + 200, content("Before merging, run CI tests")) + result = self.inspect() + paths = [x["path"] for x in result["contributor_policy"]["paths"]] + self.assertIn(".github/CONTRIBUTING.md", paths) + self.assertIn(".github/PULL_REQUEST_TEMPLATE/bugfix.md", paths) + self.assertIn({"path": ".github/CONTRIBUTING.md", "line": 2, + "stage": "BEFORE_IMPLEMENTATION", "code": "ISSUE_WORKFLOW_MENTIONED", + "excerpt": "Assign an issue before opening a pull request"}, + result["contributor_policy"]["evidence"]) + self.assertEqual(result["gates"]["BEFORE_DRAFT"]["status"], "NOT_CLEARED") + self.assertIn("UPSTREAM_MAINTAINER_MERGE_RESERVED", + result["gates"]["BEFORE_MERGE"]["reasons"]) + + def test_closed_issue_and_pr_overlap_across_pages_including_body(self): + first_page = [{"number": i, "title": "Unrelated", "body": None, + "state": "closed"} for i in range(100)] + self.get.responses[PREFIX + "/issues?state=all&per_page=100&page=1"] = ( + 200, first_page) + self.get.responses[PREFIX + "/issues?state=all&per_page=100&page=2"] = ( + 200, [{"number": 101, "title": "Something else", + "body": "Stale edit ledger causes lost updates", "state": "closed"}]) + self.get.responses[PREFIX + "/pulls?state=all&per_page=100&page=1"] = ( + 200, [{"number": 102, "title": "Fix stale edit ledger", "state": "closed"}]) + result = self.inspect(topic="stale edit ledger") + self.assertEqual(result["overlap"]["status"], + "TITLE_BODY_HEURISTIC_ONLY_NOT_PROOF_OF_ABSENCE") + self.assertEqual(result["overlap"]["issues"][0]["state"], "closed") + self.assertEqual(result["overlap"]["issues"][0]["matched_in"], "body") + self.assertEqual(result["overlap"]["pull_requests"][0]["state"], "closed") + self.assertIn("POTENTIAL_DUPLICATE_REVIEW_REQUIRED", + result["gates"]["BEFORE_IMPLEMENTATION"]["reasons"]) + + def test_potential_duplicate_token_separator_and_partial_topic(self): + self.get.responses[PREFIX + "/pulls?state=all&per_page=100&page=1"] = ( + 200, [{"number": 1, "title": "preflight batch_edit before changing files", + "body": "Avoid partial file writes", "state": "open"}]) + result = self.inspect(topic="batch edit partial mutation") + self.assertEqual(result["overlap"]["pull_requests"][0]["number"], 1) + self.assertIn("POTENTIAL_DUPLICATE_REVIEW_REQUIRED", + result["gates"]["BEFORE_IMPLEMENTATION"]["reasons"]) + + def test_page_budget_discloses_incomplete_inventory(self): + for page in range(1, 31): + self.get.responses[PREFIX + f"/issues?state=all&per_page=100&page={page}"] = ( + 200, [{"number": (page - 1) * 100 + i, "title": "other"} + for i in range(100)]) + result = self.inspect(topic="stale edit ledger") + self.assertEqual(result["overlap"]["status"], "INVENTORY_INCOMPLETE") + self.assertEqual(result["overlap"]["issue_count_examined"], 3000) + self.assertIn("DUPLICATE_INVENTORY_INCOMPLETE", + result["gates"]["BEFORE_IMPLEMENTATION"]["reasons"]) + + def test_pagination_denial_never_reports_complete(self): + self.get.responses[PREFIX + "/pulls?state=all&per_page=100&page=1"] = ( + 200, [{"title": "other"} for _ in range(100)]) + self.get.responses[PREFIX + "/pulls?state=all&per_page=100&page=2"] = (403, {}) + with self.assertRaises(IntakeError): + self.inspect(topic="stale edit ledger") + + def test_sha_pins_all_content_reads(self): + self.inspect() + content_reads = [path for path in self.get.calls if "/contents" in path] + self.assertTrue(content_reads) + self.assertTrue(all(path.endswith("?ref=" + SHA) for path in content_reads)) + + def test_malformed_nested_directory_is_insufficient(self): + self.get.responses[PREFIX + "/contents?ref=" + SHA][1].append( + {"name": ".github", "type": "dir"}) + self.get.responses[PREFIX + "/contents/.github?ref=" + SHA] = ( + 200, [{"name": "CONTRIBUTING.md", "type": "symlink"}]) + with self.assertRaises(IntakeError): + self.inspect() def test_invalid_inputs_rejected_before_network(self): for data in ({"source": "outside/../../secret"}, @@ -155,7 +245,7 @@ def test_cli_json_status_and_nonzero_for_blocked_or_failed(self): with patch("sys.stdout", new_callable=StringIO) as output: self.assertEqual(main(["--source", SOURCE], get=self.get), 0) self.assertEqual(json.loads(output.getvalue())["status"], "LICENSE_REVIEW_REQUIRED") - self.get.responses[PREFIX + "/contents?ref=main"] = (200, []) + self.get.responses[PREFIX + "/contents?ref=" + SHA] = (200, []) with patch("sys.stdout", new_callable=StringIO) as output: self.assertEqual(main(["--source", SOURCE], get=self.get), 2) self.assertEqual(json.loads(output.getvalue())["status"], "LICENSE_BLOCKED") diff --git a/tests/test_corrective_publication_queue.py b/tests/test_corrective_publication_queue.py index 892dd629..cda7bd6c 100644 --- a/tests/test_corrective_publication_queue.py +++ b/tests/test_corrective_publication_queue.py @@ -24,16 +24,17 @@ def setUpClass(cls): def test_exact_finite_snapshot_and_native_only_mode(self): board = queue.report(self.data) self.assertEqual(board["authorized_count"], 34) - self.assertEqual(board["next_candidate"], "oblivion-agent-tool-loop") - self.assertEqual(board["counts"], {"QUEUED": 34}) + self.assertEqual(board["next_candidate"], "raven-stale-edit-ledger") + self.assertEqual(board["counts"], {"QUEUED": 33, "SUBMITTED": 1}) self.assertEqual(board["test_mode"], "NATIVE_SCRIPT_ONLY_NO_LLM_AGENTS") self.assertTrue(board["no_external_writes_performed_by_this_command"]) def test_blocked_case_moves_to_next_with_source_history_unchanged(self): ledger = copy.deepcopy(self.data) - ledger["cases"][0]["publication"] = "BLOCKED" - ledger["cases"][0]["reason"] = "The current upstream source already fixed the defect." - self.assertEqual(queue.report(ledger)["next_candidate"], "raven-stale-edit-ledger") + ledger["cases"][1]["publication"] = "BLOCKED" + ledger["cases"][1]["reason"] = "The current upstream source already fixed the defect." + self.assertEqual(queue.report(ledger)["next_candidate"], + "politik-transaction-denial-return") def test_reject_out_of_scope_reordering_and_unsupported_stage(self): transforms = ( @@ -41,7 +42,7 @@ def test_reject_out_of_scope_reordering_and_unsupported_stage(self): lambda d: d["cases"].reverse(), lambda d: d["cases"][0].update(id="citadel-native-claim-exclusivity"), lambda d: d["cases"][0].update(publication="ACTIVE"), - lambda d: d["cases"][0].update(publication="SUBMITTED"), + lambda d: d["cases"][1].update(publication="SUBMITTED"), lambda d: d["cases"][0].update(pr_url="https://github.com/not-a-pr"), lambda d: d.update(candidate_snapshot_sha="0" * 40), ) From 4d59916073a6c03c480f78f58d8b06be8c998f60 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:52:57 +0300 Subject: [PATCH 11/14] chore(intake): keep publication receipts owned by PR #110 --- data/corrective-publication/2026-10-23-01.json | 2 +- tests/test_corrective_publication_queue.py | 13 ++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/data/corrective-publication/2026-10-23-01.json b/data/corrective-publication/2026-10-23-01.json index 5e41952b..2bece195 100644 --- a/data/corrective-publication/2026-10-23-01.json +++ b/data/corrective-publication/2026-10-23-01.json @@ -8,7 +8,7 @@ "authorized_count": 34, "scope": "Exact native-tested Corrective AWAITING_EXTERNAL cases from batches 01–10 only; external Draft PR creation in public opensiro-contributions direct forks, subject to verified actor and upstream gates; no external merge.", "cases": [ - {"id": "oblivion-agent-tool-loop", "publication": "SUBMITTED", "pr_url": "https://github.com/Rohith-s-hub/Oblivion-agent/pull/1", "actor": "xLagerFeuer", "base_sha": "7c57fd23ddd9abb5a2795788364f5dcdf3ec87cb", "head_sha": "1967f1df19f80cd34d4a4b70756ae1589e075c8c", "native_test_receipt": "pilots/oblivion-batch-edit/scripted_atomicity_replay.py — native RED at 7c57fd2 and GREEN on public opensiro/fix-batch-edit-preflight, both re-run 2026-10-23; positive controls PASS", "external_state": "OPEN_DRAFT", "readback_date": "2026-10-23"}, + {"id": "oblivion-agent-tool-loop", "publication": "QUEUED"}, {"id": "raven-stale-edit-ledger", "publication": "QUEUED"}, {"id": "politik-transaction-denial-return", "publication": "QUEUED"}, {"id": "join-the-team-bootstrap-validation", "publication": "QUEUED"}, diff --git a/tests/test_corrective_publication_queue.py b/tests/test_corrective_publication_queue.py index cda7bd6c..892dd629 100644 --- a/tests/test_corrective_publication_queue.py +++ b/tests/test_corrective_publication_queue.py @@ -24,17 +24,16 @@ def setUpClass(cls): def test_exact_finite_snapshot_and_native_only_mode(self): board = queue.report(self.data) self.assertEqual(board["authorized_count"], 34) - self.assertEqual(board["next_candidate"], "raven-stale-edit-ledger") - self.assertEqual(board["counts"], {"QUEUED": 33, "SUBMITTED": 1}) + self.assertEqual(board["next_candidate"], "oblivion-agent-tool-loop") + self.assertEqual(board["counts"], {"QUEUED": 34}) self.assertEqual(board["test_mode"], "NATIVE_SCRIPT_ONLY_NO_LLM_AGENTS") self.assertTrue(board["no_external_writes_performed_by_this_command"]) def test_blocked_case_moves_to_next_with_source_history_unchanged(self): ledger = copy.deepcopy(self.data) - ledger["cases"][1]["publication"] = "BLOCKED" - ledger["cases"][1]["reason"] = "The current upstream source already fixed the defect." - self.assertEqual(queue.report(ledger)["next_candidate"], - "politik-transaction-denial-return") + ledger["cases"][0]["publication"] = "BLOCKED" + ledger["cases"][0]["reason"] = "The current upstream source already fixed the defect." + self.assertEqual(queue.report(ledger)["next_candidate"], "raven-stale-edit-ledger") def test_reject_out_of_scope_reordering_and_unsupported_stage(self): transforms = ( @@ -42,7 +41,7 @@ def test_reject_out_of_scope_reordering_and_unsupported_stage(self): lambda d: d["cases"].reverse(), lambda d: d["cases"][0].update(id="citadel-native-claim-exclusivity"), lambda d: d["cases"][0].update(publication="ACTIVE"), - lambda d: d["cases"][1].update(publication="SUBMITTED"), + lambda d: d["cases"][0].update(publication="SUBMITTED"), lambda d: d["cases"][0].update(pr_url="https://github.com/not-a-pr"), lambda d: d.update(candidate_snapshot_sha="0" * 40), ) From e93bc5ee64ff521015f58678887448f350b2c341 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:26:12 +0300 Subject: [PATCH 12/14] fix(intake): recognize and pin dual-license root files --- scripts/candidate_intake_preflight.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/scripts/candidate_intake_preflight.py b/scripts/candidate_intake_preflight.py index b700b306..a01f4580 100644 --- a/scripts/candidate_intake_preflight.py +++ b/scripts/candidate_intake_preflight.py @@ -22,7 +22,10 @@ MAX_TEXT_BYTES = 256 * 1024 MAX_ITEMS = 100 MAX_PAGES = 30 -LICENSE_NAME = re.compile(r"^(licen[sc]e|copying|unlicense)(\.(md|txt|rst))?$", re.I) +LICENSE_NAME = re.compile( + r"^(licen[sc]e(?:[-_.](?:mit|apache|bsd|isc|mpl|gpl|lgpl|agpl)" + r"(?:[-_.]?[0-9]+(?:\.[0-9]+)?)?)?|copying|unlicense)" + r"(?:\.(md|txt|rst))?$", re.I) POLICY_NAME = re.compile( r"^(contributing|agents|claude|development|pull_request_template|codeowners)" r"(\.(md|txt|rst))?$", re.I) @@ -258,13 +261,20 @@ def inspect_candidate(*, source, branch=None, topic=None, get=public_get): return result if len(license_paths) > 1: result["notes"].append("Multiple root license candidates: manual scope review required") - license_path = license_paths[0] - license_text = _file_text(get, source, license_path, sha) - if not license_text.strip(): - raise IntakeError("Observed license file is empty") + license_files = [] + for license_path in license_paths: + license_text = _file_text(get, source, license_path, sha) + if not license_text.strip(): + raise IntakeError("Observed license file is empty: " + license_path) + license_files.append({ + "path": license_path, + "sha256": hashlib.sha256(license_text.encode()).hexdigest(), + }) result["license"].update({ - "verdict": "LICENSE_TEXT_PRESENT_REVIEW_REQUIRED", "path": license_path, - "sha256": hashlib.sha256(license_text.encode()).hexdigest(), + "verdict": "LICENSE_TEXT_PRESENT_REVIEW_REQUIRED", + "path": license_files[0]["path"], + "sha256": license_files[0]["sha256"], + "files": license_files, "other_root_license_candidates": license_paths[1:], }) From 3739c9fd5baf2b6308fefce74545e090fa645639 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:26:13 +0300 Subject: [PATCH 13/14] test(intake): cover dual-license source receipts --- tests/test_candidate_intake_preflight.py | 29 ++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/test_candidate_intake_preflight.py b/tests/test_candidate_intake_preflight.py index 0883138a..3f2dcbc1 100644 --- a/tests/test_candidate_intake_preflight.py +++ b/tests/test_candidate_intake_preflight.py @@ -71,6 +71,35 @@ def test_actual_license_text_required_even_when_spdx_metadata_missing(self): self.assertIn("DCO_SIGNOFF_MENTIONED", result["contributor_policy"]["hints"]) self.assertFalse(any("POST" in path for path in self.get.calls)) + def test_named_dual_license_files_are_both_read_at_pinned_source(self): + self.get.responses[PREFIX + "/contents?ref=" + SHA] = (200, [ + {"name": "LICENSE-APACHE", "type": "file"}, + {"name": "LICENSE-MIT", "type": "file"}, + ]) + self.get.responses[PREFIX + "/contents/LICENSE-APACHE?ref=" + SHA] = ( + 200, content("Apache License Version 2.0")) + self.get.responses[PREFIX + "/contents/LICENSE-MIT?ref=" + SHA] = ( + 200, content("MIT License permission is hereby granted")) + result = self.inspect() + self.assertEqual(result["status"], "LICENSE_REVIEW_REQUIRED") + self.assertEqual([file["path"] for file in result["license"]["files"]], + ["LICENSE-APACHE", "LICENSE-MIT"]) + self.assertEqual(result["license"]["path"], "LICENSE-APACHE") + self.assertTrue(all(len(file["sha256"]) == 64 for file in result["license"]["files"])) + self.assertIn("LICENSE-MIT", result["license"]["other_root_license_candidates"]) + self.assertIn(PREFIX + "/contents/LICENSE-APACHE?ref=" + SHA, self.get.calls) + self.assertIn(PREFIX + "/contents/LICENSE-MIT?ref=" + SHA, self.get.calls) + + def test_missing_second_license_text_fails_closed(self): + self.get.responses[PREFIX + "/contents?ref=" + SHA] = (200, [ + {"name": "LICENSE-APACHE", "type": "file"}, + {"name": "LICENSE-MIT", "type": "file"}, + ]) + self.get.responses[PREFIX + "/contents/LICENSE-APACHE?ref=" + SHA] = ( + 200, content("Apache License")) + with self.assertRaises(IntakeError): + self.inspect() + def test_no_root_license_blocks_before_policy_and_overlap(self): self.get.responses[PREFIX + "/contents?ref=" + SHA] = ( 200, [{"name": "CONTRIBUTING.md", "type": "file"}]) From 7928c0bc1202ac5f93ad01f61f176afb10f0ec68 Mon Sep 17 00:00:00 2001 From: alexruidan <41616537+xLagerFeuer@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:26:15 +0300 Subject: [PATCH 14/14] docs(intake): explain complete dual-license evidence --- docs/CANDIDATE_INTAKE_PREFLIGHT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CANDIDATE_INTAKE_PREFLIGHT.md b/docs/CANDIDATE_INTAKE_PREFLIGHT.md index 0dc7e75e..1152f8ad 100644 --- a/docs/CANDIDATE_INTAKE_PREFLIGHT.md +++ b/docs/CANDIDATE_INTAKE_PREFLIGHT.md @@ -13,7 +13,7 @@ The script makes only unauthenticated, repository-scoped GitHub REST `GET` reque ## Evidence and interpretation 1. Check the public repository identity, default/selected branch and exact source SHA. -2. Enumerate root `LICENSE`/`LICENCE`/`COPYING`/`UNLICENSE` files. Read the **actual content** (not only the often-missing GitHub SPDX metadata) and emit the file path and SHA-256. Multiple license candidates require explicit scope review. Notices, vendored-code licenses, patent/trademark limits and proposed patch compatibility **still require human/source review**. +2. Enumerate root `LICENSE`/`LICENCE`/`COPYING`/`UNLICENSE` files, including named `LICENSE-MIT`, `LICENSE-APACHE`, and comparable common SPDX-family filename variants. Read the **actual content of every matched root license file** (not only the often-missing GitHub SPDX metadata) and emit each path and SHA-256 under `license.files`. If any matched file is missing, malformed, or empty, fail closed. Multiple license candidates require explicit scope review. Notices, vendored-code licenses, patent/trademark limits and proposed patch compatibility **still require human/source review**. 3. Only after verifying root license text, inspect eligible root policies plus `.github/` and `docs/` policy files and `.github/{ISSUE_TEMPLATE,PULL_REQUEST_TEMPLATE}/` text/YAML templates. Pin **all** file reads to the exact observed source commit SHA. Emit content digests and `{path,line,code,stage,excerpt}` evidence. Stage-specific `gates` summarize evidence and unresolved obligations; `NOT_CLEARED` never grants permission to implement, publish, mark ready or merge. This is a bounded enumeration, not proof that no policy exists elsewhere (including linked websites and repository discussions). 4. If `--topic` is supplied, traverse both **open and closed** issues and PRs using `state=all`, up to **30 pages of 100 records per endpoint** (checking the next page after an exactly full page). Search both titles and bodies for normalized topic-token overlaps (including partial similarities); filter PR entries from issue results. `INVENTORY_INCOMPLETE` explicitly records when the bounded limit is hit; a denied page fails closed as `INSUFFICIENT_EVIDENCE`. A complete inventory only establishes bounded lexical overlap, not the absence of semantic duplicates or a fix already merged under a different title.