diff --git a/REFERENCE.md b/REFERENCE.md index 04b1e86..c1f54d7 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -256,3 +256,22 @@ the acting account's permission or refer it to a maintainer; never infer the commenter's permissions from the collector token. Reopening, unlocking and clearing an answer are separate, explicitly authorized actions. Ears performs none of them. Stale/cached evidence must be refreshed before acting. + +## Waiting on the contributor (optional snapshot v1 extension) + +An open issue or unsettled Discussion (not answered) carries two optional fields +when the policy in Mind's `policy/community_close_due.md` can apply: the thread +is not a PR, not in a broadcast category, not locked, and was opened by an +external human. `awaiting_contributor_since` is the timestamp of our latest +comment when it is the latest human message on the thread (nested replies +included); otherwise it is null. Bot comments never reset the clock. `close_due` +is true when collection time minus that timestamp is 21 days or more (the exact +boundary is due), false when it is less or when nobody is waiting on the +contributor, and null when coverage is incomplete. Null is unknown, never +"not due". + +Rows where the policy cannot apply omit both fields, and readers accept +snapshots without them. Ears only observes: it never posts the close message +or closes a thread. Brain's Community conductor lists due threads with the +standard message, and the human approves each batch before anything is posted. +The board shows a quiet "Close due" response label. diff --git a/ears/collect.py b/ears/collect.py index 6254d9a..3a11c71 100644 --- a/ears/collect.py +++ b/ears/collect.py @@ -10,6 +10,9 @@ REPO = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\Z") BROADCAST = {"Announcements", "Show and tell"} FOLLOW_UP_WINDOW = timedelta(days=30) +# Mind policy/community_close_due.md: a thread waiting on its contributor this +# long is due for the standard close message. The exact boundary is due. +CLOSE_DUE_AFTER = timedelta(days=21) DISCUSSION_COMMENTS = """query($owner:String!, $name:String!, $number:Int!, $after:String) { repository(owner:$owner, name:$name) { discussion(number:$number) { comments(first:100, after:$after) { @@ -290,6 +293,63 @@ def follow_up(raw, comments, kind, selves, complete, url): return unknown +def awaiting_contributor(comments, selves): + """Time of our comment when it is the latest human (non-bot) message, else None. + + The opening post counts as a message, so a fresh thread is never waiting on + its own author. + + Bot comments never reset the clock. A tie between us and someone else at + the latest time is not a wait on the contributor. + """ + events, _ = activity_events(comments) + if not events: + return None + timed = [(utc(t), who.casefold()) for t, who in events] + latest = max(t for t, _ in timed) + actors = {who for t, who in timed if t == latest} + return latest.isoformat() if actors <= selves else None + + +def close_due_fields(raw, comments, kind, category, settled, selves, complete, observed_at): + """Optional close-due observation; omitted where the policy never applies.""" + author = raw.get("user") + if kind == "pr" or settled or category in BROADCAST or raw.get("locked") \ + or not human(author) or author["login"].casefold() in selves: + return {} + if not complete: + return {"awaiting_contributor_since": None, "close_due": None} + try: + since = awaiting_contributor([raw] + comments, selves) + due = since is not None and utc(observed_at or now()) - utc(since) >= CLOSE_DUE_AFTER + except (ValueError, TypeError): + return {"awaiting_contributor_since": None, "close_due": None} + return {"awaiting_contributor_since": since, "close_due": due} + + +def validate_close_due(row, generated): + if "close_due" not in row and "awaiting_contributor_since" not in row: + return + if "close_due" not in row or "awaiting_contributor_since" not in row: + raise ValueError("incomplete close-due observation") + due, since = row["close_due"], row["awaiting_contributor_since"] + if row["kind"] not in {"issue", "discussion"} or row.get("closed") or row["answered"] \ + or row["category"] in BROADCAST or "follow_up" in row: + raise ValueError("close-due observation on a settled or ineligible thread") + if due is None: + if since is not None: + raise ValueError("unknown close-due carries a timestamp") + return + if type(due) is not bool: + raise ValueError("invalid close-due evidence") + if since is None: + if due: + raise ValueError("close-due lacks a timestamp") + return + if row["coverage"] != "complete" or row["awaiting_response"] is not False or due != (utc(generated) - utc(since) >= CLOSE_DUE_AFTER): + raise ValueError("inconsistent close-due evidence") + + def validate_follow_up(row): if "follow_up" not in row: return @@ -389,6 +449,8 @@ def conversation(api, repo, raw, kind, config, deliveries=None, pending=None, ob gaps.append("post-settlement activity or settlement time unknown") elif kind == "discussion" and (category in BROADCAST or raw.get("locked")): awaiting, since = False, None + close = close_due_fields(raw, comments, kind, category, settled, selves, + complete and awaiting is not None, observed_at) if kind == "discussion" and deliveries is not None: from .followthrough import derive deliveries.append(derive(api, f"https://github.com/{repo}/discussions/{number}", @@ -410,6 +472,7 @@ def conversation(api, repo, raw, kind, config, deliveries=None, pending=None, ob "feedback_report": "" in (raw.get("body") or ""), **({"follow_up": observation} if observation is not None else {}), **({"historical_follow_up_at": historical_follow_up_at} if historical_follow_up_at else {}), + **close, } @@ -531,7 +594,8 @@ def validate(snapshot): for row in rows: if not isinstance(row, dict): raise ValueError("invalid conversation") - if set(row) - {"closed", "follow_up", "created_at", "updated_at", "historical_follow_up_at"} != {"id", "repo", "number", "kind", "url", "title", "author", "category", "answered", + if set(row) - {"closed", "follow_up", "created_at", "updated_at", "historical_follow_up_at", + "awaiting_contributor_since", "close_due"} != {"id", "repo", "number", "kind", "url", "title", "author", "category", "answered", "awaiting_response", "waiting_since", "review_requested", "coverage", "gaps", "cached", "feedback_report"}: raise ValueError("unknown conversation fields; raw content must not be published") if "closed" in row and type(row["closed"]) is not bool: @@ -549,6 +613,7 @@ def validate(snapshot): raise ValueError("invalid or duplicate conversation identity/link") ids.add(identity) validate_follow_up(row) + validate_close_due(row, snapshot["generated"]) if "historical_follow_up_at" in row: historical = utc(row["historical_follow_up_at"]) if row.get("follow_up") != {"review_needed": False, "since": None, "url": None} \ diff --git a/ears/presentation.py b/ears/presentation.py index bc792bb..81ae57f 100644 --- a/ears/presentation.py +++ b/ears/presentation.py @@ -126,6 +126,8 @@ def waiting_label(row, observed): return 'Closed' if row['answered']: return 'Answered' + if row.get('close_due') is True: + return 'Close due' return 'Watching' diff --git a/tests/test_close_due.py b/tests/test_close_due.py new file mode 100644 index 0000000..8bb244b --- /dev/null +++ b/tests/test_close_due.py @@ -0,0 +1,125 @@ +"""Threads waiting on their contributor for 21 days are due for the close message.""" +import copy + +import pytest + +from test_ears import API, CONFIG, STAMP, comments, listing, thread, user +from test_listening import DiscussionAPI, connection, discussion, node +from ears import board, collect +from test_ears import BRAIN + +EXACT = '2026-09-12T12:00:00Z' # exactly 21 days before STAMP +INSIDE = '2026-09-12T12:00:01Z' # one second short of 21 days +EARLY = '2026-09-01T00:00:00Z' + + +@pytest.fixture(autouse=True) +def fixed_collection_time(monkeypatch): + monkeypatch.setattr(collect, 'now', lambda: STAMP) + + +def issue_row(activity, **raw): + api = API({listing(): [thread(created_at='2026-08-30T00:00:00Z', **raw)], comments(): activity}) + snapshot = collect.collect(api, ['example/lib'], CONFIG) + collect.validate(snapshot) + return snapshot['conversations'][0], snapshot + + +def said(login, stamp, bot=False): + return {'user': {'login': login, 'type': 'Bot' if bot else 'User'}, 'created_at': stamp} + + +@pytest.mark.parametrize('stamp, due', [(EXACT, True), (INSIDE, False)]) +def test_boundary_at_exactly_21_days_is_due(stamp, due): + row, _ = issue_row([said('Reporter', EARLY), said('Maintainer', stamp)]) + assert row['awaiting_response'] is False + assert row['awaiting_contributor_since'] == collect.utc(stamp).isoformat() + assert row['close_due'] is due + + +def test_bot_comment_after_ours_does_not_reset_the_clock(): + row, _ = issue_row([said('Reporter', EARLY), said('Maintainer', EXACT), + said('stale[bot]', '2026-10-01T00:00:00Z', bot=True)]) + assert row['close_due'] is True + assert row['awaiting_contributor_since'] == '2026-09-12T12:00:00+00:00' + + +def test_external_reply_after_ours_means_we_owe_the_reply(): + row, _ = issue_row([said('Maintainer', EARLY), said('Reporter', EXACT)]) + assert row['awaiting_response'] is True + assert row['awaiting_contributor_since'] is None and row['close_due'] is False + + +def test_thread_with_no_comments_is_not_awaiting_the_contributor(): + row, _ = issue_row([]) + assert row['awaiting_contributor_since'] is None and row['close_due'] is False + + +def test_incomplete_coverage_gives_null(): + row, snapshot = issue_row([said('Reporter', EARLY), {'user': None, 'created_at': EXACT}, + said('Maintainer', EXACT)]) + assert row['coverage'] == 'partial' + assert row['awaiting_contributor_since'] is None and row['close_due'] is None + + +def test_nested_maintainer_reply_on_open_discussion_is_due(): + raw = thread(category={'name': 'Help & Questions'}, created_at='2026-08-30T00:00:00Z') + row, _ = discussion(DiscussionAPI({ + (None, None): connection([node('c1', 'Reporter', EARLY)]), + ('c1', None): connection([node('r1', 'Second', EXACT)]), + }, raw=raw)) + assert row['kind'] == 'discussion' and row['close_due'] is True + + +@pytest.mark.parametrize('variant', ['answered', 'broadcast', 'locked', 'own_thread']) +def test_settled_or_ineligible_discussions_carry_no_close_due(variant): + raw = thread(category={'name': 'Help & Questions'}, created_at='2026-08-30T00:00:00Z') + if variant == 'answered': + raw['answer_chosen_at'] = EARLY + if variant == 'broadcast': + raw['category'] = {'name': 'Announcements'} + if variant == 'locked': + raw['locked'] = True + if variant == 'own_thread': + raw['user'] = user('Maintainer') + row, _ = discussion(DiscussionAPI({(None, None): connection([node('c1', 'Maintainer', EXACT)])}, raw=raw)) + assert 'close_due' not in row and 'awaiting_contributor_since' not in row + + +def test_pull_requests_carry_no_close_due(): + row, _ = issue_row([said('Maintainer', EXACT)], pull_request={}) + assert row['kind'] == 'pr' and 'close_due' not in row + + +@pytest.mark.parametrize('mutation', [ + lambda r: r.update(close_due=False), # disagrees with the clock + lambda r: r.update(awaiting_contributor_since=INSIDE), # too recent to be due + lambda r: r.update(closed=True), # settled thread + lambda r: r.update(close_due=None), # null with a timestamp + lambda r: r.update(close_due='yes'), + lambda r: r.update(coverage='partial', awaiting_response=None), + lambda r: r.pop('awaiting_contributor_since'), + lambda r: r.update(awaiting_response=True, waiting_since=EXACT), +]) +def test_validation_rejects_inconsistent_close_due(mutation): + _, snapshot = issue_row([said('Reporter', EARLY), said('Maintainer', EXACT)]) + bad = copy.deepcopy(snapshot) + mutation(bad['conversations'][0]) + with pytest.raises(ValueError): + collect.validate(bad) + + +def test_old_snapshots_without_the_fields_remain_valid(): + _, snapshot = issue_row([said('Reporter', EARLY), said('Maintainer', EXACT)]) + for key in ('close_due', 'awaiting_contributor_since'): + snapshot['conversations'][0].pop(key) + collect.validate(snapshot) + + +def test_board_shows_a_quiet_close_due_label_and_valid_state(): + import json + _, snapshot = issue_row([said('Reporter', EARLY), said('Maintainer', EXACT)]) + result = board.render(snapshot, CONFIG, BRAIN, rendered_at=STAMP) + assert 'Close due' in result['index.html'] + state = json.loads(result['state.json']) + assert not board.presentation(BRAIN)[1].validate_state(state)