Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

## Unreleased

No changes recorded after the v0.19.0 consolidation.
- **Read-only GitHub CLI transport (PATCH):** Add explicit `--transport gh` to the publication history and exact payload validators, delegating authentication to the configured GitHub CLI instead of handling credentials in agent command text. Preserve existing HTTP mode and all evidence, access, source, history and exact-consent gates; no automatic fallback or release bump.

## [0.19.0](changes/v0.19.0.md) — Source-aware Roadmap construction and verified publication

Expand Down
12 changes: 11 additions & 1 deletion docs/PUBLICATION_HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ Before proposing another public Roadmap Issue, use the **read-only** publication
For a read-only organization inventory, use `python3 scripts/publication_history.py --format json`. For any candidate, use the procedure below. The CLI never posts and the bounded archive remains incomplete.


## Explicit GitHub CLI transport

For an operator runtime with an already configured and authorized GitHub CLI account, both `publication_history.py` and `validate_public_issue_payload.py` accept `--transport gh`. Use the same explicit transport for discovery, persisted-case approval and pre-POST recheck when appropriate. The default `--transport http` is unchanged for existing callers and CI.

The CLI transport delegates authentication to `gh api --hostname github.com`; the Python scripts do not retrieve, print or pass a credential in command arguments. It accepts only the REST read routes required by the existing evidence scan (explicit GET) and the two fixed, read-only Discussion GraphQL query documents. GraphQL uses POST only as the query transport, never as a mutation. Pagination limits, first-party evidence, canonical metadata checks, exact approval fingerprint, owner PAUSE/STOP and external publication consent are unchanged.

Use only when the runtime's configured access and applicable security policies authorize that read. Do not select this mode to override a denied operation or evade API limits; errors, missing CLI, missing authorization, rate limits, timeouts, malformed JSON and GraphQL errors remain fail-closed. No implicit retries, account switching or fallback to another credential/transport. The transport does not establish publisher identity or authorize a GitHub write; repeat the separate native route and actual publisher checks before approved publication.

For example, append `--transport gh` to the existing commands below; no credential extraction is required.

## Mandatory persisted Roadmap gate

The history scan is deliberately a two-step workflow. Discovery and local draft checks do not make a proposal ready for the owner.
Expand Down Expand Up @@ -67,7 +77,7 @@ The example is an interface illustration, not authorization or a new Browser Har

The view uses the existing `roadmap_view.py` verified fork discovery and canonical case IDs; it reads case receipt and append-only `publication` events as proof. A GitHub URL *merely cited in a research file* is **not** evidence OpenSiro published it. Same-case publication in the **same action channel** returns `ALREADY_PUBLISHED` even if an old README said `NOT_PUBLISHED`. A separate fork vs original Issue remains a separately approvable action but returns overlap for review. Exact older OpenSiro-authored titles returned by provider search yield `REUSE_EXISTING`; related original/cross-project references yield `POSSIBLE_OVERLAP`. Insufficient provider, history or search coverage yields `HISTORY_UNVERIFIED`.

GitHub REST GET is used for original/fork Issues, PRs, and bounded Issue comments, while an authenticated **read-only GitHub GraphQL query** is used for Discussion content and comments. A missing token, 403/404, truncated comments, changed outbound SHA, source mismatch or unsupported channel yields `UNVERIFIED`. The CLI searches native original Issues **and PRs**, both by publisher and bounded terms, and reads bounded repository Discussions through authenticated read-only GraphQL when enabled. Missing token or pagination/completeness uncertainty is recorded as `HISTORY_UNVERIFIED`. Native REST Issue/PR search reads up to 1,000 results per query in 100-item pages; every page must have a consistent reported count, complete flag, expected length and distinct, correct-channel identities. A result beyond the provider cap, page error, count drift or duplicate remains unverified; a successful bounded scan is not exhaustive global history. CLI uses the existing GH_TOKEN/GITHUB_TOKEN runtime authentication if configured; exhausted anonymous REST quota is a blocker, not grounds for bypass. Native original search does not cover every alternate audience; new non-original-Issue channels remain conservatively unverified for novelty. Independently review source-native alternatives, actual maintainer feedback and the concrete user-visible delta. Keyword matches and bounded negative searches do not establish equivalence or novelty.
GitHub REST GET is used for original/fork Issues, PRs, and bounded Issue comments, while an authenticated **read-only GitHub GraphQL query** is used for Discussion content and comments. A missing token, 403/404, truncated comments, changed outbound SHA, source mismatch or unsupported channel yields `UNVERIFIED`. The CLI searches native original Issues **and PRs**, both by publisher and bounded terms, and reads bounded repository Discussions through authenticated read-only GraphQL when enabled. Missing token or pagination/completeness uncertainty is recorded as `HISTORY_UNVERIFIED`. Native REST Issue/PR search reads up to 1,000 results per query in 100-item pages; every page must have a consistent reported count, complete flag, expected length and distinct, correct-channel identities. A result beyond the provider cap, page error, count drift or duplicate remains unverified; a successful bounded scan is not exhaustive global history. The default HTTP transport uses existing GH_TOKEN/GITHUB_TOKEN runtime authentication if configured; the explicitly selected CLI transport uses the configured GitHub CLI authorization. Exhausted quota or denied access is a blocker, not grounds for bypass. Native original search does not cover every alternate audience; new non-original-Issue channels remain conservatively unverified for novelty. Independently review source-native alternatives, actual maintainer feedback and the concrete user-visible delta. Keyword matches and bounded negative searches do not establish equivalence or novelty.

