From a7ad3177d0232f5cfaa1c4cc118abb76d20c7528 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:36:40 +0800 Subject: [PATCH 1/3] Inspect issue and pull request labels against recorded decisions Agent-assisted-by: Codex / gpt-6.2-astra effort=max (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- .github/workflows/ci-nightly.yml | 10 + docs/agent-collaboration.md | 2 + docs/guides/issue-label-audit.md | 26 ++ tests/repository/test_audit_issue_labels.py | 334 ++++++++++++++++ tools/audit_issue_labels.py | 409 ++++++++++++++++++++ tools/label_audit_evidence.py | 203 ++++++++++ tools/label_cutover.py | 198 ++++++++++ 7 files changed, 1182 insertions(+) create mode 100644 docs/guides/issue-label-audit.md create mode 100644 tests/repository/test_audit_issue_labels.py create mode 100644 tools/audit_issue_labels.py create mode 100644 tools/label_audit_evidence.py create mode 100644 tools/label_cutover.py diff --git a/.github/workflows/ci-nightly.yml b/.github/workflows/ci-nightly.yml index 1003ef50e..6b1e6dce2 100644 --- a/.github/workflows/ci-nightly.yml +++ b/.github/workflows/ci-nightly.yml @@ -29,6 +29,7 @@ jobs: permissions: contents: read issues: read + pull-requests: read steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 @@ -49,3 +50,12 @@ jobs: gh api --paginate "repos/$GITHUB_REPOSITORY/labels" \ --jq '.[] | {name, description}' > "$RUNNER_TEMP/labels.jsonl" python tools/check_labels.py "$RUNNER_TEMP/labels.jsonl" + - name: Inspect recently updated Issues and PRs + env: + GH_TOKEN: ${{ github.token }} + run: python tools/audit_issue_labels.py --recent-hours 48 > "$RUNNER_TEMP/issue-label-audit.json" + - uses: actions/upload-artifact@v4 + with: + name: issue-label-audit + path: ${{ runner.temp }}/issue-label-audit.json + if-no-files-found: error diff --git a/docs/agent-collaboration.md b/docs/agent-collaboration.md index e26259ac6..84d650385 100644 --- a/docs/agent-collaboration.md +++ b/docs/agent-collaboration.md @@ -414,6 +414,8 @@ Change labels by editing `labels.json` in a PR first, then applying that change repository. The nightly `safety-net` job reports drift between the repository labels and `labels.json`, and any label that an Issue template or `tools/skill_eval_*_config.json` references but `labels.json` lacks. No workflow writes labels. +The [per-object inspection and hourly handoff](guides/issue-label-audit.md) +explain how to read the nightly findings and verify an authorized writer's cutover. [`external-labels.json`](../.github/external-labels.json) names the labels that an outside GitHub App owns and applies, with the app that owns each one. Those names are exempt from the diff --git a/docs/guides/issue-label-audit.md b/docs/guides/issue-label-audit.md new file mode 100644 index 000000000..80a15f90a --- /dev/null +++ b/docs/guides/issue-label-audit.md @@ -0,0 +1,26 @@ +# Inspect Issue and PR labels + +The nightly `safety-net` job publishes an `issue-label-audit` JSON artifact for Issues and PRs updated in the preceding 48 hours. Consecutive windows overlap. Count distinct object and event IDs when combining runs. [Collaboration rules](../agent-collaboration.md#labels) · [Workflow](../../.github/workflows/ci-nightly.yml) + +## Read a report + +Run `python tools/audit_issue_labels.py 335 658` with an authenticated GitHub CLI that can read InferRSI Issues and PRs. Use `--recent-hours 48` instead of object numbers to reproduce the nightly selection. Each entry identifies the object, observed labels, PR head where applicable, suggested additions/removals and evidence links. A pending finding identifies missing evidence. Findings can be nonempty on a successful run. An unavailable API returns an error. The existing `tools/check_labels.py` independently fails on label definition or reference drift. + +The optional `--evidence decisions.json` supplies a human reading of public records, keyed by object number. A proof has `url` and an exact `quote` from its body. For a parent Issue comment, add `via`, the URL of a record on the inspected object containing the parent link. The tool fetches that comment and verifies its quotation. Review the meaning and ownership before acting. Useful keys include: + +- `open_question`, `scope_decision`, `whole_scope_acceptance`, `deferral`, `label_delegation`, `delivery`, `blocker` and `disposition`. For a suggested missing kind, pair `suggested_kind` with `kind_choice`. Pair a list of `suggested_areas` with an `area_scope` quote covering the named responsibilities. Conflicting acceptance and deferral evidence leaves the decision pending. +- `closer_login`, `closer_role` (`owner` or `delegate`), `closer_identity`, `owner_authority`, `goal_decision` and `closure_summary` identify who closed this open cycle and on what grounds. A delegated close also needs `closure_delegation`. Interpret an explicit statement of capacity. One shared login may represent several actors. +- `standing_reviews` entries cite native `activity`. The activity or a reviewer-authored `role` proof identifies a standing reviewer. A formal PR review supplies its commit. For a comment supply `revision`, and for Issues also supply `issue_revision` identifying the current state. An `invitation` proof quotes the @ mention, request to review and revision in a prior record. Missing evidence is pending. The uninvited count requires an explicit positive record from the standing reviewer. + +## Reconstruct PR kinds at cutover + +Pass `--cutover-pr N` with the merged **inspection** PR number. Its GitHub `merged` timeline event supplies T, the event ID and the matching merge commit SHA. On each PR, `replayed` shows pre-T changes and `at_cutover` the reconstructed kinds. `new_additions` counts each distinct addition strictly after T, including re-additions on older PRs. A same-second boundary with unknown order or incomplete history stays pending. [Accepted cutover](https://github.com/InferMatrixLab/InferRSI/issues/658#issuecomment-7155913512) + +An original `--snapshot snapshot.json` has an exact zoned `at` timestamp and an `objects` map from PR number to its observed `kind:*` list. An empty list is a recorded absence. Supply only original per-object evidence. The November 24 snapshot published 186 Issues and 323 PRs, with 176 PRs carrying kind. Its precise timestamp and object-label rows were unavailable at implementation. The separately measured Shanghai 30-day creation cohort contained 181 Issues and 319 PRs, including 184 with kind. The report preserves both published counts. A newly created post-T PR can be replayed from its creation. [Audit windows](https://github.com/InferMatrixLab/InferRSI/issues/658) + +## Hand off the hourly classifier + +1. When this inspector is ready to merge, the operator of “分类标签小时维护” pauses **every** remote label operation, invalidates all previously planned requests and retry generations, drains in-flight requests and records time, generation and zero queue/retry/in-flight counts on the PR. Keep the writer paused across T. [Owner and operator decisions](https://github.com/InferMatrixLab/InferRSI/issues/658#issuecomment-7155986059) +2. After the merge, record the actual GitHub merged event. With the writer still paused, run one complete read-only cycle that inspects a pre-existing open PR with no kind. Record the PR URL and head, opening state and labels, run ID/time, zero remote label requests for the whole run, and a separate GitHub readback. If no PR qualifies, record that and keep the writer paused. [Operator clarification](https://github.com/InferMatrixLab/InferRSI/issues/658#issuecomment-7154855391) +3. To check the operator's recorded fields and their timing, run `python tools/audit_issue_labels.py --cutover-pr N --handoff operator.json P`, where P was inspected. The `freeze` object records `at`, `url`, `scope: all-label-writes`, `invalidated_generation`, `queued`, `retries` and `in_flight`. The `trial` object records `at`, `url`, `run_id`, `pr_url`, `head`, `existing_open_pr`, `inspected`, `remote_label_requests`, `kinds_before`, `kinds_after` and a separate `readback_url`. Verify the linked operator logs, counters and independent GitHub readback before resuming. The CLI validates the supplied fields and timestamps. +4. Resume with a fresh generation and recheck every plan at send and retry time. Automatic additions are limited to documented areas with clear evidence. Issue kind and proposed status are suggestions. For a delegated status change verify the owner's recorded decision, an existing proposal and the applicable authority. Keep missing/partial acceptance and PR kind/status out of the writer. Preserve the body, record actual changes in the task history and use the report for routine findings. [Write authority](../agent-collaboration.md#labels) diff --git a/tests/repository/test_audit_issue_labels.py b/tests/repository/test_audit_issue_labels.py new file mode 100644 index 000000000..d7e07f56e --- /dev/null +++ b/tests/repository/test_audit_issue_labels.py @@ -0,0 +1,334 @@ +import json +from copy import deepcopy + +import pytest + +from tools import audit_issue_labels as audit +from tools.label_cutover import handoff_gaps, hourly_area_plan_current, merge_event, replay_pr_kind + +BASE = "https://github.com/InferMatrixLab/InferRSI" +HEAD = "a" * 40 +ORIGINAL = "2026-11-24T12:00:00Z" +T = "2026-11-25T04:00:00Z" +MERGE = {"at": T, "event_id": 45, "sha": HEAD, "url": f"{BASE}/pull/20#event-45"} +BEFORE = "2026-11-25T03:59:59Z" +AFTER = "2026-11-25T04:00:01Z" +LATER = "2026-11-25T04:00:02Z" +KIND = "kind:task" + + +def obj(labels=(), pr=True): + item = { + "number": 7, + "html_url": f"{BASE}/{'pull' if pr else 'issues'}/7", + "state": "open", + "created_at": "2026-11-07T00:00:00Z", + "updated_at": LATER, + "labels": [{"name": v} for v in labels], + "body": "", + } + if pr: + item.update(pull_request={}, head_sha=HEAD) + return item + + +def change(n, op, at, label=KIND): + return {"id": n, "event": op, "created_at": at, "label": {"name": label}} + + +def replay(labels, changes, original, **overrides): + item = obj(labels) + item.update(overrides) + return replay_pr_kind(item, changes, {"at": ORIGINAL, "objects": {"7": original}}, MERGE) + + +def test_cutover_is_native_event_with_matching_sha(): + event = {"event": "merged", "id": 45, "created_at": T, "commit_id": HEAD} + assert merge_event([event], HEAD, f"{BASE}/pull/20") == MERGE + for events, sha in (([], HEAD), ([event, event], HEAD), ([event], "b" * 40)): + with pytest.raises(ValueError): + merge_event(events, sha, f"{BASE}/pull/20") + + +def test_unchanged_old_kind_stays_in_baseline(): + report = replay([KIND], [], [KIND]) + assert report == {"at_cutover": [KIND], "replayed": [], "new_additions": [], "pending": []} + + +def test_pre_cutover_changes_are_replayed_only_in_baseline(): + report = replay([], [change(1, "unlabeled", BEFORE)], [KIND]) + assert report["at_cutover"] == [] + assert [e["id"] for e in report["replayed"]] == [1] + assert not report["new_additions"] and not report["pending"] + + +def test_post_cutover_remove_and_readd_on_an_old_pr_count_once(): + addition = change(3, "labeled", LATER) + report = replay([KIND], [change(2, "unlabeled", AFTER), addition, deepcopy(addition)], [KIND]) + assert report["at_cutover"] == [KIND] + assert [e["id"] for e in report["new_additions"]] == [3] + assert not report["pending"] + + +@pytest.mark.parametrize( + "history", + [ + [change(1, "labeled", T)], + [change(1, "labeled", ORIGINAL)], + [change(1, "labeled", AFTER), change(1, "unlabeled", AFTER)], + [change(1, "unlabeled", AFTER)], + [{"event": "labeled", "label": {"name": KIND}}], + ], +) +def test_ambiguous_or_incomplete_history_never_counted(history): + result = replay([KIND], history, []) + assert result["pending"] and result["at_cutover"] is None and not result["new_additions"] + + +def test_missing_original_fields_and_new_object_are_distinct(): + for snapshot in ({}, {"at": ORIGINAL, "objects": {}}): + assert replay_pr_kind(obj([KIND]), [], snapshot, MERGE)["pending"] + new = obj([KIND]) + new["created_at"] = AFTER + row = replay_pr_kind(new, [change(9, "labeled", AFTER)], {}, MERGE) + assert not row["pending"] and [e["id"] for e in row["new_additions"]] == [9] + + +def comment(number, body, who="owner", when=BEFORE): + return { + "event": "commented", + "id": number, + "html_url": f"{BASE}/issues/7#issuecomment-{number}", + "body": body, + "user": {"login": who}, + "created_at": when, + } + + +def proof(c): + return {"url": c["html_url"], "quote": c["body"]} + + +def codes(row): + return {f["code"] for f in row["findings"]} + + +def test_shared_login_is_not_delegation(): + issue = obj(["area:process", KIND], pr=False) + issue.update(state="closed", closed_by={"login": "owner"}) + c = comment(13, "I am acting on behalf of the issue owner. The owner accepted this scope.") + closed = {"id": 19, "event": "closed", "actor": {"login": "owner"}, "created_at": AFTER} + evidence = { + k: proof(c) + for k in ("closer_identity", "owner_authority", "closure_summary", "goal_decision") + } + evidence.update(closer_login="owner", closer_role="delegate") + row = audit.audit_object(issue, [c, closed], evidence, {}, None) + assert row["closure"]["role"] == "delegate" and "closure_delegation" in codes(row) + evidence["closer_role"] = "owner" + assert "closure-identity" in codes(audit.audit_object(issue, [c, closed], evidence, {}, None)) + c["body"] = "I am the issue owner and personally accept and close this scope." + owner = { + k: proof(c) + for k in ("closer_identity", "owner_authority", "closure_summary", "goal_decision") + } + owner.update(closer_login="owner", closer_role="owner") + assert not codes(audit.audit_object(issue, [c, closed], owner, {}, None)) + reopened = {"event": "reopened", "id": 2, "created_at": T} + assert "goal_decision" in codes( + audit.audit_object(issue, [c, reopened, closed], owner, {}, None) + ) + + +def test_frozen_writer_rejects_old_queue_and_retry_before_each_remote_call(): + pr_labels = {"area:process"} + remote_calls = [] + + def send(plan, writer): + if hourly_area_plan_current(plan, writer): + remote_calls.append(plan["label"]) + pr_labels.add(plan["label"]) + + def readback(): + return sorted(pr_labels) + + before = readback() + stale_kind = {"operation": "add", "label": KIND, "generation": "old", "area_evidence": "diff"} + stale_area = {**stale_kind, "label": "area:harness"} + for writer in ( + {"mode": "frozen", "generation": "old"}, + {"mode": "trial", "generation": "new"}, + {"mode": "resumed", "generation": "new"}, + ): + for stale in (stale_kind, stale_area): + send(stale, writer) # Previously queued. + send(stale, writer) # Previously scheduled retry. + assert remote_calls == [] and readback() == before + writer = {"mode": "resumed", "generation": "new"} + send({**stale_kind, "generation": "new"}, writer) + send({**stale_area, "generation": "new", "area_evidence": ""}, writer) + assert remote_calls == [] + send({**stale_area, "generation": "new"}, writer) + assert remote_calls == ["area:harness"] and readback() == ["area:harness", "area:process"] + + +def test_operator_receipts_require_separate_post_merge_readback_and_zero_writes(): + freeze = { + "at": BEFORE, + "url": f"{BASE}/pull/20#issuecomment-100", + "scope": "all-label-writes", + "invalidated_generation": "old", + "queued": 0, + "retries": 0, + "in_flight": 0, + } + trial = { + "at": AFTER, + "url": f"{BASE}/pull/20#issuecomment-101", + "run_id": "hourly-678", + "pr_url": f"{BASE}/pull/7", + "head": HEAD, + "inspected": True, + "existing_open_pr": True, + "readback_url": f"{BASE}/pull/20#issuecomment-102", + "remote_label_requests": 0, + "kinds_before": [], + "kinds_after": [], + } + assert handoff_gaps({"freeze": freeze, "trial": trial}, MERGE) == [] + for k, v in ( + ("remote_label_requests", 1), + ("kinds_after", [KIND]), + ("at", T), + ("readback_url", ""), + ("readback_url", trial["url"]), + ("run_id", ""), + ("inspected", False), + ): + assert handoff_gaps({"freeze": freeze, "trial": {**trial, k: v}}, MERGE) + assert handoff_gaps({"freeze": {**freeze, "retries": 1}, "trial": trial}, MERGE) + + +def test_standing_activity_needs_affirmative_account_and_revision_evidence(): + pr = obj(["area:process"]) + action = comment( + 9, "I am a standing reviewer. I started this review without an invitation.", "bot", LATER + ) + action.update(event="reviewed", commit_id=HEAD) + assert audit.audit_object(pr, [action], {}, {}, None)["uninvited_standing_reviews"] == 1 + action["body"] = "I am a standing reviewer. I reviewed this." + mention = comment(8, f"@bot please review {HEAD}") + evidence = { + "standing_reviews": [{"activity": action["html_url"], "invitation": proof(mention)}] + } + assert not codes(audit.audit_object(pr, [mention, action], evidence, {}, None)) + mention["body"] = "@bot please review an unrelated commit" + assert "review-invitation" in codes( + audit.audit_object(pr, [mention, action], evidence, {}, None) + ) + action["body"] = "I reviewed this as a human." + assert not codes(audit.audit_object(pr, [action], {}, {}, None)) + action.update( + body="I am a standing reviewer. I started this review without an invitation.", + commit_id="b" * 40, + ) + assert audit.audit_object(pr, [action], {}, {}, None)["uninvited_standing_reviews"] == 0 + + +def test_status_decision_is_cited_and_suggestions_are_separate_from_authority(): + issue = obj(["area:process", KIND, "status:proposed"], pr=False) + issue["body"] = ( + "**Current state:** delivered\n**Decision needed:** none\n**Next action:** verify" + ) + decision = comment(10, "I accept the entire scope.") + evidence = {"whole_scope_acceptance": proof(decision), "scope_decision": proof(decision)} + row = audit.audit_object(issue, [decision], evidence, {}, None) + assert {"scope-update", "delivery", "progress-decision", "label-authority"} <= codes(row) + assert next(r for r in row["findings"] if r["code"] == "scope-update")["add"] == [ + "status:accepted" + ] + wrong = { + **evidence, + "whole_scope_acceptance": {"url": decision["html_url"], "quote": "another decision"}, + } + assert "scope-update" not in codes(audit.audit_object(issue, [decision], wrong, {}, None)) + issue["state"] = "closed" + pending = audit.audit_object(issue, [decision], {}, {}, None) + f = next(x for x in pending["findings"] if x["code"] == "closed-proposed") + assert f["state"] == "pending" and not f["remove"] + + +def test_empty_fields_quotes_and_code_examples_do_not_set_progress(): + fields = audit.progress_fields( + "> **Current state:** done\n~~~\n**Current state:** active\n~~~\n" + "\n**Current state:** \n**Next action:** ask" + ) + assert fields["word"] == "" and "decision needed" not in fields + + +def test_quoted_review_and_conflicting_decisions_are_not_positive_findings(): + activity = comment( + 9, "I am a standing reviewer.\n> I started this review without an invitation.", "bot" + ) + activity.update(event="reviewed", commit_id=HEAD) + assert audit.audit_object(obj(), [activity], {}, {}, None)["uninvited_standing_reviews"] == 0 + activity["body"] = ( + "~~~\n\nI started this review without an invitation.\n~~~" + ) + assert "review-invitation" not in codes(audit.audit_object(obj(), [activity], {}, {}, None)) + accepted, deferred = comment(10, "I accept the scope."), comment(11, "I defer this.") + issue = obj([KIND, "status:proposed"], pr=False) + data = {"whole_scope_acceptance": proof(accepted), "deferral": proof(deferred)} + items = audit.audit_object(issue, [accepted, deferred], data, {}, None)["findings"] + update = [item for item in items if item["code"] == "scope-update"] + assert len(update) == 1 and update[0]["state"] == "pending" and not update[0]["add"] + + +def test_a_reopened_issue_cannot_borrow_prior_close_identity_and_event(): + issue = obj([KIND], pr=False) + issue["body"] = "**Current state:** done" + c = comment(13, "I am the issue owner and close this scope.") + close = {"id": 18, "event": "closed", "actor": {"login": "owner"}, "created_at": BEFORE} + reopen = {"id": 19, "event": "reopened", "created_at": AFTER} + data = {"closer_login": "owner", "closer_role": "owner", "closer_identity": proof(c)} + row = audit.audit_object(issue, [c, close, reopen], data, {}, None) + assert row["closure"]["role"] is None and row["closure"]["close_event"] is None + assert "closure-identity" in codes(row) + + +def test_cited_multiple_areas_only_suggest_missing_known_labels(): + item = obj(["area:process"]) + reason = comment(10, "The delivery covers both engineering process and the execution harness.") + data = {"area_scope": proof(reason), "suggested_areas": ["area:process", "area:harness"]} + findings = audit.audit_object(item, [reason], data, {}, None)["findings"] + assert ( + len(findings) == 1 and findings[0]["add"] == ["area:harness"] and not findings[0]["remove"] + ) + + +def test_live_reader_uses_get_only_paginates_and_returns_findings_as_data(monkeypatch, capsys): + calls = [] + item = obj([], pr=False) + + def run(command, **kwargs): + assert command[:4] == ["gh", "api", "--method", "GET"] + path = command[-1] + calls.append(path) + if "/timeline?" in path: + value = [] + elif "/issues?" in path: + value = [item] * 100 if path.endswith("page=1") else [] + else: + value = item + + class Response: + returncode = 0 + stdout = json.dumps(value) + + return Response() + + monkeypatch.setattr(audit.subprocess, "run", run) + assert audit.main(["--recent-hours", "48"]) == 0 + report = json.loads(capsys.readouterr().out) + assert len(report["objects"]) == 1 and "issue-kind" in codes(report["objects"][0]) + assert any("page=2" in p for p in calls) diff --git a/tools/audit_issue_labels.py b/tools/audit_issue_labels.py new file mode 100644 index 000000000..22652f606 --- /dev/null +++ b/tools/audit_issue_labels.py @@ -0,0 +1,409 @@ +"""Inspect selected Issues and PRs without changing GitHub. See --help.""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +from datetime import datetime, timedelta, timezone +from pathlib import Path +from urllib.parse import urlencode + +if __package__: + from .label_audit_evidence import CAPACITY, ISSUE_COMMENT, REPO, Evidence, actor, own_text + from .label_cutover import AREAS, LABELS, handoff_gaps, instant, merge_event, replay_pr_kind +else: # Direct invocation: python tools/audit_issue_labels.py + from label_audit_evidence import CAPACITY, ISSUE_COMMENT, REPO, Evidence, actor, own_text + from label_cutover import AREAS, LABELS, handoff_gaps, instant, merge_event, replay_pr_kind + +PROGRESS_KINDS = {"kind:task", "kind:rfc", "kind:acceptance", "kind:tracking"} +ISSUE_KINDS = {row["name"] for row in LABELS if row["group"] == "kind"} +# First rule introducing single Issue kind: PR #299's merged timeline event. +KIND_RULE_AT = "2026-11-01T13:13:59Z" +WORDS = {"proposed", "active", "blocked", "delivered", "done"} +FIELD = re.compile( + r"^[ \t]*(?:[-*] )?(?:\*\*)?(Current state|Decision needed|Next action):" + r"(?:\*\*)?[ \t]*(.*?)[ \t]*$", + re.I | re.M, +) + + +def get_json(path: str) -> dict | list: + command = ["gh", "api", "--method", "GET", path] + response = subprocess.run(command, capture_output=True, encoding="utf-8", timeout=90) + if response.returncode: + raise ValueError(f"GitHub GET {path}: {response.stderr.strip()}") + return json.loads(response.stdout) + + +def paginated(path: str) -> list[dict]: + rows = [] + page = 1 + while True: + separator = "&" if "?" in path else "?" + batch = get_json(f"{path}{separator}per_page=100&page={page}") + rows.extend(batch) + if len(batch) < 100: + return rows + page += 1 + + +def progress_fields(body: str) -> dict: + fields = {} + for match in FIELD.finditer(own_text(body)): + fields.setdefault(match[1].lower(), match[2]) + state = fields.get("current state", "").lstrip("`*").split() + fields["word"] = re.split(r"[^a-z]", state[0].lower())[0] if state else "" + return fields + + +def event_link(obj: dict, event: dict) -> str: + return event.get("html_url") or f"{obj['html_url']}#event-{event['id']}" + + +def audit_object( + obj: dict, + events: list[dict], + evidence: dict, + snapshot: dict, + cutover: dict | None, + linked: dict | None = None, +) -> dict: + """Evidence is a human interpretation of linked public records, never a write grant.""" + pr = "pull_request" in obj + url = obj["html_url"] + labels = sorted(v["name"] for v in obj["labels"]) + status = [v for v in labels if v.startswith("status:")] + kinds = [v for v in labels if v.startswith("kind:")] + result = { + "number": obj["number"], + "url": url, + "type": "PR" if pr else "Issue", + "labels": labels, + "findings": [], + "uninvited_standing_reviews": 0, + } + if pr: + result["head"] = obj["head_sha"] + + def finding(code, detail, *, pending=False, add=(), remove=(), sources=()): + result["findings"].append( + { + "code": code, + "state": "pending" if pending else "advisory", + "detail": detail, + "add": list(add), + "remove": list(remove), + "sources": list(sources) or [url], + } + ) + + proof = Evidence(obj, events, evidence, linked or {}) + source = proof.field + for code, detail, pending, sources in proof.standing_reviews(pr): + finding(code, detail, pending=pending, sources=sources) + if code == "uninvited-standing-review": + result["uninvited_standing_reviews"] += 1 + + area_scope = source("area_scope") + suggested = evidence.get("suggested_areas") + valid_areas = isinstance(suggested, list) and all( + isinstance(v, str) and v in AREAS for v in suggested + ) + if area_scope and valid_areas and suggested: + additions = sorted(set(suggested) - set(labels)) + if additions: + finding( + "area", + "Cited responsibilities touched by this object.", + add=additions, + sources=[area_scope], + ) + elif not any(v.startswith("area:") for v in labels): + finding( + "area", "Identify the changed responsibilities from the scope or diff.", pending=True + ) + if pr: + if status: + finding("pr-status", "Use native PR progress.", remove=status) + if cutover: + report = replay_pr_kind(obj, events, snapshot, cutover) + result["kind_history"] = report + for gap in report["pending"]: + finding("pr-kind-history", gap, pending=True, sources=[url, cutover["url"]]) + for addition in report["new_additions"]: + finding( + "new-pr-kind", + f"Post-cutover addition of {addition['label']}.", + remove=[addition["label"]] if addition["label"] in kinds else [], + sources=[addition["url"], cutover["url"]], + ) + elif kinds: + finding( + "pr-kind", + "Historical kind observed; cutover evidence needed to date it.", + pending=True, + ) + return result + + if not kinds: + selected = evidence.get("suggested_kind") + if source("kind_choice") and selected in ISSUE_KINDS: + finding( + "issue-kind", + "Creator's or delegate's cited purpose.", + add=[selected], + sources=[source("kind_choice")], + ) + else: + finding("issue-kind", "Creator or delegate selects the Issue's purpose.", pending=True) + if len(kinds) > 1 and (len(kinds) > 2 or instant(obj["created_at"]) >= instant(KIND_RULE_AT)): + finding( + "issue-kind-count", + "Resolve overlapping Issue kinds against the creator's purpose.", + pending=True, + ) + if len(status) > 1: + finding("status-conflict", "Multiple scope decisions are displayed together.") + proposed = "status:proposed" in status + fields = progress_fields(obj.get("body") or "") + word = fields["word"] + closed = obj["state"] == "closed" + if not closed and set(kinds) & PROGRESS_KINDS: + if word not in WORDS or not fields.get("decision needed") or not fields.get("next action"): + finding("progress-block", "Complete the three-line progress block.", pending=True) + if word == "proposed" and not status: + if source("open_question"): + finding( + "open-decision", + "Named outstanding decision and owner.", + add=["status:proposed"], + sources=[source("open_question")], + ) + else: + finding( + "open-decision", + "Verify the open question and its decision owner.", + pending=True, + ) + if "status:deferred" in status and word in WORDS - {"proposed"}: + finding("deferred-progress", "A deferred decision uses proposed in the first line.") + if word in {"active", "delivered"} and not source("scope_decision"): + finding("accepted-scope", "Link the owner's accepted scope.", pending=True) + if word in {"active", "delivered", "done"} and proposed: + finding("progress-decision", "The progress word and undecided scope conflict.") + if word == "delivered" and not source("delivery"): + finding( + "delivery", + "Verify the agreed delivery artifacts and applicable merges.", + pending=True, + ) + if word == "blocked" and not source("blocker"): + finding("blocker", "Verify the obstacle and who can unblock it.", pending=True) + + if proposed and closed: + disposition = source("disposition") + finding( + "closed-proposed", + "Check the recorded disposition and separate write authority.", + pending=not disposition, + remove=["status:proposed"] if disposition else [], + sources=[url, disposition] if disposition else [url], + ) + if proposed and not closed: + decisions = [ + (source(key), target) + for key, target in ( + ("whole_scope_acceptance", "status:accepted"), + ("deferral", "status:deferred"), + ) + if source(key) + ] + if len(decisions) > 1: + finding( + "scope-update", + "Resolve which owner decision governs this scope.", + pending=True, + sources=[link for link, _ in decisions], + ) + elif decisions: + link, target = decisions[0] + finding( + "scope-update", + "Recorded owner decision; verify write delegation separately.", + add=[target], + remove=["status:proposed"], + sources=[link], + ) + if not source("label_delegation"): + finding( + "label-authority", "Verify the executor's applicable delegation.", pending=True + ) + if any(v in status for v in ("status:accepted", "status:deferred")) and not source( + "scope_decision" + ): + finding("status-decision", "Identify the applicable owner's decision.", pending=True) + if closed or word == "done": + cycles = [e for e in events if e.get("event") in {"reopened", "closed"}] + last_open = next((e for e in reversed(cycles) if e["event"] == "reopened"), None) + last_close = cycles[-1] if closed and cycles and cycles[-1]["event"] == "closed" else None + + def current_cycle(record): + return not last_open or bool( + record.get("created_at") + and instant(record["created_at"]) > instant(last_open["created_at"]) + ) + + links = [] + required = ["closure_summary", "goal_decision", "owner_authority"] + role = evidence.get("closer_role") + close_actor = actor(last_close or {}) + identity = proof.proof(evidence.get("closer_identity")) + if ( + role not in {"owner", "delegate"} + or not close_actor + or (evidence.get("closer_login") or "").lower() != close_actor + or not identity + or not current_cycle(identity[1]) + or identity[2] not in own_text(identity[1].get("body") or "") + or actor(identity[1]) != close_actor + or not CAPACITY[role].search(identity[2]) + or (role == "owner" and CAPACITY["delegate"].search(identity[2])) + ): + role = None + if role not in {"owner", "delegate"}: + finding( + "closure-identity", + "Establish whether the actor was the owner or a delegate; " + "a shared GitHub login is insufficient.", + pending=True, + ) + if role == "delegate": + required.append("closure_delegation") + for key in required: + link = source(key) + record = proof.local.get(link) or proof.linked.get(link) or {} + if link and not current_cycle(record): + link = None + if not link: + finding(key, f"Verify {key.replace('_', ' ')} for this open cycle.", pending=True) + else: + links.append(link) + result["closure"] = { + "role": role, + "sources": links, + "close_event": event_link(obj, last_close) if last_close else None, + } + return result + + +def read_file(path: Path | None) -> dict: + return json.loads(path.read_text(encoding="utf-8")) if path else {} + + +def linked_comments(root, evidence, obj, events): + """Read explicitly cited parent comments only when a local record references them.""" + local = {e["html_url"]: e for e in events if e.get("html_url")} + local[obj["html_url"]] = obj + refs = list(evidence.values()) + for item in evidence.get("standing_reviews", []): + if isinstance(item, dict): + refs.extend(item.values()) + linked = {} + for item in refs: + if not isinstance(item, dict) or not isinstance(item.get("url"), str): + continue + url = item["url"] + match = ISSUE_COMMENT.fullmatch(url) + via = local.get(item.get("via")) or {} + if match and url not in local and url not in linked and url in (via.get("body") or ""): + record = get_json(f"{root}/issues/comments/{match[1]}") + if record.get("html_url") == url: + linked[url] = record + return linked + + +def inspect(root, number, evidence, snapshot, cutover): + path = f"{root}/issues/{number}" + obj = get_json(path) + if "pull_request" in obj: + obj["head_sha"] = get_json(f"{root}/pulls/{number}")["head"]["sha"] + events = paginated(f"{path}/timeline") + linked = linked_comments(root, evidence, obj, events) + after = get_json(path) + if any(obj[k] != after[k] for k in ("updated_at", "body", "state", "labels")) or ( + "head_sha" in obj and get_json(f"{root}/pulls/{number}")["head"]["sha"] != obj["head_sha"] + ): + return { + "number": number, + "url": obj["html_url"], + "pending": "Changed during inspection; retry.", + } + return audit_object(obj, events, evidence, snapshot, cutover, linked) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("numbers", type=int, nargs="*", help="Issue or PR numbers") + parser.add_argument( + "--recent-hours", type=int, help="inspect Issues and PRs updated in this window" + ) + parser.add_argument( + "--cutover-pr", type=int, help="the merged inspector PR; reads its actual merge event" + ) + parser.add_argument("--snapshot", type=Path, help="original timestamp and per-object kind rows") + parser.add_argument( + "--evidence", type=Path, help="reviewed public evidence keyed by object number" + ) + parser.add_argument("--handoff", type=Path, help="operator's freeze and dry-run record") + args = parser.parse_args(argv) + if bool(args.numbers) == (args.recent_hours is not None): + parser.error("supply object numbers or one recent time window") + if args.recent_hours is not None and args.recent_hours <= 0: + parser.error("--recent-hours must be positive") + if any(n <= 0 for n in args.numbers) or (args.cutover_pr is not None and args.cutover_pr <= 0): + parser.error("use positive object numbers") + if args.handoff and not args.cutover_pr: + parser.error("--handoff needs --cutover-pr") + root = f"repos/{REPO}" + try: + snapshot, evidence, cutover = read_file(args.snapshot), read_file(args.evidence), None + if args.cutover_pr: + pr = get_json(f"{root}/pulls/{args.cutover_pr}") + if not pr["merged"] or pr["base"]["ref"] != "main": + raise ValueError("the inspector PR must have merged into main") + cutover = merge_event( + paginated(f"{root}/issues/{args.cutover_pr}/timeline"), + pr["merge_commit_sha"], + pr["html_url"], + ) + report = {"cutover": cutover, "objects": []} + report["published_samples"] = { + "original_2026_11_24": {"issues": 186, "prs": 323, "prs_with_kind": 176}, + "shanghai_30_complete_days": {"issues": 181, "prs": 319, "prs_with_kind": 184}, + } + numbers = args.numbers + if args.recent_hours: + since = datetime.now(timezone.utc) - timedelta(hours=args.recent_hours) + report["updated_since"] = since.isoformat() + query = urlencode( + {"state": "all", "since": since.isoformat(), "sort": "updated", "direction": "asc"} + ) + numbers = [o["number"] for o in paginated(f"{root}/issues?{query}")] + if args.handoff: + report["handoff_pending"] = handoff_gaps(read_file(args.handoff), cutover) + for number in dict.fromkeys(numbers): + report["objects"].append( + inspect(root, number, evidence.get(str(number), {}), snapshot, cutover) + ) + print(json.dumps(report, indent=2, ensure_ascii=False)) + except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as exc: + print(f"Could not complete read-only label inspection: {exc}", file=sys.stderr) + return 1 + return 0 # Advisory findings can be nonempty. + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/label_audit_evidence.py b/tools/label_audit_evidence.py new file mode 100644 index 000000000..721b96ba2 --- /dev/null +++ b/tools/label_audit_evidence.py @@ -0,0 +1,203 @@ +"""Verify per-object evidence references and standing-review interpretations.""" + +from __future__ import annotations + +import re + +if __package__: + from .label_cutover import instant +else: + from label_cutover import instant + +REPO = "InferMatrixLab/InferRSI" +ISSUE_COMMENT = re.compile(rf"https://github\.com/{REPO}/issues/\d+#issuecomment-(\d+)") +STANDING = re.compile( + r"^\s*\s*$|\bI am (?:an? |the )?" + r"(?:unattended|standing) reviewer\b|我是常驻(?:自动)?评审", + re.I | re.M, +) +REVIEW = re.compile(r"\breview\b|NO PASS|检视|评审|审阅|复核", re.I) +UNINVITED = re.compile( + r"\bI (?:started|submitted|initiated) (?:this|the|my) review " + r"(?:uninvited|without (?:an? )?invitation)\b|" + r"我(?:在)?未(?:经|获)(?:点名|邀请)(?:时|便|就|的情况下)?(?:主动)?(?:发起|开始|提交)(?:了)?评审", + re.I, +) +CAPACITY = { + "owner": re.compile( + r"\bI (?:am |act (?:here )?as )(?:the )?(?:issue |decision )?owner\b|" + r"我(?:是|作为)(?:本单)?负责人", + re.I, + ), + "delegate": re.compile(r"on behalf of|acting for|受托|代办|代表", re.I), + "human": re.compile(r"\bI (?:am|reviewed as) (?:a )?human\b|人工评审|我本人", re.I), +} + + +def actor(record: dict) -> str: + return (record.get("user") or record.get("actor") or {}).get("login", "").lower() + + +def record_time(record: dict): + value = record.get("submitted_at") or record.get("created_at") + return instant(value) if value else None + + +def own_text(body: str, *, keep_standing_marker: bool = False) -> str: + """Discard quoted material, code examples and hidden instructions.""" + if keep_standing_marker: + body = re.sub( + r"(?m)^([ \t]*)[ \t]*$", + r"\1I am a standing reviewer", + body, + ) + lines = [] + fence = None + for line in re.sub(r"", "", body, flags=re.S).splitlines(): + stripped = line.lstrip() + if stripped.startswith(">"): + continue + marker = re.match(r"^(`{3,}|~{3,})", stripped) + if marker: + run = marker[1] + if fence is None: + fence = run + elif run.startswith(fence) and not stripped[len(run) :].strip(): + fence = None + elif fence is None and not line.startswith((" ", "\t")): + lines.append(line) + return "\n".join(lines) + + +class Evidence: + """Accept a curator's interpretation only with a traceable quotation.""" + + def __init__(self, obj, events, supplied, linked): + self.obj = obj + self.supplied = supplied + self.local = {e["html_url"]: e for e in events if e.get("html_url")} + self.local[obj["html_url"]] = obj + self.linked = linked + + def proof(self, value): + if not isinstance(value, dict): + return None + url, quote = value.get("url"), value.get("quote") + if not isinstance(url, str) or not isinstance(quote, str) or not quote.strip(): + return None + record = self.local.get(url) + if record is None: + via = self.local.get(value.get("via"), {}) + if url not in (via.get("body") or ""): + return None + record = self.linked.get(url) + if not record or quote not in (record.get("body") or ""): + return None + return url, record, quote + + def field(self, name): + proof = self.proof(self.supplied.get(name)) + return proof[0] if proof else None + + def standing_reviews(self, pr: bool): + """Return (code, detail, pending, sources) for positive or ambiguous cases.""" + activities = { + v.get("activity"): v + for v in self.supplied.get("standing_reviews", []) + if isinstance(v, dict) and isinstance(v.get("activity"), str) + } + for url, record in self.local.items(): + body = own_text(record.get("body") or "", keep_standing_marker=True) + if ( + record.get("event") in {"reviewed", "commented"} + and STANDING.search(body) + and (record.get("event") == "reviewed" or REVIEW.search(body)) + ): + activities.setdefault(url, {}) + for url, item in activities.items(): + event = self.local.get(url) or {} + account = actor(event) + body = own_text(event.get("body") or "", keep_standing_marker=True) + if event.get("event") not in {"reviewed", "commented"} or not account: + yield ( + "review-evidence", + "Verify the cited native review activity.", + True, + [self.obj["html_url"]], + ) + continue + role = self.proof(item.get("role")) + mode = {"human": "human", "delegated": "delegate"}.get(item.get("mode")) + role_text = ( + own_text((role[1].get("body") or ""), keep_standing_marker=True) if role else "" + ) + if ( + role + and mode + and role[2] in role_text + and CAPACITY[mode].search(role[2]) + and actor(role[1]) == account + ): + continue + if not ( + STANDING.search(body) + or ( + role + and role[2] in role_text + and actor(role[1]) == account + and STANDING.search(role[2]) + ) + ): + yield ( + "review-role", + "The account's standing reviewer role needs evidence.", + True, + [url], + ) + continue + if event.get("event") != "reviewed" and not REVIEW.search(body): + continue + revision = event.get("commit_id") or item.get("revision") + if not revision or (not event.get("commit_id") and revision not in body): + yield "review-revision", "Identify the reviewed commit or Issue state.", True, [url] + continue + if pr and revision != self.obj.get("head_sha"): + continue + if not pr and revision != self.supplied.get("issue_revision"): + yield "review-revision", "Verify the named current Issue state.", True, [url] + continue + invitation = self.proof(item.get("invitation")) + if invitation: + _, record, quote = invitation + mentioned = re.search(rf"(? datetime: + result = datetime.fromisoformat(value.replace("Z", "+00:00")) + if result.utcoffset() is None: + raise ValueError("an explicit time zone is required") + return result.astimezone(timezone.utc) + + +def merge_event(events: list[dict], merge_sha: str, pr_url: str) -> dict: + matches = [e for e in events if e.get("event") == "merged"] + if len(matches) != 1: + raise ValueError("cutover needs exactly one GitHub merged timeline event") + event = matches[0] + if not event.get("id") or not merge_sha or event.get("commit_id") != merge_sha: + raise ValueError("merge event ID and merged PR's matching commit are required") + at = instant(event["created_at"]).isoformat().replace("+00:00", "Z") + return { + "at": at, + "event_id": event["id"], + "sha": merge_sha, + "url": f"{pr_url}#event-{event['id']}", + } + + +def replay_pr_kind(obj: dict, events: list[dict], snapshot: dict, cutover: dict) -> dict: + """Reconstruct one object's kinds at T and isolate additions strictly after T.""" + url = obj["html_url"] + result = {"at_cutover": None, "new_additions": [], "replayed": [], "pending": []} + missing = result["pending"] + end = instant(cutover["at"]) + created = instant(obj["created_at"]) + if created > end: + start, kinds = created, set() + else: + start_text = snapshot.get("at") + if not start_text: + missing.append("exact timestamp of the original snapshot") + return result + start = instant(start_text) + if start >= end: + raise ValueError("baseline snapshot must precede the merge event") + if created > start: + kinds = set() # The object did not yet exist, independently of cohort membership. + else: + row = snapshot.get("objects", {}).get(str(obj["number"])) + if not isinstance(row, list): + missing.append("original object-level snapshot row") + return result + if not all(isinstance(v, str) and v.startswith("kind:") for v in row): + raise ValueError("a snapshot row must list exact kind labels") + kinds = set(row) + at_cut = set(kinds) + seen = {} + ordered = [] + for event in events: + op = event.get("event") + label = (event.get("label") or {}).get("name", "") + if op not in ("labeled", "unlabeled") or not label.startswith("kind:"): + continue + if not event.get("id") or not event.get("created_at"): + missing.append("timestamp and event ID for each kind change") + continue + when = instant(event["created_at"]) + key = event["id"] + details = when, op, label + if key in seen: + if seen[key] != details: + missing.append(f"conflicting records for event {key}") + continue + seen[key] = details + if when < start: + continue + ordered.append((when, key, op, label)) + # GitHub IDs identify events. They do not order events across timelines. + # Preserve the order from the paginated object timeline within each second. + for when, key, op, label in sorted(ordered, key=lambda row: row[0]): + if when == end or ( + created <= start + and snapshot.get("at") + and when == start + and created <= instant(snapshot["at"]) + ): + missing.append(f"event {key} shares a boundary second; ordering is unknown") + continue + if when < created: + missing.append(f"event {key} predates the object") + continue + add = op == "labeled" + if (label in kinds) == add: + missing.append(f"event {key} disagrees with the reconstructed prior state") + if add: + kinds.add(label) + else: + kinds.discard(label) + entry = { + "id": key, + "at": when.isoformat(), + "event": op, + "label": label, + "url": f"{url}#event-{key}", + } + if when < end: + at_cut = set(kinds) + result["replayed"].append(entry) + elif add: + result["new_additions"].append(entry) + observed = {label["name"] for label in obj["labels"] if label["name"].startswith("kind:")} + if kinds != observed: + missing.append("timeline and current label readback disagree") + if missing: + result["new_additions"] = [] # No count from an unresolved replay. + else: + result["at_cutover"] = sorted(at_cut) + return result + + +def hourly_area_plan_current(plan: dict, writer: dict) -> bool: + """Can this queued area addition still be considered after the handoff? + + Re-evaluate immediately before *each* send or retry. A new generation after + the freeze invalidates every old plan. This predicate issues no requests. + """ + return ( + writer.get("mode") == "resumed" + and bool(writer.get("generation")) + and plan.get("generation") == writer["generation"] + and plan.get("operation") == "add" + and plan.get("label") in AREAS + and bool(plan.get("area_evidence")) + ) + + +def handoff_gaps(receipt: dict, cutover: dict) -> list[str]: + """Validate an operator's counters and timestamps, preserving missing evidence.""" + gaps = [] + freeze = receipt.get("freeze") or {} + stop_time = freeze.get("at") + if ( + not stop_time + or instant(stop_time) >= instant(cutover["at"]) + or not public_link(freeze.get("url")) + or freeze.get("scope") != "all-label-writes" + or not freeze.get("invalidated_generation") + or any( + type(freeze.get(k)) is not int or freeze[k] != 0 + for k in ("queued", "retries", "in_flight") + ) + ): + gaps.append( + "dated pre-merge operator record: all writes paused, old generation " + "invalidated, queues, retries and in-flight traffic drained" + ) + trial = receipt.get("trial") or {} + timestamp = trial.get("at") + if ( + not timestamp + or instant(timestamp) <= instant(cutover["at"]) + or not public_link(trial.get("url")) + or not trial.get("run_id") + or not re.fullmatch( + r"https://github\.com/InferMatrixLab/InferRSI/pull/\d+", trial.get("pr_url", "") + ) + or not re.fullmatch(r"[0-9a-f]{40}", trial.get("head", "")) + or not public_link(trial.get("readback_url")) + or trial.get("readback_url") == trial.get("url") + or trial.get("existing_open_pr") is not True + or trial.get("inspected") is not True + or type(trial.get("remote_label_requests")) is not int + or trial["remote_label_requests"] != 0 + or trial.get("kinds_before") != [] + or trial.get("kinds_after") != [] + ): + gaps.append( + "dated post-merge operator dry run on an existing open PR without kind: " + "inspection, zero remote label writes and independent readback" + ) + return gaps + + +def public_link(value) -> bool: + if not isinstance(value, str): + return False + parsed = urlsplit(value) + return parsed.scheme == "https" and bool(parsed.hostname) and not parsed.username From 7c46dcc14be1a8072fb9bb1218d8da56909785c7 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:45:21 +0800 Subject: [PATCH 2/3] Anchor nightly replay to the inspection pull request Agent-assisted-by: Codex / gpt-6.2-astra effort=max (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- .github/workflows/ci-nightly.yml | 2 +- docs/guides/issue-label-audit.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci-nightly.yml b/.github/workflows/ci-nightly.yml index 6b1e6dce2..f94da81c9 100644 --- a/.github/workflows/ci-nightly.yml +++ b/.github/workflows/ci-nightly.yml @@ -53,7 +53,7 @@ jobs: - name: Inspect recently updated Issues and PRs env: GH_TOKEN: ${{ github.token }} - run: python tools/audit_issue_labels.py --recent-hours 48 > "$RUNNER_TEMP/issue-label-audit.json" + run: python tools/audit_issue_labels.py --recent-hours 48 --cutover-pr 681 > "$RUNNER_TEMP/issue-label-audit.json" - uses: actions/upload-artifact@v4 with: name: issue-label-audit diff --git a/docs/guides/issue-label-audit.md b/docs/guides/issue-label-audit.md index 80a15f90a..defa28491 100644 --- a/docs/guides/issue-label-audit.md +++ b/docs/guides/issue-label-audit.md @@ -4,7 +4,7 @@ The nightly `safety-net` job publishes an `issue-label-audit` JSON artifact for ## Read a report -Run `python tools/audit_issue_labels.py 335 658` with an authenticated GitHub CLI that can read InferRSI Issues and PRs. Use `--recent-hours 48` instead of object numbers to reproduce the nightly selection. Each entry identifies the object, observed labels, PR head where applicable, suggested additions/removals and evidence links. A pending finding identifies missing evidence. Findings can be nonempty on a successful run. An unavailable API returns an error. The existing `tools/check_labels.py` independently fails on label definition or reference drift. +Run `python tools/audit_issue_labels.py 335 658` with an authenticated GitHub CLI that can read InferRSI Issues and PRs. Use `--recent-hours 48 --cutover-pr 681` instead of object numbers to reproduce the nightly selection. Each entry identifies the object, observed labels, PR head where applicable, suggested additions/removals and evidence links. A pending finding identifies missing evidence. Findings can be nonempty on a successful run. An unavailable API returns an error. The existing `tools/check_labels.py` independently fails on label definition or reference drift. The optional `--evidence decisions.json` supplies a human reading of public records, keyed by object number. A proof has `url` and an exact `quote` from its body. For a parent Issue comment, add `via`, the URL of a record on the inspected object containing the parent link. The tool fetches that comment and verifies its quotation. Review the meaning and ownership before acting. Useful keys include: @@ -14,7 +14,7 @@ The optional `--evidence decisions.json` supplies a human reading of public reco ## Reconstruct PR kinds at cutover -Pass `--cutover-pr N` with the merged **inspection** PR number. Its GitHub `merged` timeline event supplies T, the event ID and the matching merge commit SHA. On each PR, `replayed` shows pre-T changes and `at_cutover` the reconstructed kinds. `new_additions` counts each distinct addition strictly after T, including re-additions on older PRs. A same-second boundary with unknown order or incomplete history stays pending. [Accepted cutover](https://github.com/InferMatrixLab/InferRSI/issues/658#issuecomment-7155913512) +Pass `--cutover-pr 681` for [the inspection PR](https://github.com/InferMatrixLab/InferRSI/pull/681). Its GitHub `merged` timeline event supplies T, the event ID and the matching merge commit SHA. On each PR, `replayed` shows pre-T changes and `at_cutover` the reconstructed kinds. `new_additions` counts each distinct addition strictly after T, including re-additions on older PRs. A same-second boundary with unknown order or incomplete history stays pending. [Accepted cutover](https://github.com/InferMatrixLab/InferRSI/issues/658#issuecomment-7155913512) An original `--snapshot snapshot.json` has an exact zoned `at` timestamp and an `objects` map from PR number to its observed `kind:*` list. An empty list is a recorded absence. Supply only original per-object evidence. The November 24 snapshot published 186 Issues and 323 PRs, with 176 PRs carrying kind. Its precise timestamp and object-label rows were unavailable at implementation. The separately measured Shanghai 30-day creation cohort contained 181 Issues and 319 PRs, including 184 with kind. The report preserves both published counts. A newly created post-T PR can be replayed from its creation. [Audit windows](https://github.com/InferMatrixLab/InferRSI/issues/658) @@ -22,5 +22,5 @@ An original `--snapshot snapshot.json` has an exact zoned `at` timestamp and an 1. When this inspector is ready to merge, the operator of “分类标签小时维护” pauses **every** remote label operation, invalidates all previously planned requests and retry generations, drains in-flight requests and records time, generation and zero queue/retry/in-flight counts on the PR. Keep the writer paused across T. [Owner and operator decisions](https://github.com/InferMatrixLab/InferRSI/issues/658#issuecomment-7155986059) 2. After the merge, record the actual GitHub merged event. With the writer still paused, run one complete read-only cycle that inspects a pre-existing open PR with no kind. Record the PR URL and head, opening state and labels, run ID/time, zero remote label requests for the whole run, and a separate GitHub readback. If no PR qualifies, record that and keep the writer paused. [Operator clarification](https://github.com/InferMatrixLab/InferRSI/issues/658#issuecomment-7154855391) -3. To check the operator's recorded fields and their timing, run `python tools/audit_issue_labels.py --cutover-pr N --handoff operator.json P`, where P was inspected. The `freeze` object records `at`, `url`, `scope: all-label-writes`, `invalidated_generation`, `queued`, `retries` and `in_flight`. The `trial` object records `at`, `url`, `run_id`, `pr_url`, `head`, `existing_open_pr`, `inspected`, `remote_label_requests`, `kinds_before`, `kinds_after` and a separate `readback_url`. Verify the linked operator logs, counters and independent GitHub readback before resuming. The CLI validates the supplied fields and timestamps. +3. To check the operator's recorded fields and their timing, run `python tools/audit_issue_labels.py --cutover-pr 681 --handoff operator.json P`, where P was inspected. The `freeze` object records `at`, `url`, `scope: all-label-writes`, `invalidated_generation`, `queued`, `retries` and `in_flight`. The `trial` object records `at`, `url`, `run_id`, `pr_url`, `head`, `existing_open_pr`, `inspected`, `remote_label_requests`, `kinds_before`, `kinds_after` and a separate `readback_url`. Verify the linked operator logs, counters and independent GitHub readback before resuming. The CLI validates the supplied fields and timestamps. 4. Resume with a fresh generation and recheck every plan at send and retry time. Automatic additions are limited to documented areas with clear evidence. Issue kind and proposed status are suggestions. For a delegated status change verify the owner's recorded decision, an existing proposal and the applicable authority. Keep missing/partial acceptance and PR kind/status out of the writer. Preserve the body, record actual changes in the task history and use the report for routine findings. [Write authority](../agent-collaboration.md#labels) From 59718ce88f9cd778dbb1df5d4b2c90c4e4cd3b37 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:00:23 +0800 Subject: [PATCH 3/3] Require verifiable evidence before closure and review Agent-assisted-by: Codex / gpt-6.2-astra effort=max (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/guides/issue-label-audit.md | 4 +- tests/repository/test_audit_issue_labels.py | 62 +++++++++++++++++++++ tools/audit_issue_labels.py | 56 ++++++++++++++----- tools/label_audit_evidence.py | 13 +++-- 4 files changed, 115 insertions(+), 20 deletions(-) diff --git a/docs/guides/issue-label-audit.md b/docs/guides/issue-label-audit.md index defa28491..024ddcbee 100644 --- a/docs/guides/issue-label-audit.md +++ b/docs/guides/issue-label-audit.md @@ -9,8 +9,8 @@ Run `python tools/audit_issue_labels.py 335 658` with an authenticated GitHub CL The optional `--evidence decisions.json` supplies a human reading of public records, keyed by object number. A proof has `url` and an exact `quote` from its body. For a parent Issue comment, add `via`, the URL of a record on the inspected object containing the parent link. The tool fetches that comment and verifies its quotation. Review the meaning and ownership before acting. Useful keys include: - `open_question`, `scope_decision`, `whole_scope_acceptance`, `deferral`, `label_delegation`, `delivery`, `blocker` and `disposition`. For a suggested missing kind, pair `suggested_kind` with `kind_choice`. Pair a list of `suggested_areas` with an `area_scope` quote covering the named responsibilities. Conflicting acceptance and deferral evidence leaves the decision pending. -- `closer_login`, `closer_role` (`owner` or `delegate`), `closer_identity`, `owner_authority`, `goal_decision` and `closure_summary` identify who closed this open cycle and on what grounds. A delegated close also needs `closure_delegation`. Interpret an explicit statement of capacity. One shared login may represent several actors. -- `standing_reviews` entries cite native `activity`. The activity or a reviewer-authored `role` proof identifies a standing reviewer. A formal PR review supplies its commit. For a comment supply `revision`, and for Issues also supply `issue_revision` identifying the current state. An `invitation` proof quotes the @ mention, request to review and revision in a prior record. Missing evidence is pending. The uninvited count requires an explicit positive record from the standing reviewer. +- `closer_login`, `closer_role` (`owner` or `delegate`), `closer_identity`, `owner_authority`, `goal_decision` and `closure_summary` identify who closed this open cycle and on what grounds. A delegated close also needs `closure_delegation`. A closure record must originate after the latest reopening, if any. Its current text and any local link to a parent decision must predate the native close. A later edit or an unresolved same-second ordering leaves the evidence pending. Interpret an explicit statement of capacity. One shared login may represent several actors. +- `standing_reviews` entries cite native `activity`. The activity or a reviewer-authored `role` proof identifies a standing reviewer. A formal PR review supplies its commit. For a comment supply `revision`, and for Issues also supply `issue_revision` identifying the current state. An `invitation` proof quotes the @ mention, request to review and revision. The latest version of the cited body or comment must predate the review. Missing evidence is pending. The uninvited count requires an explicit positive record from the standing reviewer. ## Reconstruct PR kinds at cutover diff --git a/tests/repository/test_audit_issue_labels.py b/tests/repository/test_audit_issue_labels.py index d7e07f56e..3e1f195b6 100644 --- a/tests/repository/test_audit_issue_labels.py +++ b/tests/repository/test_audit_issue_labels.py @@ -140,6 +140,56 @@ def test_shared_login_is_not_delegation(): ) +@pytest.mark.parametrize( + ("created", "edited", "pending"), + [ + (BEFORE, None, False), + (T, None, True), + (AFTER, None, True), + (BEFORE, T, True), + (BEFORE, AFTER, True), + ], +) +def test_only_decisions_and_delegations_verifiable_before_closure_count(created, edited, pending): + item = obj(["area:process", KIND], pr=False) + item["state"] = "closed" + identity = comment(10, "I am acting on behalf of the issue owner.", "delegate") + decision = comment(11, "I accept the result and delegate closure.", when=created) + if edited: + decision["updated_at"] = edited + close = {"event": "closed", "id": 20, "actor": {"login": "delegate"}, "created_at": T} + data = { + "closer_login": "delegate", + "closer_role": "delegate", + "closer_identity": proof(identity), + "goal_decision": proof(decision), + "closure_delegation": proof(decision), + } + row = audit.audit_object(item, [identity, decision, close], data, {}, None) + assert row["closure"]["role"] == "delegate" + for key in ("goal_decision", "closure_delegation"): + assert (key in codes(row)) == pending + assert (decision["html_url"] in row["closure"]["sources"]) != pending + + +def test_parent_decision_needs_a_reference_from_the_close_cycle(): + item = obj(["area:process", KIND], pr=False) + item["state"] = "closed" + parent = comment(10, "I accept the result.") + parent["html_url"] = f"{BASE}/issues/8#issuecomment-10" + reference = comment(11, parent["html_url"]) + evidence = {"goal_decision": {**proof(parent), "via": reference["html_url"]}} + groups = {parent["html_url"]: parent} + close = {"event": "closed", "id": 20, "actor": {"login": "owner"}, "created_at": T} + assert "goal_decision" not in codes( + audit.audit_object(item, [reference, close], evidence, {}, None, groups) + ) + reference["updated_at"] = AFTER + assert "goal_decision" in codes( + audit.audit_object(item, [reference, close], evidence, {}, None, groups) + ) + + def test_frozen_writer_rejects_old_queue_and_retry_before_each_remote_call(): pr_labels = {"area:process"} remote_calls = [] @@ -235,6 +285,18 @@ def test_standing_activity_needs_affirmative_account_and_revision_evidence(): assert audit.audit_object(pr, [action], {}, {}, None)["uninvited_standing_reviews"] == 0 +@pytest.mark.parametrize(("edited", "pending"), [(BEFORE, False), (T, True), (AFTER, True)]) +def test_invitation_comment_text_must_predate_the_review(edited, pending): + invite = comment(10, f"@bot please review {HEAD}", when=ORIGINAL) + invite["updated_at"] = edited + review = comment(11, "I am a standing reviewer. I reviewed this.", "bot", T) + review.update(event="reviewed", commit_id=HEAD) + data = {"standing_reviews": [{"activity": review["html_url"], "invitation": proof(invite)}]} + row = audit.audit_object(obj(["area:process"]), [invite, review], data, {}, None) + assert ("review-invitation" in codes(row)) == pending + assert row["uninvited_standing_reviews"] == 0 + + def test_status_decision_is_cited_and_suggestions_are_separate_from_authority(): issue = obj(["area:process", KIND, "status:proposed"], pr=False) issue["body"] = ( diff --git a/tools/audit_issue_labels.py b/tools/audit_issue_labels.py index 22652f606..b27fb22d9 100644 --- a/tools/audit_issue_labels.py +++ b/tools/audit_issue_labels.py @@ -12,10 +12,28 @@ from urllib.parse import urlencode if __package__: - from .label_audit_evidence import CAPACITY, ISSUE_COMMENT, REPO, Evidence, actor, own_text + from .label_audit_evidence import ( + CAPACITY, + ISSUE_COMMENT, + REPO, + Evidence, + actor, + own_text, + record_time, + text_version_time, + ) from .label_cutover import AREAS, LABELS, handoff_gaps, instant, merge_event, replay_pr_kind else: # Direct invocation: python tools/audit_issue_labels.py - from label_audit_evidence import CAPACITY, ISSUE_COMMENT, REPO, Evidence, actor, own_text + from label_audit_evidence import ( + CAPACITY, + ISSUE_COMMENT, + REPO, + Evidence, + actor, + own_text, + record_time, + text_version_time, + ) from label_cutover import AREAS, LABELS, handoff_gaps, instant, merge_event, replay_pr_kind PROGRESS_KINDS = {"kind:task", "kind:rfc", "kind:acceptance", "kind:tracking"} @@ -250,23 +268,36 @@ def finding(code, detail, *, pending=False, add=(), remove=(), sources=()): last_open = next((e for e in reversed(cycles) if e["event"] == "reopened"), None) last_close = cycles[-1] if closed and cycles and cycles[-1]["event"] == "closed" else None + reopened_at = record_time(last_open or {}) + closed_at = record_time(last_close or {}) + def current_cycle(record): - return not last_open or bool( - record.get("created_at") - and instant(record["created_at"]) > instant(last_open["created_at"]) - ) + created = record_time(record) + if not created or (last_open and (not reopened_at or created <= reopened_at)): + return False + if closed: + return bool(closed_at and text_version_time(record) < closed_at) + return True + + def closure_proof(key): + citation = evidence.get(key) + entry = proof.proof(citation) + if not entry or not current_cycle(entry[1]): + return None + if entry[0] not in proof.local and not current_cycle(proof.local[citation["via"]]): + return None + return entry links = [] required = ["closure_summary", "goal_decision", "owner_authority"] role = evidence.get("closer_role") close_actor = actor(last_close or {}) - identity = proof.proof(evidence.get("closer_identity")) + identity = closure_proof("closer_identity") if ( role not in {"owner", "delegate"} or not close_actor or (evidence.get("closer_login") or "").lower() != close_actor or not identity - or not current_cycle(identity[1]) or identity[2] not in own_text(identity[1].get("body") or "") or actor(identity[1]) != close_actor or not CAPACITY[role].search(identity[2]) @@ -283,14 +314,11 @@ def current_cycle(record): if role == "delegate": required.append("closure_delegation") for key in required: - link = source(key) - record = proof.local.get(link) or proof.linked.get(link) or {} - if link and not current_cycle(record): - link = None - if not link: + entry = closure_proof(key) + if not entry: finding(key, f"Verify {key.replace('_', ' ')} for this open cycle.", pending=True) else: - links.append(link) + links.append(entry[0]) result["closure"] = { "role": role, "sources": links, diff --git a/tools/label_audit_evidence.py b/tools/label_audit_evidence.py index 721b96ba2..fc5373174 100644 --- a/tools/label_audit_evidence.py +++ b/tools/label_audit_evidence.py @@ -43,6 +43,14 @@ def record_time(record: dict): return instant(value) if value else None +def text_version_time(record: dict): + """Latest time the observed text could have been written.""" + created = record_time(record) + if created and record.get("updated_at"): + return max(created, instant(record["updated_at"])) + return created + + def own_text(body: str, *, keep_standing_marker: bool = False) -> str: """Discard quoted material, code examples and hidden instructions.""" if keep_standing_marker: @@ -170,11 +178,8 @@ def standing_reviews(self, pr: bool): if invitation: _, record, quote = invitation mentioned = re.search(rf"(?