diff --git a/docs/ASSESSMENT_CANDIDATE_BATCHES.md b/docs/ASSESSMENT_CANDIDATE_BATCHES.md index c07c0eea..e1df1883 100644 --- a/docs/ASSESSMENT_CANDIDATE_BATCHES.md +++ b/docs/ASSESSMENT_CANDIDATE_BATCHES.md @@ -4,6 +4,8 @@ **Read-only all-lane status:** [Harness Status](../HARNESS_STATUS.md) groups work as harness → intervention → external PR, preserving these batch manifests as historical technical records. `python3 scripts/harness_status.py --filter actionable` is an inventory view, **not** an authorized publication scheduler or fresh source/PR verification. See the [source hierarchy](HARNESS_STATUS_MODEL.md). +**Machine-assisted license-first intake:** use the [read-only candidate preflight](CANDIDATE_INTAKE_PREFLIGHT.md) at the beginning of a 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. The preflight does not replace the five-source batch CAS, native fit checks or external-stage grants. + **Continuous working-fork link:** after each admitted technical batch or updated handoff, regenerate the [source → fork intent registry](../data/contribution-workspaces/registry.json) with `python3 scripts/contribution_workspaces.py sync` in the same internal @@ -60,7 +62,7 @@ Within this expressly selected **#56 experiment** and its explicitly chosen `ups 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. For prospective `ASSESSMENT_DERIVED`, commit or otherwise timestamp the predicted native weakness, expected benefit and null/falsifier **before** investigating the target's fresh code/issues; a later VSM explanation is not derived-origin evidence. 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 derivatives:** run the [read-only preflight](CANDIDATE_INTAKE_PREFLIGHT.md) and independently inspect the actual current upstream `LICENSE`/NOTICE text, source SHA, redistribution compatibility and contributor requirements **before preparing a derivative patch or public fork**. Record the source link and `LICENSE_ELIGIBLE` / `LICENSE_BLOCKED` / `LICENSE_UNRESOLVED` decision separately; the preflight's `LICENSE_REVIEW_REQUIRED` is not clearance. If the license grant cannot be established, do not copy, modify or publish upstream code; record `BLOCKED_EVIDENCE`. Then independently inspect current source, issue/PR overlap and native need, and record the four fit gates (`need`, `mechanism`, `counterfactual`, `scope`) with dated primary-source links. Preserve the prospective hypothesis chronology from step 2. 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, require relevant **native deterministic scripts** against pinned genuine product code, matched baseline/after and controls. For prospective strict-derived cases, dispatch them to a distinct CI/runner and verify its first-party source/test pins, run URL, commands, logs and controls; when unavailable record `BLOCKED_INDEPENDENT_EXECUTION`, not a chatbot-executed benefit claim. **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. diff --git a/docs/ASSESSMENT_TO_IMPROVEMENT.md b/docs/ASSESSMENT_TO_IMPROVEMENT.md index 1ae0a503..42967c91 100644 --- a/docs/ASSESSMENT_TO_IMPROVEMENT.md +++ b/docs/ASSESSMENT_TO_IMPROVEMENT.md @@ -76,7 +76,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):** *before fresh target-code/issue inspection*, preserve the dated hypothesis checkpoint described above. 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 before derivative code or fork preparation**; missing GitHub license metadata alone is inconclusive, but no actual applicable grant means no public derivative fork/patch. The read-only intake preflight supplies evidence, not automatic license clearance. 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. **Independent native scripted test and repair:** have the separate deterministic runner demonstrate the pre-change failure/shortfall against actual product source through reproducible scripts; implement one scoped upstream-native change; have the runner re-run the matched workload against changed code and native regressions, and inspect its receipts. 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. diff --git a/docs/CANDIDATE_INTAKE_PREFLIGHT.md b/docs/CANDIDATE_INTAKE_PREFLIGHT.md new file mode 100644 index 00000000..1152f8ad --- /dev/null +++ b/docs/CANDIDATE_INTAKE_PREFLIGHT.md @@ -0,0 +1,51 @@ +# 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, 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. + +## 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; 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 | + +**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; 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 +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. diff --git a/docs/CORRECTIVE_PR_PUBLICATION.md b/docs/CORRECTIVE_PR_PUBLICATION.md index d22720d3..865b066f 100644 --- a/docs/CORRECTIVE_PR_PUBLICATION.md +++ b/docs/CORRECTIVE_PR_PUBLICATION.md @@ -12,11 +12,13 @@ > Local preparation and authorized working-fork synchronization stay separate > from publishing. See [continuous working-fork pipeline](CONTINUOUS_WORKING_FORK_PIPELINE.md). -> **2026-10-25 finite-cohort reconciliation:** The [reviewable working ledger in PR #129](https://github.com/opensiro/upstream/pull/129) records **13 SUBMITTED / 21 BLOCKED / 0 QUEUED** from exactly 34 fixed cases. All queue entries are terminal under the present mandate; **21 BLOCKED cases are not published fixes or third-party rejection decisions**. Reopening requires new evidence/permission as appropriate, not an automatic next cohort. The [operational-readiness review](../reports/2026-10-25-upstream-operational-readiness.md) distinguishes a real finite publication experiment from an inactive general executor. Until #129 merges, `main` retains an older ledger; do not confuse their counts. +> **2026-10-25 finite-cohort reconciliation:** The [ledger integrated in PR #129](https://github.com/opensiro/upstream/pull/129) recorded **13 SUBMITTED / 21 BLOCKED / 0 QUEUED** from exactly 34 fixed cases. All queue entries were terminal under that mandate; **21 BLOCKED cases are not published fixes or third-party rejection decisions**. Reopening requires new evidence/permission as appropriate, not an automatic next cohort. The [operational-readiness review](../reports/2026-10-25-upstream-operational-readiness.md) distinguishes a real finite publication experiment from an inactive general executor. This is a dated checkpoint; read the current ledger on `main` for live state. + +**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 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 historical 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 PRs without returning for individual routine approvals**. On **2026-10-24**, the owner corrected the publication-state preference: fully checked, non-blocked Corrective PRs should be sent directly as **Ready for review (`draft: false`)**; use Draft only when a concrete unresolved prerequisite makes that state honest. This amendment changes PR review state, not candidate scope or merge authority. Publishing a PR remains distinct from upstream acceptance and merge. +Historically, this superseded the prior **human-per-PR publication choice only within the enumerated Corrective packet set**. Under that finite mandate, an assistant with legitimate contributor credentials could create public organization forks, branches, fixes/tests and external PRs without separate routine per-PR approval. On **2026-10-24**, the owner corrected the publication-state preference to **Ready for review (`draft: false`)** for fully checked, non-blocked cases, with Draft reserved for a real prerequisite. **The 2026-11-09 prospective human-per-PR publication gate above now controls any new submission.** Neither policy authorizes external merge. ## Finite source and allowed actions @@ -28,12 +30,29 @@ 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. Preserve the target's own PR template and append the [AI-assisted contribution disclosure](AI_ASSISTED_PR_DISCLOSURE.md). Send as **Ready for review** if native gates and source policy allow review now. Reserve **Draft** for a documented unfinished requirement; do not imply Ready is merge approval or all CI is green. 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). **In the same reviewable change**, register that exact PR URL in the hourly [maintenance watchlist](../data/pr-maintenance/targets.json); preserve its historic checkpoint and avoid duplicates. This is an explicit audited watchlist, not a search-fed list. 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 upstream-native need and scope → first-party native RED/GREEN → authentic actor/permission/fork/branch checks → Ready-for-review PR (justified Draft only if blocked) → readback → durable result → next case**. This is engineering source validation, **not** the deprecated Product-native fit metric. 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. diff --git a/pilots/CATALOG.md b/pilots/CATALOG.md index 1ff1a249..1aa712b4 100644 --- a/pilots/CATALOG.md +++ b/pilots/CATALOG.md @@ -7,7 +7,7 @@ fitness, fork existence, PR publication, maintainer acceptance, or VSM grades. See [experiment contract](EXPERIMENT_CONTRACT.md) and [working-fork pipeline](../docs/CONTINUOUS_WORKING_FORK_PIPELINE.md). -**Coverage:** 68 indexed pilot directories · 186 files. The frozen baseline protects 66 historical directories and their files; 2 directories were added later. +**Coverage:** 68 indexed pilot directories · 187 files. The frozen baseline protects 66 historical directories and their files; 2 directories were added later. Each row links its preferred entry file. Read the actual receipt and governing batch/PR before attributing positive results or current status. @@ -43,7 +43,7 @@ batch/PR before attributing positive results or current status. | `forgedock` | [Open](forgedock/CONTRIBUTION_HANDOFF.md) | patch: 1, handoff: 1 | | `friday-s2` | [Open](friday-s2/CONTRIBUTION_HANDOFF.md) | patch: 2, handoff: 1, receipt: 1 | | `harness2` | [Open](harness2/CONTRIBUTION_HANDOFF.md) | patch: 1, handoff: 1 | -| `harnessdesk-1772` | [Open](harnessdesk-1772/README.md) | patch: 2, handoff: 2, receipt: 1, native_code: 1, fixture_or_recipe: 4, other: 4 | +| `harnessdesk-1772` | [Open](harnessdesk-1772/README.md) | patch: 2, handoff: 2, receipt: 1, native_code: 1, fixture_or_recipe: 4, other: 5 | | `henrik-agent-harness` | [Open](henrik-agent-harness/CONTRIBUTION_HANDOFF.md) | patch: 1, handoff: 1 | | `histh-s2` | [Open](histh-s2/CONTRIBUTION_HANDOFF.md) | patch: 2, handoff: 1, receipt: 1 | | `join-the-team` | [Open](join-the-team/CONTRIBUTION_HANDOFF.md) | patch: 1, handoff: 1 | diff --git a/pilots/catalog.json b/pilots/catalog.json index 68dba4cb..a7aff436 100644 --- a/pilots/catalog.json +++ b/pilots/catalog.json @@ -5,7 +5,7 @@ "generated_from": "pilots/ direct subdirectories and their preserved files", "counts": { "pilot_directories": 68, - "artifact_files": 186, + "artifact_files": 187, "historical_directories": 66, "new_directories": 2, "by_kind": { @@ -424,7 +424,7 @@ "receipt": 1, "native_code": 1, "fixture_or_recipe": 4, - "other": 4 + "other": 5 }, "files": [ "ASSESSMENT_LINKAGE_2026-10-20.md", @@ -433,6 +433,7 @@ "PREPARE_SHARED_CURRENT_20261020.md", "PREPARE_V2_HANDOFF.md", "README.md", + "UNPUBLISHED_PR_PACKAGE_20261020.md", "prepare-v2-20261020-24aa8d7.json", "prepare-v2-20261020-81d5e34-shared.json", "prepare-v2-handoff.json", diff --git a/scripts/candidate_intake_preflight.py b/scripts/candidate_intake_preflight.py new file mode 100644 index 00000000..a01f4580 --- /dev/null +++ b/scripts/candidate_intake_preflight.py @@ -0,0 +1,328 @@ +#!/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 math +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 +MAX_PAGES = 30 +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) +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.""" + + +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): + 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="") + + +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 = set(re.findall(r"[a-z0-9]+", topic.casefold())) + 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") + 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"), "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): + """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": [], "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."], + } + 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(sha, 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["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. " + "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_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_files[0]["path"], + "sha256": license_files[0]["sha256"], + "files": license_files, + "other_root_license_candidates": license_paths[1:], + }) + + 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()}) + 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: + 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), + "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 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 + + +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), + "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 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_candidate_intake_preflight.py b/tests/test_candidate_intake_preflight.py new file mode 100644 index 00000000..3f2dcbc1 --- /dev/null +++ b/tests/test_candidate_intake_preflight.py @@ -0,0 +1,296 @@ +"""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=" + SHA: (200, [ + {"name": "LICENSE", "type": "file"}, + {"name": "CONTRIBUTING.md", "type": "file"}, + ]), + 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&page=1": (200, []), + PREFIX + "/pulls?state=all&per_page=100&page=1": (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_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"}]) + 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=" + 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=" + 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=" + SHA + 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=" + SHA + 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=" + SHA] = (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&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=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_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_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"], + "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"}, + {"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=" + 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") + 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()