## Approval packet / human review

Expand Down
84 changes: 84 additions & 0 deletions scripts/gh_readonly_transport.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""Explicit read-only GitHub CLI transport for publication evidence.

GitHub CLI owns authentication. No credentials are extracted or printed.
No implicit retry, alternative account, transport fallback or write operation.
"""
import json
import re
import subprocess
from urllib.parse import unquote, urlsplit

from aggregate import APIError

DISCUSSION_QUERY = """query($owner:String!, $name:String!, $number:Int!) {
repository(owner:$owner, name:$name) {
discussion(number:$number) {
title body createdAt updatedAt author { login }
comments(first: 100) {
totalCount pageInfo { hasNextPage }
nodes { url body author { login } authorAssociation createdAt updatedAt }
}
}
}
}"""
DISCUSSION_SEARCH_QUERY = """query($owner:String!, $name:String!, $cursor:String) {
repository(owner:$owner, name:$name) {
discussions(first: 100, after:$cursor) {
totalCount pageInfo { hasNextPage endCursor }
nodes { number url title body updatedAt author { login } }
}
}
}"""

READ_QUERIES = {
DISCUSSION_QUERY: {"owner", "name", "number"},
DISCUSSION_SEARCH_QUERY: {"owner", "name", "cursor"},
}


class GhReadOnlyTransport:
"""One explicit host; REST GET and two fixed GraphQL query documents."""

def _run(self, args, data=None):
command = ["gh", "api", "--hostname", "github.com",
"-H", "Accept: application/vnd.github+json",
"-H", "X-GitHub-Api-Version: 2022-11-28", *args]
try:
result = subprocess.run(command, input=data, text=True, capture_output=True,
check=False, timeout=30)
except (OSError, subprocess.TimeoutExpired) as exc:
raise APIError(0, "GitHub CLI read unavailable") from exc
if result.returncode:
# Do not echo stderr/stdout, command payload, or credential information.
status = re.search(r"\bHTTP ([45][0-9]{2})\b", result.stderr or "")
code = int(status.group(1)) if status else 0
raise APIError(code, f"GitHub CLI read failed (HTTP {code})" if code
else "GitHub CLI read failed")
try:
return json.loads(result.stdout)
except (ValueError, TypeError) as exc:
raise APIError(0, "GitHub CLI response is not JSON") from exc

def get(self, path):
if (not isinstance(path, str) or not path.startswith("/") or path.startswith("//")
or any(ord(c) < 32 or ord(c) == 127 for c in path)
or any(c in path for c in ("{", "}"))):
raise APIError(0, "Unsupported GitHub REST read path")
parsed = urlsplit(path)
decoded = unquote(parsed.path)
if (parsed.scheme or parsed.netloc or parsed.fragment
or any(ord(c) < 32 or ord(c) == 127 for c in decoded)
or any(c in decoded for c in (chr(92), "{", "}"))
or any(s in (".", "..") for s in decoded.split("/"))
or not re.fullmatch(r"/(?:repos/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:/(?:contents(?:/[^?]*)?|git/ref/heads/[^?]+|issues/[1-9][0-9]*(?:/comments)?|pulls/[1-9][0-9]*))?|orgs/[A-Za-z0-9_.-]+/repos|search/issues)", parsed.path)):
raise APIError(0, "Unsupported GitHub REST read path")
return self._run(["--method", "GET", "--", path.lstrip("/")])

def query(self, query, variables):
if query not in READ_QUERIES or not isinstance(variables, dict) or set(variables) != READ_QUERIES[query]:
raise APIError(0, "Unsupported GitHub GraphQL read operation")
result = self._run(["--method", "POST", "--input", "-", "--", "graphql"],
json.dumps({"query": query, "variables": variables}))
if not isinstance(result, dict) or result.get("errors") or not isinstance(result.get("data"), dict):
raise APIError(0, "GraphQL readback errors")
return result["data"]
40 changes: 20 additions & 20 deletions scripts/publication_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from urllib.error import HTTPError, URLError

from aggregate import APIError, GitHub, api, REPOSITORY
from gh_readonly_transport import GhReadOnlyTransport, DISCUSSION_QUERY, DISCUSSION_SEARCH_QUERY
from roadmap_view import roadmap_view, read_text
from publication_archive import discover_archive
from roadmap_proposal_gate import (ACTIONS, BLOCKED, VERIFIED, GATE_ERRORS,
Expand Down Expand Up @@ -177,17 +178,7 @@ def _query(self, query, variables):

def discussion(self, repo, number):
owner, name = repo.split("/", 1)
query = """query($owner:String!, $name:String!, $number:Int!) {
repository(owner:$owner, name:$name) {
discussion(number:$number) {
title body createdAt updatedAt author { login }
comments(first: 100) {
totalCount pageInfo { hasNextPage }
nodes { url body author { login } authorAssociation createdAt updatedAt }
}
}
}
}"""
query = DISCUSSION_QUERY
data = self._query(query, {"owner": owner, "name": name, "number": number})
item = (data.get("repository") or {}).get("discussion")
if not isinstance(item, dict):
Expand All @@ -197,14 +188,7 @@ def discussion(self, repo, number):
def discussion_search(self, repo, terms):
"""Bounded first-party Discussion enumeration, not a semantic classifier."""
owner, name = repo.split("/", 1)
query = """query($owner:String!, $name:String!, $cursor:String) {
repository(owner:$owner, name:$name) {
discussions(first: 100, after:$cursor) {
totalCount pageInfo { hasNextPage endCursor }
nodes { number url title body updatedAt author { login } }
}
}
}"""
query = DISCUSSION_SEARCH_QUERY
cursor = None
rows = []
seen = set()
Expand Down Expand Up @@ -235,6 +219,19 @@ def discussion_search(self, repo, terms):
raise APIError(0, "GraphQL discussion scan bound reached")


class GhPublicationGitHub(ReadOnlyGitHub):
"""Reuse the exact evidence/pagination logic with explicit CLI transport."""

def __init__(self):
self.transport = GhReadOnlyTransport()

def get(self, path):
return self.transport.get(path)

def _query(self, query, variables):
return self.transport.query(query, variables)


def feedback_observation(client, repo, number, expected_count):
"""Bounded original Issue comments; do not score bot replies as acceptance."""
if expected_count == 0:
Expand Down Expand Up @@ -820,8 +817,11 @@ def main(argv=None):
p.add_argument("--previous-report", type=Path,
help="approval-time JSON report; any changed evidence requires re-review")
p.add_argument("--format", choices=["json"], default="json")
p.add_argument("--transport", choices=("http", "gh"), default="http",
help="explicit read-only GitHub CLI transport (no token extraction or fallback)")
a = p.parse_args(argv)
client = ReadOnlyGitHub(os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN"))
client = (GhPublicationGitHub() if a.transport == "gh" else
ReadOnlyGitHub(os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN")))
source_before = source_error = None
if a.candidate_original and a.candidate_kind in ACTIONS:
try:
Expand Down
6 changes: 5 additions & 1 deletion scripts/validate_public_issue_payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from pathlib import Path
from validate_capability_roadmap import value
from aggregate import GitHub
from gh_readonly_transport import GhReadOnlyTransport
from roadmap_proposal_gate import (BLOCKED, VERIFIED, GATE_ERRORS, digest,
review_evidence_sha256, verify_persisted_case)
from preflight_publication_destination import (markdown_feature_template_requirements,
Expand Down Expand Up @@ -295,6 +296,8 @@ def main():
help="local structural preparation only; never an approval preview")
p.add_argument("--history-report", type=Path,
help="fresh publication_history.py report for the exact committed candidate")
p.add_argument("--transport", choices=("http", "gh"), default="http",
help="explicit read-only GitHub CLI transport (no token extraction or fallback)")
a = p.parse_args()
if a.render_fork:
if a.kind != "fork":
Expand Down Expand Up @@ -341,7 +344,8 @@ def main():
raise ValueError("--history-report required; use --draft-only for local preparation")
report = json.loads(a.history_report.read_text(encoding="utf-8"))
proof = verify_issue_approval_case(
GitHub(os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN")), report,
(GhReadOnlyTransport() if a.transport == "gh" else
GitHub(os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN"))), report,
a.kind, a.case_dir, a.repo, a.case_ref, title, body_bytes, a.source_head)
except GATE_ERRORS as exc:
print(BLOCKED + ": " + str(exc))
Expand Down
Loading
Loading