diff --git a/REFERENCE.md b/REFERENCE.md index 81da152..89721ac 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -47,10 +47,24 @@ Response timing uses the earliest external message after the last maintainer message, including PR review comments and submitted reviews. A reply is not proof of resolution. Missing timestamps/order mean unknown. Accepted answers and broadcast categories preserve the existing hub settlement semantics. -The REST discussion adapter does not independently verify nested replies: -discussion activity is marked partial and response state unknown unless the -accepted-answer/broadcast policy already settles it. A later adapter can -upgrade coverage; do not silently claim full coverage now. +Discussion activity uses fixed read-only GraphQL queries for the complete +top-level comment connection and each comment's reply connection. Every +connection follows `pageInfo` cursors independently up to `max_pages`; a +missing/repeated cursor, null node, malformed response, GraphQL error or page +limit makes coverage partial. A failed GraphQL read may retain REST comments, +but those cannot prove reply completeness or clear the gap. No comment bodies +are requested by these queries. See GitHub's +[Discussion and DiscussionComment contracts](https://docs.github.com/en/graphql/guides/using-the-graphql-api-for-discussions). + +Deleted/unavailable actors, deleted comments, missing timestamps and ambiguous +cross-author ordering make response state unknown. A source that failed to +read is distinct from a successful empty read. REST PR review comments include +inline replies; submitted reviews and issue comments are separately paginated. +This measures response activity, not review-thread resolution or delivery. +An accepted proposal settles the hub response obligation only; implementation +and release evidence belong to the later follow-through phase. Accepted-answer +and broadcast policy can settle response obligation even while a coverage gap +remains visible. The CLI returns 2 for invalid configuration, input or render failure. Source read failures appear in a valid degraded snapshot so the dashboard can expose @@ -82,6 +96,9 @@ Clipboard failure exposes selectable prompt text; external text is escaped. Python 3.12+ and PyYAML; `gh` for live reads. GitHub Actions supplies its read-only token. Local operators use their existing GitHub authentication; never add credentials to config. No model/API calls or billing path. +GraphQL unavailability on a particular token or proxy is reported as partial +coverage; it never triggers credential changes or a write request. GraphQL +queries use HTTP POST as required by that read API, but contain no mutations. ```bash python bin/pyauto-ears scan --mind ../PyAutoMind --output output/snapshot.json diff --git a/ears/board.py b/ears/board.py index 18ce06e..f79b62c 100644 --- a/ears/board.py +++ b/ears/board.py @@ -104,7 +104,7 @@ def section(title, selected, empty): text += " — " + "; ".join(line(g) for g in r["gaps"]) body.append("
  • " + esc(text) + "
  • ") md.append("- " + esc(text)) - body.append('

    Discussion coverage is limited to the REST comments returned by the source; nested replies are not independently verified.

    ') + body.append('

    Discussion comments and replies are read separately. Failed reads and pagination limits remain explicit coverage gaps; accepted answers do not establish delivery.

    ') for title, message in [("Following through", "Planned: linked development and release evidence. Delivery tracking is not active yet."), ("Recurring feedback", "Planned: evidence-backed themes across independent reports. No themes have been inferred by this collector.")]: body.append(f"

    {title}

    {message}

    ") diff --git a/ears/collect.py b/ears/collect.py index 27b839c..1a2e861 100644 --- a/ears/collect.py +++ b/ears/collect.py @@ -9,6 +9,22 @@ REPO = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\Z") BROADCAST = {"Announcements", "Show and tell"} +DISCUSSION_COMMENTS = """query($owner:String!, $name:String!, $number:Int!, $after:String) { + repository(owner:$owner, name:$name) { discussion(number:$number) { + comments(first:100, after:$after) { + nodes { id createdAt deletedAt author { login __typename } } + pageInfo { hasNextPage endCursor } + } + } } +}""" +DISCUSSION_REPLIES = """query($id:ID!, $after:String) { + node(id:$id) { ... on DiscussionComment { + replies(first:100, after:$after) { + nodes { id createdAt deletedAt author { login __typename } } + pageInfo { hasNextPage endCursor } + } + } } +}""" def utc(value): @@ -71,6 +87,86 @@ def get(self, endpoint): except ValueError: raise ReadError("invalid JSON response") from None + def discussion_page(self, repo, number, after=None, comment_id=None): + """Only these fixed queries are allowed; source text is never executable.""" + owner, name = repository(repo).split("/") + query = DISCUSSION_REPLIES if comment_id else DISCUSSION_COMMENTS + variables = {"id": comment_id} if comment_id else { + "owner": owner, "name": name, "number": number} + if after is not None: + variables["after"] = after + payload = json.dumps({"query": query, "variables": variables}) + try: + r = subprocess.run([self.binary, "api", "graphql", "--input", "-"], + input=payload, capture_output=True, text=True, timeout=60) + if r.returncode: + raise ReadError("Discussion GraphQL read failed (permissions, rate limit or endpoint)") + result = json.loads(r.stdout) + if not isinstance(result, dict) or result.get("errors"): + raise ReadError("Discussion GraphQL returned incomplete evidence") + data = result["data"] + return data["node"]["replies"] if comment_id else data["repository"]["discussion"]["comments"] + except (OSError, subprocess.TimeoutExpired): + raise ReadError("Discussion GraphQL client unavailable or timed out") from None + except (ValueError, KeyError, TypeError): + raise ReadError("invalid Discussion GraphQL response") from None + + +def discussion_connection(api, repo, number, cap, comment_id=None): + rows, seen, cursor = [], set(), None + if not hasattr(api, "discussion_page"): + return rows, False, "Discussion GraphQL adapter unavailable" + for _ in range(cap): + try: + data = api.discussion_page(repo, number, cursor, comment_id) + except ReadError as exc: + return rows, False, str(exc) + if not isinstance(data, dict) or not isinstance(data.get("nodes"), list): + return rows, False, "invalid Discussion connection" + # Null nodes may represent deleted/inaccessible activity. Keep the gap. + if any(not isinstance(x, dict) for x in data["nodes"]): + rows.extend(x for x in data["nodes"] if isinstance(x, dict)) + return rows, False, "Discussion activity contains an unavailable node" + rows.extend(data["nodes"]) + info = data.get("pageInfo") + if not isinstance(info, dict) or type(info.get("hasNextPage")) is not bool: + return rows, False, "invalid Discussion pagination metadata" + if not info["hasNextPage"]: + return rows, True, None + cursor = info.get("endCursor") + if not isinstance(cursor, str) or not cursor or cursor in seen: + return rows, False, "Discussion pagination cursor missing or repeated" + seen.add(cursor) + return rows, False, "Discussion page budget reached; additional entries may exist" + + +def discussion_activity(api, repo, number, cap): + comments, complete, reason = discussion_connection(api, repo, number, cap) + gaps = [reason] if reason else [] + activity = list(comments) + for comment in comments: + identity = comment.get("id") + if not isinstance(identity, str) or not identity: + complete = False + gaps.append("Discussion comment identity unavailable") + continue + replies, ok, why = discussion_connection(api, repo, number, cap, identity) + activity.extend(replies) + complete &= ok + if why: + gaps.append(why) + normalized = [{"created_at": x.get("createdAt"), "deleted_at": x.get("deletedAt"), + "user": {"login": x["author"].get("login"), + "type": x["author"].get("__typename")} + if isinstance(x.get("author"), dict) else None} for x in activity] + if not complete: + # REST can preserve observed activity, but cannot erase the GraphQL gap. + fallback, _, why = pages(api, f"repos/{repo}/discussions/{number}/comments", cap) + normalized.extend(fallback) + if why: + gaps.append(why) + return normalized, complete, list(dict.fromkeys(gaps)) + def pages(api, endpoint, cap): items = [] @@ -89,10 +185,23 @@ def pages(api, endpoint, cap): def human(user): - return bool(user and user.get("login")) and user.get("type") != "Bot" \ + return isinstance(user, dict) and isinstance(user.get("login"), str) and bool(user["login"]) and user.get("type") != "Bot" \ and not user["login"].endswith("[bot]") +def activity_events(entries): + events, gaps = [], [] + for entry in entries: + actor = entry.get("user") + if entry.get("state") == "PENDING": + continue + if entry.get("deleted_at") or not isinstance(actor, dict) or not isinstance(actor.get("login"), str) or not actor["login"]: + gaps.append("activity author deleted or unavailable") + elif human(actor): + events.append((entry.get("submitted_at") or entry.get("created_at"), actor["login"])) + return events, list(dict.fromkeys(gaps)) + + def waiting(events, selves): """Oldest external message since the latest maintainer message. @@ -123,16 +232,14 @@ def conversation(api, repo, raw, kind, config): raise ReadError("invalid conversation number") path = "discussions" if kind == "discussion" else "issues" prefix = f"repos/{repo}/{path}/{number}" - comments, complete, reason = pages(api, prefix + "/comments", config["max_pages"]) - gaps = [reason] if reason else [] if kind == "discussion": - # The available REST contract does not prove recursive reply coverage. - # Keep the source visibly partial until an adapter can establish it. - complete = False - gaps.append("nested discussion replies not independently verified") - events = [(raw.get("created_at"), raw["user"]["login"])] if human(raw.get("user")) else [] - events += [(x.get("created_at"), x["user"]["login"]) for x in comments - if human(x.get("user"))] + comments, complete, gaps = discussion_activity(api, repo, number, config["max_pages"]) + else: + comments, complete, reason = pages(api, prefix + "/comments", config["max_pages"]) + gaps = [reason] if reason else [] + events, missing = activity_events([raw] + comments) + gaps.extend(missing) + complete &= not missing reviewers = [] if kind == "pr": for endpoint in ("comments", "reviews"): @@ -140,9 +247,10 @@ def conversation(api, repo, raw, kind, config): complete &= ok if why: gaps.append(why) - events += [(x.get("submitted_at") or x.get("created_at"), x["user"]["login"]) - for x in entries if human(x.get("user")) - and x.get("state") != "PENDING"] + review_events, missing = activity_events(entries) + events.extend(review_events) + gaps.extend(missing) + complete &= not missing try: detail = api.get(f"repos/{repo}/pulls/{number}") reviewers = [x["login"].casefold() for x in detail.get("requested_reviewers", [])] @@ -151,6 +259,9 @@ def conversation(api, repo, raw, kind, config): gaps.append("requested reviewers unavailable") selves = {x.casefold() for x in config["self_logins"]} awaiting, since = waiting(events, selves) if complete else (None, None) + if complete and awaiting is None: + complete = False + gaps.append("activity timestamps unavailable or ordering ambiguous") category = (raw.get("category") or {}).get("name") answered = raw.get("answer_chosen_at") is not None # Preserve the established hub policy; delivery follow-up is separate. @@ -202,12 +313,15 @@ def collect(api, repo_homes, config): for entry in entries: if entry.get("state", "open") != "open" or entry.get("locked"): continue - item_kind = "pr" if entry.get("pull_request") else kind + item_kind = "pr" if "pull_request" in entry else kind is_human = human(entry.get("user")) - if not is_human and item_kind != "pr": + known_bot = isinstance(entry.get("user"), dict) and ( + entry["user"].get("type") == "Bot" or + str(entry["user"].get("login", "")).endswith("[bot]")) + if known_bot and item_kind != "pr": continue external = is_human and entry["user"]["login"].casefold() not in selves - if item_kind == "issue" and not external: + if item_kind == "issue" and is_human and not external: continue try: row = conversation(api, repo, entry, item_kind, config) diff --git a/tests/test_listening.py b/tests/test_listening.py new file mode 100644 index 0000000..bfd7344 --- /dev/null +++ b/tests/test_listening.py @@ -0,0 +1,142 @@ +"""Coverage and ordering regression cases for the public evidence reader.""" +import copy +import json + +import pytest + +from test_ears import API, CONFIG, STAMP, comments, listing, thread, user +from ears import collect + + +def node(identity, login='Reporter', stamp=STAMP, **extra): + return {'id': identity, 'author': {'login': login, '__typename': 'User'}, + 'createdAt': stamp, 'deletedAt': None, **extra} + + +def connection(nodes=(), cursor=None): + return {'nodes': list(nodes), 'pageInfo': {'hasNextPage': cursor is not None, 'endCursor': cursor}} + + +class DiscussionAPI(API): + def __init__(self, graph=None, raw=None, overrides=None): + super().__init__({listing('example/hub', 'discussions'): [raw or thread(category={'name': 'Help & Questions'})], + **(overrides or {})}) + self.graph = graph or {} + self.graph_calls = [] + + def discussion_page(self, repo, number, after=None, comment_id=None): + self.graph_calls.append((comment_id, after)) + value = self.graph.get((comment_id, after), connection()) + if isinstance(value, Exception): + raise value + return copy.deepcopy(value) + + +def discussion(api): + snapshot = collect.collect(api, [], CONFIG) + collect.validate(snapshot) + return snapshot['conversations'][0], snapshot['receipts'][0] + + +def test_all_discussion_comment_and_reply_pages_contribute_to_response_age(): + api = DiscussionAPI({ + (None, None): connection([node('c1', 'Second', '2026-10-02T00:00:00Z')], 'c-page2'), + (None, 'c-page2'): connection([node('c2', 'Reporter', '2026-10-02T05:00:00Z')]), + ('c1', None): connection([node('r1', 'SECOND', '2026-10-02T01:00:00Z')], 'r-page2'), + ('c1', 'r-page2'): connection([node('r2', 'Reporter', '2026-10-02T02:00:00Z')]), + }) + row, receipt = discussion(api) + assert row['coverage'] == receipt['status'] == 'complete' + assert row['awaiting_response'] is True + assert row['waiting_since'] == '2026-10-02T02:00:00+00:00' + assert ('c1', 'r-page2') in api.graph_calls and ('c2', None) in api.graph_calls + assert comments('example/hub', 'discussions') not in api.calls + + +def test_nested_maintainer_reply_settles_response(): + row, _ = discussion(DiscussionAPI({ + (None, None): connection([node('c1', 'Reporter', '2026-10-02T00:00:00Z')]), + ('c1', None): connection([node('r1', 'sEcOnD')]), + })) + assert row['awaiting_response'] is False and row['waiting_since'] is None + + +@pytest.mark.parametrize('failure', [ + collect.ReadError('rate limit'), {'nodes': []}, connection([None]), + connection([node('r1')], 'repeat'), +]) +def test_reply_failure_malformed_or_cap_stays_unknown(failure): + api = DiscussionAPI({(None, None): connection([node('c1')]), + ('c1', None): failure, ('c1', 'repeat'): failure}) + row, receipt = discussion(api) + assert row['coverage'] == receipt['status'] == 'partial' + assert row['awaiting_response'] is None and row['gaps'] + + +@pytest.mark.parametrize('event', [node('c1', author=None), node('c1', deletedAt=STAMP), + node('c1', stamp=None), node('c1', author={'login': 42})]) +def test_deleted_author_or_unknown_time_is_never_checked_clear(event): + row, receipt = discussion(DiscussionAPI({(None, None): connection([event])})) + assert row['awaiting_response'] is None + assert row['coverage'] == receipt['status'] == 'partial' + + +def test_rest_only_fallback_is_explicitly_partial(): + row, _ = discussion(API({listing('example/hub', 'discussions'): [thread()], + comments('example/hub', 'discussions'): [{'user': user('Maintainer'), 'created_at': STAMP}]})) + assert row['awaiting_response'] is None + assert 'Discussion GraphQL adapter unavailable' in row['gaps'] + + +@pytest.mark.parametrize('category,answer', [('Ideas & Proposals', STAMP), ('Announcements', None), ('Show and tell', None)]) +def test_accepted_proposal_or_broadcast_does_not_claim_delivery(category, answer): + row, receipt = discussion(DiscussionAPI(raw=thread(category={'name': category}, answer_chosen_at=answer))) + assert row['awaiting_response'] is False + assert row['coverage'] == receipt['status'] == 'complete' + assert 'delivered' not in row and 'delivery_state' not in row + + +def test_empty_success_is_distinct_from_inaccessible_connection(): + complete, _ = discussion(DiscussionAPI()) + partial, _ = discussion(DiscussionAPI({(None, None): collect.ReadError('not accessible')})) + assert complete['awaiting_response'] is True and complete['coverage'] == 'complete' + assert partial['awaiting_response'] is None and partial['coverage'] == 'partial' + + +def test_unknown_issue_author_remains_visible(): + snapshot = collect.collect(API({listing(): [thread(user=None)]}), ['example/lib'], CONFIG) + assert len(snapshot['conversations']) == 1 + assert snapshot['conversations'][0]['awaiting_response'] is None + + +def test_pr_review_replies_paginate_and_deleted_actor_degrades(): + api = API({listing(): [thread(pull_request={})], + comments(kind='pulls'): [{'user': user('Reporter'), 'created_at': STAMP}] * 100, + comments(kind='pulls', page=2): [{'user': user('Second'), 'created_at': '2026-10-04T00:00:00Z', 'in_reply_to_id': 1}]}) + row = collect.collect(api, ['example/lib'], CONFIG)['conversations'][0] + assert row['awaiting_response'] is False + api.overrides[comments(kind='pulls', page=2)][0]['user'] = None + row = collect.collect(api, ['example/lib'], CONFIG)['conversations'][0] + assert row['awaiting_response'] is None and row['coverage'] == 'partial' + + +def test_graphql_transport_only_fixed_queries_and_no_raw_body(monkeypatch): + calls = [] + def run(args, **kw): + calls.append((args, json.loads(kw['input']))) + return type('Result', (), {'returncode': 0, 'stdout': json.dumps({'data': {'repository': {'discussion': {'comments': connection()}}}})})() + monkeypatch.setattr(collect.subprocess, 'run', run) + assert collect.GitHub().discussion_page('example/hub', 1) == connection() + args, payload = calls[0] + assert args == ['gh', 'api', 'graphql', '--input', '-'] + assert payload['query'] == collect.DISCUSSION_COMMENTS + assert 'body' not in payload['query'] and 'mutation' not in payload['query'] + assert payload['variables'] == {'owner': 'example', 'name': 'hub', 'number': 1} + + +@pytest.mark.parametrize('response', [{'data': {'repository': {'discussion': {'comments': connection()}}}, 'errors': [{'message': 'SECRET'}]}, {'data': {'repository': None}}, []]) +def test_graphql_errors_never_leak_or_count_as_empty_success(monkeypatch, response): + monkeypatch.setattr(collect.subprocess, 'run', lambda *a, **k: type('Result', (), {'returncode': 0, 'stdout': json.dumps(response)})()) + with pytest.raises(collect.ReadError) as exc: + collect.GitHub().discussion_page('example/hub', 1) + assert 'SECRET' not in str(exc.value)