From fb1c7f6ecf5a393fbe5aa447884aa860f71bae37 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:52:51 +0800 Subject: [PATCH] feat(steward): refine stalled PR signal clock, author-reply bypass, and bucket wakeups Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../native_chat/github_pr_evidence.py | 153 ++++++++++++++++- .../capabilities/native_chat/steward_turn.py | 2 +- .../collaboration/steward_managed_mode.ts | 49 +++++- .../steward_managed_mode.test.ts | 155 ++++++++++++++++++ ...test_steward_pr_merge_and_review_signal.py | 153 +++++++++++++++++ 5 files changed, 500 insertions(+), 12 deletions(-) diff --git a/loopx/capabilities/native_chat/github_pr_evidence.py b/loopx/capabilities/native_chat/github_pr_evidence.py index 94834bfdc2..7aafc696ba 100644 --- a/loopx/capabilities/native_chat/github_pr_evidence.py +++ b/loopx/capabilities/native_chat/github_pr_evidence.py @@ -3,6 +3,7 @@ from __future__ import annotations import configparser +from datetime import datetime, timezone import json from pathlib import Path import re @@ -41,6 +42,30 @@ {"FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"} ) _CHECK_PASS_CONCLUSIONS = frozenset({"SUCCESS", "NEUTRAL", "SKIPPED"}) +_KNOWN_BOT_LOGINS = frozenset( + {"mergify", "codecov", "codecov-commenter", "github-actions", "dependabot"} +) + + +def _parse_iso_timestamp(value: Any) -> tuple[datetime, str] | None: + raw = str(value or "").strip() + if not raw: + return None + normalized = f"{raw[:-1]}+00:00" if raw.endswith("Z") else raw + try: + dt = datetime.fromisoformat(normalized) + except ValueError: + return None + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + else: + dt = dt.astimezone(timezone.utc) + return dt, raw + + +def _is_bot_login(login: str) -> bool: + cleaned = str(login or "").strip().casefold() + return not cleaned or cleaned.endswith("[bot]") or cleaned in _KNOWN_BOT_LOGINS def normalize_github_repo_slug(value: Any) -> str | None: @@ -275,6 +300,70 @@ def _actor_actionable_verdict(record: Mapping[str, Any]) -> str | None: return None +def _summarize_request_changes_stall( + row: Mapping[str, Any], + *, + raw_reviews: Sequence[Mapping[str, Any]], + latest_record_by_actor: Mapping[tuple[str, str], tuple[str, dict[str, Any]]], + head_oid: str, + pr_author: str, +) -> tuple[str | None, str | None, bool]: + rc_candidates: list[tuple[datetime, str, dict[str, Any], str]] = [] + for verdict_val, rec in latest_record_by_actor.values(): + if verdict_val != "REQUEST_CHANGES": + continue + parsed = _parse_iso_timestamp(rec.get("submitted_at")) + if parsed is not None: + rc_candidates.append((parsed[0], str(rec.get("id") or ""), rec, parsed[1])) + if not rc_candidates: + return None, None, False + latest_rc_dt, _latest_id, latest_rec, rc_iso = max( + rc_candidates, key=lambda item: (item[0], item[1]) + ) + latest_rc_review_id = latest_rec.get("id") + anchors: list[tuple[datetime, str]] = [(latest_rc_dt, rc_iso)] + for commit_key in ("headCommitPushedAt", "headCommitCommittedAt"): + parsed_commit = _parse_iso_timestamp(row.get(commit_key)) + if parsed_commit is not None: + anchors.append(parsed_commit) + stalled_anchor_dt, stalled_since = max(anchors, key=lambda pair: pair[0]) + + post_replies: list[tuple[datetime, int, str]] = [] + for comment in row.get("comments") or []: + if not isinstance(comment, Mapping): + continue + parsed_ts = _parse_iso_timestamp(comment.get("createdAt") or comment.get("created_at")) + if parsed_ts is None or parsed_ts[0] <= stalled_anchor_dt: + continue + raw_user = comment.get("author") or comment.get("user") or {} + login = str(raw_user.get("login") if isinstance(raw_user, Mapping) else "").strip() + if _is_bot_login(login): + continue + is_author = 1 if (pr_author and login.casefold() == pr_author.casefold()) else 0 + post_replies.append((parsed_ts[0], is_author, login)) + + for review in raw_reviews: + if str(review.get("state") or "").strip().upper() != "COMMENTED": + continue + parsed_ts = _parse_iso_timestamp(review.get("submittedAt") or review.get("submitted_at")) + if parsed_ts is None or parsed_ts[0] <= stalled_anchor_dt: + continue + raw_user = review.get("author") or review.get("user") or {} + login = str(raw_user.get("login") if isinstance(raw_user, Mapping) else "").strip() + if _is_bot_login(login): + continue + if _extract_review_record(review, head_oid=head_oid, pr_author=pr_author)["valid_verdict_review"]: + continue + is_author = 1 if (pr_author and login.casefold() == pr_author.casefold()) else 0 + post_replies.append((parsed_ts[0], is_author, login)) + + post_replies.sort(key=lambda item: (item[0], item[1])) + author_replied = bool( + pr_author and post_replies and post_replies[-1][2].casefold() == pr_author.casefold() + ) + return latest_rc_review_id, stalled_since, author_replied + + def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: """Project compact, deterministic exact-head review, check, and gate facts.""" head_oid = str(row.get("headRefOid") or "").strip() @@ -297,6 +386,7 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: exact_reviews.sort(key=lambda item: (item["submitted_at"] or "", item["id"] or "")) latest_by_actor: dict[tuple[str, str], str | None] = {} + latest_record_by_actor: dict[tuple[str, str], tuple[str, dict[str, Any]]] = {} inconsistent_verdict = False for record in exact_reviews: actionable = _actor_actionable_verdict(record) @@ -308,11 +398,22 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: ) if actionable == "DISMISSED": latest_by_actor.pop(actor_key, None) + latest_record_by_actor.pop(actor_key, None) elif actionable == "CONFLICT": inconsistent_verdict = True latest_by_actor[actor_key] = "REQUEST_CHANGES" + latest_record_by_actor[actor_key] = ("REQUEST_CHANGES", record) else: latest_by_actor[actor_key] = actionable + latest_record_by_actor[actor_key] = (actionable, record) + + latest_rc_review_id, stalled_since, author_replied_after_rc = _summarize_request_changes_stall( + row, + raw_reviews=raw_reviews, + latest_record_by_actor=latest_record_by_actor, + head_oid=head_oid, + pr_author=pr_author, + ) verdicts = {val for val in latest_by_actor.values() if val} review_decision = str(row.get("reviewDecision") or "").strip().upper() @@ -363,11 +464,16 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: "mergeStateStatus": row.get("mergeStateStatus"), "mergeable": row.get("mergeable"), "updatedAt": row.get("updatedAt"), + "stalled_since": stalled_since, + "author_replied_after_request_changes": author_replied_after_rc, "checks_summary": checks_summary, "review_summary": { "effective_verdict": effective_verdict, "has_review_conflict": has_conflict, "stale_review_count": stale_count, + "latest_request_changes_review_id": latest_rc_review_id, + "stalled_since": stalled_since, + "author_replied_after_request_changes": author_replied_after_rc, "exact_head_reviews": exact_reviews, }, "bypassed_gates": bypassed_gates, @@ -409,6 +515,14 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: author { login } + comments(last: 20) { + nodes { + createdAt + author { + login + } + } + } reviews(last: 20) { nodes { id @@ -426,6 +540,9 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: commits(last: 1) { nodes { commit { + oid + committedDate + pushedDate statusCheckRollup { contexts(first: 30) { nodes { @@ -460,15 +577,34 @@ def _normalize_graphql_pr_node(node: Mapping[str, Any]) -> dict[str, Any]: else: reviews = [] + raw_comments = node.get("comments") + if isinstance(raw_comments, Mapping) and isinstance(raw_comments.get("nodes"), list): + comments = [item for item in raw_comments["nodes"] if isinstance(item, Mapping)] + elif isinstance(raw_comments, list): + comments = [item for item in raw_comments if isinstance(item, Mapping)] + else: + comments = [] + + raw_commits = node.get("commits") + commit_nodes = raw_commits.get("nodes") if isinstance(raw_commits, Mapping) else None + first_commit = ( + commit_nodes[0].get("commit") + if isinstance(commit_nodes, list) and commit_nodes and isinstance(commit_nodes[0], Mapping) + else None + ) + head_oid = str(node.get("headRefOid") or "").strip() + head_committed_at = node.get("headCommitCommittedAt") + head_pushed_at = node.get("headCommitPushedAt") + if isinstance(first_commit, Mapping): + commit_oid = str(first_commit.get("oid") or "").strip() + if not commit_oid or not head_oid or commit_oid.casefold() == head_oid.casefold(): + if head_committed_at is None: + head_committed_at = first_commit.get("committedDate") + if head_pushed_at is None: + head_pushed_at = first_commit.get("pushedDate") + rollup = node.get("statusCheckRollup") if rollup is None: - raw_commits = node.get("commits") - commit_nodes = raw_commits.get("nodes") if isinstance(raw_commits, Mapping) else None - first_commit = ( - commit_nodes[0].get("commit") - if isinstance(commit_nodes, list) and commit_nodes and isinstance(commit_nodes[0], Mapping) - else None - ) raw_rollup = first_commit.get("statusCheckRollup") if isinstance(first_commit, Mapping) else None raw_contexts = raw_rollup.get("contexts") if isinstance(raw_rollup, Mapping) else None context_nodes = raw_contexts.get("nodes") if isinstance(raw_contexts, Mapping) else None @@ -487,6 +623,9 @@ def _normalize_graphql_pr_node(node: Mapping[str, Any]) -> dict[str, Any]: "mergeStateStatus": node.get("mergeStateStatus"), "mergeable": node.get("mergeable"), "updatedAt": node.get("updatedAt"), + "headCommitCommittedAt": head_committed_at, + "headCommitPushedAt": head_pushed_at, + "comments": comments, "reviews": reviews, "statusCheckRollup": rollup, } diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py index 900e993e7e..2662706298 100644 --- a/loopx/capabilities/native_chat/steward_turn.py +++ b/loopx/capabilities/native_chat/steward_turn.py @@ -1588,7 +1588,7 @@ def run(native_request: Mapping[str, Any], launch_scope: Any) -> dict[str, Any]: followup_ctx = self._steward_followup_context(actor, session_id, request, authority) prompt += ( "\nSteward advancement instructions: Evaluate the monitor prompt and signal snapshot against authorized recipients (`context_delegation.targets`), prior receipts (`prior_handoff_receipts`, avoid duplicate delivery for unchanged PR@headRefOid), and open user todos (`open_user_todos`). " - "When `signal_snapshot.repository_snapshot.items` is present, each PR carries `mergeable`, `checks_summary`, `bypassed_gates`, and `review_summary` (`effective_verdict`, `has_review_conflict`, `stale_review_count`, `exact_head_reviews` with `reviewer_declaration`, `valid_verdict_review`, `author_owned_fallback`). Keep triage read-only; never execute merges here. " + "When `signal_snapshot.repository_snapshot.items` is present, each PR carries `mergeable`, `checks_summary`, `bypassed_gates`, `stalled_since`, `author_replied_after_request_changes`, optional `stalled_bucket` (`awaiting_maintainer_reply` | `24h_to_72h` | `72h_plus` | `7d_plus`), and `review_summary` (`effective_verdict`, `has_review_conflict`, `stale_review_count`, `latest_request_changes_review_id`, `stalled_since`, `author_replied_after_request_changes`, `exact_head_reviews` with `reviewer_declaration`, `valid_verdict_review`, `author_owned_fallback`). Keep triage read-only; never execute merges here. " "You may include optional top-level JSON fields alongside the normal kernel fields: " "`context_handoff` (single object or array <=32 of {goal_id, agent_id, brief} with `schema_version='collaboration_brief_v0'` and `inputs=[]` when referencing URLs/PRs, restricted to `context_delegation.targets`), " "`steward_owner_report` (optional non-empty Markdown string <=24000 chars or `{markdown}` delivered once directly to the bound Steward App and Feishu conversation; omit or set `null` when silent/no report should be sent), " diff --git a/loopx/control_plane/collaboration/steward_managed_mode.ts b/loopx/control_plane/collaboration/steward_managed_mode.ts index fe40887e83..fa9ba4c6c7 100644 --- a/loopx/control_plane/collaboration/steward_managed_mode.ts +++ b/loopx/control_plane/collaboration/steward_managed_mode.ts @@ -986,6 +986,13 @@ function hasMatchingApprovedReviewerDeclaration(item: JsonObject, requiredTokens ); } +function classifyStalledBucket(stalledAgeMs: number, authorReplyBypass: boolean): string { + if (authorReplyBypass) return "awaiting_maintainer_reply"; + if (stalledAgeMs >= 168 * 3_600_000) return "7d_plus"; + if (stalledAgeMs >= 72 * 3_600_000) return "72h_plus"; + return "24h_to_72h"; +} + function filterScopedRepositoryItems( rawItems: unknown[], filter: JsonObject | null, @@ -1033,11 +1040,35 @@ function filterScopedRepositoryItems( if (authorMode === "exclude" && login && authors.has(login)) continue; } if (minStalledHours !== null) { - const updatedMs = typeof item.updatedAt === "string" ? Date.parse(item.updatedAt) : NaN; - if (!Number.isFinite(updatedMs) || observedAtMs - updatedMs < minStalledHours * 3_600_000) { + const authorReplied = item.author_replied_after_request_changes === true + || reviewSummary?.author_replied_after_request_changes === true; + const hasExplicitStalledSince = Object.prototype.hasOwnProperty.call(item, "stalled_since") + || (reviewSummary !== null && Object.prototype.hasOwnProperty.call(reviewSummary, "stalled_since")); + const rawStalledSince = typeof item.stalled_since === "string" + ? item.stalled_since + : (typeof reviewSummary?.stalled_since === "string" ? reviewSummary.stalled_since : null); + if ( + hasExplicitStalledSince + && rawStalledSince === null + && effectiveVerdicts !== null + && effectiveVerdicts.size === 1 + && effectiveVerdicts.has("REQUEST_CHANGES") + ) { continue; } - matched.push({ ...item, stalled_threshold_met: true }); + const basisIso = rawStalledSince ?? (typeof item.updatedAt === "string" ? item.updatedAt : null); + const basisMs = basisIso !== null ? Date.parse(basisIso) : NaN; + const authorReplyBypass = authorReplied && authorMode === "exclude"; + const thresholdMet = Number.isFinite(basisMs) && observedAtMs - basisMs >= minStalledHours * 3_600_000; + if (!authorReplyBypass && !thresholdMet) { + continue; + } + const stalledAgeMs = Number.isFinite(basisMs) ? Math.max(0, observedAtMs - basisMs) : 0; + matched.push({ + ...item, + stalled_threshold_met: thresholdMet, + stalled_bucket: classifyStalledBucket(stalledAgeMs, authorReplyBypass), + }); } else { matched.push(item); } @@ -1073,6 +1104,16 @@ export function observeStewardSignalMonitor(params: JsonObject): JsonObject { params.observed_at ?? repo?.observed_at, ) : null; + const hashedRepoItems = signalScope !== null && scopedRepoItems !== null + ? scopedRepoItems.map((item) => { + const reviewSummary = jsonObject(item.review_summary); + const hasStalledSinceClock = typeof item.stalled_since === "string" + || typeof reviewSummary?.stalled_since === "string"; + if (!hasStalledSinceClock) return item; + const { updatedAt: _ignoredUpdatedAt, ...rest } = item; + return rest; + }) + : rawRepoItems; const includePortfolio = signalScope === null ? true : signalScope.include_portfolio === true; const includeInbox = signalScope === null ? true : signalScope.include_inbox === true; const facts = signalScope === null @@ -1085,7 +1126,7 @@ export function observeStewardSignalMonitor(params: JsonObject): JsonObject { signal_scope: signalScope, portfolio_hash: includePortfolio ? (portfolio?.result_hash ?? null) : null, inbox_items: includeInbox ? inboxItems : [], - repository_items: scopedRepoItems, + repository_items: hashedRepoItems, }; const clocks = new Set(["snapshot_id", "portfolio_snapshot_id", "collected_at", "collection_completed_at", "generated_at", "evaluated_at", "age_seconds", "observed_at"]); diff --git a/tests/control_plane_ts/steward_managed_mode.test.ts b/tests/control_plane_ts/steward_managed_mode.test.ts index 538ec92d2b..939201418e 100644 --- a/tests/control_plane_ts/steward_managed_mode.test.ts +++ b/tests/control_plane_ts/steward_managed_mode.test.ts @@ -671,3 +671,158 @@ test("observeStewardSignalMonitor preserves feature-off parity and isolates scop repository_snapshot: sampleRepo, })); }); + +test("observeStewardSignalMonitor uses stalled_since, author-reply bypass, and stalled_bucket wakeups", () => { + const stalledInternalScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "include", + authors: ["alice"], + min_stalled_hours: 24, + }, + }; + const stalledExternalScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "exclude", + authors: ["alice"], + min_stalled_hours: 24, + }, + }; + + const makeRepo = (botUpdatedAt: string) => ({ + status: "ok", + repository: "acme/widgets", + items: [ + { + number: 201, + title: "Internal RC with Mergify bot ping", + isDraft: false, + mergeable: "MERGEABLE", + author: {login: "alice"}, + updatedAt: botUpdatedAt, + stalled_since: "2026-11-20T09:00:00Z", + author_replied_after_request_changes: false, + review_summary: { + effective_verdict: "REQUEST_CHANGES", + has_review_conflict: false, + latest_request_changes_review_id: "PRR_201", + stalled_since: "2026-11-20T09:00:00Z", + author_replied_after_request_changes: false, + exact_head_reviews: [], + }, + }, + { + number: 202, + title: "External author replied right after RC", + isDraft: false, + mergeable: "MERGEABLE", + author: {login: "ext-user"}, + updatedAt: "2026-11-21T08:30:00Z", + stalled_since: "2026-11-21T07:00:00Z", + author_replied_after_request_changes: true, + review_summary: { + effective_verdict: "REQUEST_CHANGES", + has_review_conflict: false, + latest_request_changes_review_id: "PRR_202", + stalled_since: "2026-11-21T07:00:00Z", + author_replied_after_request_changes: true, + exact_head_reviews: [], + }, + }, + { + number: 203, + title: "Stale RC on previous commit after new head push", + isDraft: false, + mergeable: "MERGEABLE", + author: {login: "ext-user"}, + updatedAt: "2026-11-18T00:00:00Z", + stalled_since: null, + author_replied_after_request_changes: false, + review_summary: { + effective_verdict: "REQUEST_CHANGES", + has_review_conflict: false, + latest_request_changes_review_id: null, + stalled_since: null, + author_replied_after_request_changes: false, + exact_head_reviews: [], + }, + }, + ], + }); + + // At 23h since stalled_since (2026-11-20T09:00 -> 2026-11-21T08:00), PR #201 is excluded even with newer updatedAt. + const before24h = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + repository_snapshot: makeRepo("2026-11-21T08:30:00Z"), + observed_at: "2026-11-21T08:00:00Z", + }); + assert.deepEqual(before24h.scoped_repository_items, []); + + // At 24h exact (2026-11-21T09:00), PR #201 enters 24h_to_72h bucket. + const at24h = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: before24h.result_hash, + repository_snapshot: makeRepo("2026-11-21T08:30:00Z"), + observed_at: "2026-11-21T09:00:00Z", + }); + assert.equal(at24h.material_change, true); + assert.equal(at24h.scoped_repository_items[0].number, 201); + assert.equal(at24h.scoped_repository_items[0].stalled_threshold_met, true); + assert.equal(at24h.scoped_repository_items[0].stalled_bucket, "24h_to_72h"); + + // Bot comment bumping updatedAt at 71h produces zero hash change in the same bucket. + const at71hBotBump = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: at24h.result_hash, + repository_snapshot: makeRepo("2026-11-23T07:55:00Z"), + observed_at: "2026-11-23T08:00:00Z", + }); + assert.equal(at71hBotBump.result_hash, at24h.result_hash); + assert.equal(at71hBotBump.material_change, false); + + // Crossing into 72h_plus and 7d_plus wakes the monitor exactly at bucket boundaries. + const at72h = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: at71hBotBump.result_hash, + repository_snapshot: makeRepo("2026-11-23T07:55:00Z"), + observed_at: "2026-11-23T09:00:00Z", + }); + assert.equal(at72h.material_change, true); + assert.equal(at72h.scoped_repository_items[0].stalled_bucket, "72h_plus"); + + const at73h = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: at72h.result_hash, + repository_snapshot: makeRepo("2026-11-23T07:55:00Z"), + observed_at: "2026-11-23T10:00:00Z", + }); + assert.equal(at73h.material_change, false); + + const at7d = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: at73h.result_hash, + repository_snapshot: makeRepo("2026-11-23T07:55:00Z"), + observed_at: "2026-11-27T09:00:00Z", + }); + assert.equal(at7d.material_change, true); + assert.equal(at7d.scoped_repository_items[0].stalled_bucket, "7d_plus"); + + // External monitor prioritizes awaiting_maintainer_reply immediately (<24h) and drops stale-commit RC (#203). + const externalObs = observeStewardSignalMonitor({ + signal_scope: stalledExternalScope, + repository_snapshot: makeRepo("2026-11-21T08:30:00Z"), + observed_at: "2026-11-21T09:00:00Z", + }); + assert.deepEqual(externalObs.scoped_repository_items.map((row: {number: number}) => row.number), [202]); + assert.equal(externalObs.scoped_repository_items[0].stalled_threshold_met, false); + assert.equal(externalObs.scoped_repository_items[0].stalled_bucket, "awaiting_maintainer_reply"); +}); diff --git a/tests/test_steward_pr_merge_and_review_signal.py b/tests/test_steward_pr_merge_and_review_signal.py index 0d216334da..a2df571bdc 100644 --- a/tests/test_steward_pr_merge_and_review_signal.py +++ b/tests/test_steward_pr_merge_and_review_signal.py @@ -562,3 +562,156 @@ def fake_gh(cmd, **_kwargs): assert recovered["status"] == "applied" assert recovered["receipt"]["outcome"] == "pr_merged_recovered" assert recovered["receipt"]["resource_ids"]["merge_commit_oid"] == "9" * 40 + + +def test_summarize_pr_stalled_since_and_author_reply_detection(monkeypatch) -> None: + head = "e" * 40 + old = "0" * 40 + gpt_decl = "model_agent · gpt-6.2-sol · OpenAI (runtime_reported, max)" + + # Mergify bot comment bumps updatedAt without resetting stalled_since or flagging author reply. + bot_bumped = summarize_github_pr_signal( + { + **_sample_pr( + number=301, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc1", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + ], + ), + "updatedAt": "2030-01-02T00:00:00Z", + "comments": [ + {"createdAt": "2030-01-01T09:00:00Z", "author": {"login": "mergify[bot]"}}, + ], + } + ) + assert bot_bumped["stalled_since"] == "2030-01-01T08:00:00Z" + assert bot_bumped["author_replied_after_request_changes"] is False + assert bot_bumped["review_summary"]["latest_request_changes_review_id"] == "PRR_rc1" + + # External author replies after REQUEST_CHANGES -> awaiting maintainer reply; maintainer reply resets it. + author_replied = summarize_github_pr_signal( + { + **_sample_pr( + number=302, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc2", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + ], + ), + "comments": [ + {"createdAt": "2030-01-01T10:00:00Z", "author": {"login": "ext-contributor"}}, + {"createdAt": "2030-01-01T10:30:00Z", "author": {"login": "mergify[bot]"}}, + ], + } + ) + assert author_replied["author_replied_after_request_changes"] is True + + maintainer_replied = summarize_github_pr_signal( + { + **_sample_pr( + number=302, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc2", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + }, + { + "id": "PRR_reply", + "author": {"login": "maintainer"}, + "state": "COMMENTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T11:00:00Z", + "body": "Please keep the existing state field unchanged.", + }, + ], + ), + "comments": [ + {"createdAt": "2030-01-01T10:00:00Z", "author": {"login": "ext-contributor"}}, + ], + } + ) + assert maintainer_replied["author_replied_after_request_changes"] is False + + # Stale-commit CHANGES_REQUESTED after new head commit push leaves stalled_since as None. + stale_after_push = summarize_github_pr_signal( + _sample_pr( + number=303, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_stale_rc", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": old}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=old, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + ], + ) + ) + assert stale_after_push["stalled_since"] is None + assert stale_after_push["review_summary"]["latest_request_changes_review_id"] is None + assert stale_after_push["author_replied_after_request_changes"] is False + + # GraphQL page normalization retains comments and head commit pushedDate. + gql_node = _graphql_node( + _sample_pr( + number=304, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc4", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + ], + ) + ) + gql_node["comments"] = {"nodes": [{"createdAt": "2030-01-01T12:00:00Z", "author": {"login": "ext-contributor"}}]} + gql_node["commits"]["nodes"][0]["commit"]["oid"] = head + gql_node["commits"]["nodes"][0]["commit"]["committedDate"] = "2030-01-01T07:00:00Z" + gql_node["commits"]["nodes"][0]["commit"]["pushedDate"] = "2030-01-01T09:00:00Z" + + def fake_gql(cmd, **_kwargs): + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([gql_node])), stderr="") + + monkeypatch.setattr("loopx.capabilities.native_chat.steward_monitor.subprocess.run", fake_gql) + observed = _observe_github_repository_prs("org/repo") + assert observed["status"] == "ok" + item = observed["items"][0] + assert item["stalled_since"] == "2030-01-01T09:00:00Z" + assert item["author_replied_after_request_changes"] is True + assert item["review_summary"]["latest_request_changes_review_id"] == "PRR_rc4"