Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
c0d0d79
fix(steward): reject incomplete open PR pagination
hhyykk Nov 27, 2026
80cab8f
fix(steward): reject unidentifiable PR nodes in snapshots
hhyykk Nov 27, 2026
f04c236
fix(steward): check open PR count across GraphQL pages
hhyykk Nov 27, 2026
9f4df8a
fix(steward): adapt bounded scan for larger PR queues
hhyykk Nov 27, 2026
d8a1866
fix(steward): share one deadline across PR evidence reads
hhyykk Nov 27, 2026
0cce87a
fix(steward): target comment backfill to the monitor scope
hhyykk Nov 27, 2026
a49054c
fix(steward): apply firm age thresholds before comment coverage
hhyykk Nov 27, 2026
11ad88b
fix(steward): verify older comment pagination flags
hhyykk Nov 27, 2026
3b9efbd
fix(steward): reject unreadable comment coverage
hhyykk Nov 27, 2026
3ede75d
fix(steward): preserve uncertainty for unidentified replies
hhyykk Nov 27, 2026
3b8b17d
fix(steward): preserve uncertainty when PR creator is missing
hhyykk Nov 27, 2026
c922884
fix(steward): preserve uncertain author-scope membership
hhyykk Nov 27, 2026
72d9dcf
fix(steward): reject unreadable repository item lists
hhyykk Nov 27, 2026
248527f
fix(steward): reject unreadable repository PR rows
hhyykk Nov 27, 2026
6ac3659
fix(steward): preserve unknown stalled PR age
hhyykk Nov 27, 2026
56d029a
fix(steward): preserve ambiguous reply timing
hhyykk Nov 27, 2026
a3a73c9
fix(steward): gate review scopes on complete review evidence
hhyykk Nov 27, 2026
6c6b714
fix(steward): recover older review pages within the scan budget
hhyykk Nov 27, 2026
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
525 changes: 377 additions & 148 deletions loopx/capabilities/native_chat/github_pr_evidence.py

Large diffs are not rendered by default.

14 changes: 11 additions & 3 deletions loopx/capabilities/native_chat/steward_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from __future__ import annotations

from collections.abc import Mapping, Sequence
from collections.abc import Callable, Mapping, Sequence
import subprocess as subprocess

from ...control_plane.scheduler.monitor_todo import monitor_todo_is_due
Expand Down Expand Up @@ -64,11 +64,19 @@


def _observe_github_repository_prs(
repo_slug: str, *, backfill_comments: bool = False
repo_slug: str,
*,
backfill_comments: bool = False,
select_comment_backfill: Callable[[Sequence[Mapping[str, object]], float], set[int]] | None = None,
select_review_backfill: Callable[[Sequence[Mapping[str, object]], float], set[int]] | None = None,
) -> dict[str, object]:
"""Read bounded public/authorized open PR signal metadata without side effects."""
raw = observe_github_repository_prs(
repo_slug, runner=subprocess.run, backfill_comments=backfill_comments
repo_slug,
runner=subprocess.run,
backfill_comments=backfill_comments,
select_comment_backfill=select_comment_backfill,
select_review_backfill=select_review_backfill,
)
return _coerce_dict(raw)

Expand Down
32 changes: 27 additions & 5 deletions loopx/capabilities/native_chat/steward_monitor_signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from __future__ import annotations

from collections.abc import Callable, Mapping, Sequence
from datetime import timedelta
from functools import partial
import inspect
import math
from pathlib import Path
Expand Down Expand Up @@ -91,14 +93,34 @@ def _read_repository_snapshot(
todo: Mapping[str, object],
signal_scope: Mapping[str, object] | None,
observe_github_prs: Callable[..., dict[str, object]],
core: Callable[[str, Mapping[str, object]], Mapping[str, object]],
) -> dict[str, object] | None:
repo_slug = _github_repo_slug(todo.get("task_repository"))
if not repo_slug:
return None
backfill_comments = _signal_scope_uses_stalled_age(signal_scope)
if backfill_comments and _accepts_backfill_comments(observe_github_prs):
return observe_github_prs(repo_slug, backfill_comments=True)
return observe_github_prs(repo_slug)
if signal_scope is None:
return observe_github_prs(repo_slug)

def select_backfill(source: str, items: Sequence[Mapping[str, object]], remaining_seconds: float) -> set[int]:
latest_observation = now_utc() + timedelta(milliseconds=math.ceil(remaining_seconds * 1000))
planned = core(f"collaboration.steward.monitor.{source}_backfill.plan", {
"signal_scope": signal_scope,
"repository_items": items,
"observed_at": latest_observation.isoformat(),
}).get("pr_numbers")
if not isinstance(planned, list) or any(type(number) is not int or number <= 0 for number in planned):
raise TypeError(f"invalid Steward {source} backfill plan")
return set(planned)

parameters = inspect.signature(observe_github_prs).parameters
options: dict[str, object] = {}
if "select_review_backfill" in parameters:
options["select_review_backfill"] = partial(select_backfill, "review")
if _signal_scope_uses_stalled_age(signal_scope) and _accepts_backfill_comments(observe_github_prs):
options["backfill_comments"] = True
if "select_comment_backfill" in parameters:
options["select_comment_backfill"] = partial(select_backfill, "comment")
return observe_github_prs(repo_slug, **options)


def _persist_signal_snapshot(
Expand Down Expand Up @@ -212,7 +234,7 @@ def collect_signal_monitor(
inbox_items = _read_pending_inbox_items(
runtime_root, goal_id=goal_id, agent_id=agent_id, include_inbox=include_inbox
)
repo_snapshot = _read_repository_snapshot(todo, signal_scope, observe_github_prs)
repo_snapshot = _read_repository_snapshot(todo, signal_scope, observe_github_prs, bindings._core)
observed_at = now_utc().isoformat()
signal_request: dict[str, object] = {
"portfolio_observation": portfolio,
Expand Down
152 changes: 113 additions & 39 deletions loopx/control_plane/collaboration/steward_managed_mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1130,14 +1130,34 @@ function classifyStalledBucket(stalledAgeMs: number, authorReplyBypass: boolean)
return "under_24h";
}

type RepositoryItem = JsonObject & { number: number };

function hasReadableRepositoryItems(items: unknown[]): items is RepositoryItem[] {
const seenNumbers = new Set<number>();
for (const item of items) {
const number = jsonObject(item)?.number;
if (typeof number !== "number" || !Number.isSafeInteger(number) || number <= 0 || seenNumbers.has(number)) {
return false;
}
seenNumbers.add(number);
}
return true;
}

type RepositoryBackfillPlan = {
source: "comment" | "review";
add: (item: RepositoryItem) => void;
};

function filterScopedRepositoryItems(
rawItems: unknown[],
items: RepositoryItem[],
filter: JsonObject | null,
observedAtValue: unknown,
): { items: JsonObject[]; observationIncomplete: boolean } {
plan?: RepositoryBackfillPlan,
): { items: RepositoryItem[]; observationIncomplete: boolean } {
const minStalledHours = typeof filter?.min_stalled_hours === "number" ? filter.min_stalled_hours : null;
let observedAtMs = NaN;
if (minStalledHours !== null) {
if (minStalledHours !== null && plan?.source !== "review") {
observedAtMs = typeof observedAtValue === "string" ? Date.parse(observedAtValue) : NaN;
if (!Number.isFinite(observedAtMs)) {
throw new EffectRuntimeRequestError("scoped monitor min_stalled_hours requires a valid observed_at timestamp");
Expand All @@ -1151,77 +1171,131 @@ function filterScopedRepositoryItems(
: null;
const authorMode = typeof filter?.author_mode === "string" ? filter.author_mode : null;
const authors = Array.isArray(filter?.authors) ? new Set(filter.authors.map(String)) : null;
const canBypassAge = authorMode === "exclude";
const requiresCompleteReviews = minStalledHours !== null || effectiveVerdicts !== null
|| requiredApprovers !== null || filter?.exclude_conflicting === true;

const matched: JsonObject[] = [];
for (const rawItem of rawItems) {
const item = jsonObject(rawItem);
if (!item) continue;
const matched: RepositoryItem[] = [];
for (const item of items) {
if (filter?.exclude_drafts === true && item.isDraft === true) continue;
const reviewSummary = jsonObject(item.review_summary);
if (
filter?.exclude_conflicting === true
&& (String(item.mergeable ?? "").toUpperCase() === "CONFLICTING" || reviewSummary?.has_review_conflict === true)
&& String(item.mergeable ?? "").toUpperCase() === "CONFLICTING"
) {
continue;
}
let authorMembershipUncertain = false;
if (authorMode !== null && authors !== null) {
const login = prAuthorLogin(item);
authorMembershipUncertain = !login;
if (login && authorMode === "include" && !authors.has(login)) continue;
if (login && authorMode === "exclude" && authors.has(login)) continue;
}
if (requiresCompleteReviews && item.review_coverage_incomplete === true) {
if (plan === undefined) return { items: [], observationIncomplete: true };
if (plan.source === "review") plan.add(item);
continue;
}
if (plan?.source === "review") continue;
const reviewSummary = jsonObject(item.review_summary);
if (filter?.exclude_conflicting === true && reviewSummary?.has_review_conflict === true) continue;
if (effectiveVerdicts !== null) {
const verdict = String(reviewSummary?.effective_verdict ?? "NONE");
if (!effectiveVerdicts.has(verdict)) continue;
}
if (requiredApprovers !== null && !hasMatchingApprovedReviewerDeclaration(item, requiredApprovers)) {
continue;
}
if (authorMode !== null && authors !== null) {
const login = prAuthorLogin(item);
if (authorMode === "include" && (!login || !authors.has(login))) continue;
if (authorMode === "exclude" && login && authors.has(login)) continue;
}
let scopedItem = item;
if (minStalledHours !== null) {
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);
: (reviewSummary?.stalled_since ?? item.stalled_since);
const stalledSinceUnknown = item.stalled_since_unknown === true;
if (
hasExplicitStalledSince
&& rawStalledSince === null
!stalledSinceUnknown
&& hasExplicitStalledSince
&& rawStalledSince == null
&& effectiveVerdicts !== null
&& effectiveVerdicts.size === 1
&& effectiveVerdicts.has("REQUEST_CHANGES")
) {
continue;
}
const basisIso = stalledSinceUnknown ? null : (rawStalledSince ?? item.updatedAt);
const basisMs = typeof basisIso === "string" ? Date.parse(basisIso) : NaN;
const basisKnown = Number.isFinite(basisMs);
const thresholdMet = basisKnown && observedAtMs - basisMs >= minStalledHours * 3_600_000;
if (!canBypassAge && basisKnown && !thresholdMet) continue;

// Fail closed when comment pagination did not reach the stalled anchor or a newer
// author/maintainer reply, so evicted replies cannot drop awaiting_maintainer_reply.
const commentsCoverageIncomplete = item.comments_coverage_incomplete === true
|| reviewSummary?.comments_coverage_incomplete === true;
if (commentsCoverageIncomplete) {
return { items: [], observationIncomplete: true };
if (commentsCoverageIncomplete && (basisKnown || canBypassAge)) {
if (plan === undefined) return { items: [], observationIncomplete: true };
// Backfill cannot resolve missing creator or clock evidence.
if (!authorMembershipUncertain || (canBypassAge && basisKnown && !thresholdMet)) {
plan.add(item);
}
continue;
}
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;
const authorReplyBypass = authorReplied && canBypassAge;
if (!authorReplyBypass && !thresholdMet) {
if (!basisKnown && plan === undefined) return { items: [], observationIncomplete: true };
continue;
}
const stalledAgeMs = Number.isFinite(basisMs) ? Math.max(0, observedAtMs - basisMs) : 0;
matched.push({
const stalledAgeMs = basisKnown ? Math.max(0, observedAtMs - basisMs) : 0;
scopedItem = {
...item,
stalled_threshold_met: thresholdMet,
stalled_bucket: classifyStalledBucket(stalledAgeMs, authorReplyBypass),
});
} else {
matched.push(item);
};
}
if (authorMembershipUncertain) {
if (plan === undefined) return { items: [], observationIncomplete: true };
continue;
}
matched.push(scopedItem);
}
return { items: matched, observationIncomplete: false };
}

function planStewardSignalBackfill(params: JsonObject, source: RepositoryBackfillPlan["source"]): JsonObject {
const scope = normalizeStewardSignalMonitorScope(params.signal_scope);
const filter = jsonObject(scope?.pr_filter);
const items = params.repository_items;
if (!Array.isArray(items)) {
throw new EffectRuntimeRequestError(`${source} backfill requires repository items`);
}
if (!hasReadableRepositoryItems(items)) {
throw new EffectRuntimeRequestError(`${source} backfill requires distinct valid PR numbers`);
}
const prNumbers: number[] = [];
// The planner's cutoff includes the time still available for provider reads.
filterScopedRepositoryItems(items, filter, params.observed_at, {
source,
add: (item) => prNumbers.push(item.number),
});
return { pr_numbers: prNumbers };
}

/** Read-only selection at the same coverage gate used by scoped observation. */
export function planStewardSignalCommentBackfill(params: JsonObject): JsonObject {
return planStewardSignalBackfill(params, "comment");
}

export function planStewardSignalReviewBackfill(params: JsonObject): JsonObject {
return planStewardSignalBackfill(params, "review");
}

const AGE_FILTER_ITEM_FIELDS = [
"stalled_since",
"stalled_since_unknown",
"author_replied_after_request_changes",
"comments_coverage_incomplete",
"stalled_threshold_met",
Expand All @@ -1240,23 +1314,21 @@ function omitKeys(obj: JsonObject, keysToOmit: readonly string[]): JsonObject {
return Object.fromEntries(Object.entries(obj).filter(([key]) => !omit.has(key)));
}

function projectRepositoryItemForMaterialHash(rawItem: unknown, usesStalledAgeFilter: boolean): unknown {
const item = jsonObject(rawItem);
if (!item) return rawItem;
function projectRepositoryItemForMaterialHash(item: RepositoryItem, usesStalledAgeFilter: boolean): JsonObject {
const reviewSummary = jsonObject(item.review_summary);
if (usesStalledAgeFilter) {
const hasStalledSinceClock = typeof item.stalled_since === "string"
|| typeof reviewSummary?.stalled_since === "string";
const omittedItemFields = hasStalledSinceClock
? ["comments_coverage_incomplete", "updatedAt"]
: ["comments_coverage_incomplete"];
? ["comments_coverage_incomplete", "stalled_since_unknown", "updatedAt"]
: ["comments_coverage_incomplete", "stalled_since_unknown"];
const projectedItem = omitKeys(item, omittedItemFields);
if (reviewSummary !== null) {
projectedItem.review_summary = omitKeys(reviewSummary, ["comments_coverage_incomplete"]);
}
return projectedItem;
}
const projectedItem = omitKeys(item, AGE_FILTER_ITEM_FIELDS);
const projectedItem = omitKeys(item, [...AGE_FILTER_ITEM_FIELDS, "review_coverage_incomplete"]);
if (reviewSummary !== null) {
projectedItem.review_summary = omitKeys(reviewSummary, AGE_FILTER_REVIEW_SUMMARY_FIELDS);
}
Expand All @@ -1278,21 +1350,23 @@ export function observeStewardSignalMonitor(params: JsonObject): JsonObject {
};
const signalScope = normalizeStewardSignalMonitorScope(params.signal_scope);
const repo = params.repository_snapshot == null ? null : requireJsonObject(params.repository_snapshot, "repository signal");
if (repo !== null && repo.status === "unavailable") {
const rawItems = repo?.items;
const repoItems = Array.isArray(rawItems) && hasReadableRepositoryItems(rawItems) ? rawItems : null;
// An unreadable list must not report that PRs were removed.
if (repo !== null && (repo.status === "unavailable" || repoItems === null)) {
return incompleteObservation;
}
const portfolio = params.portfolio_observation == null ? null
: requireJsonObject(params.portfolio_observation, "portfolio observation");
const inboxItems = Array.isArray(params.inbox_items) ? params.inbox_items : [];
const rawRepoItems = repo === null ? null : (Array.isArray(repo.items) ? repo.items : []);
const prFilter = signalScope === null ? null : jsonObject(signalScope.pr_filter);
const rawMinStalledHours = prFilter?.min_stalled_hours;
const usesStalledAgeFilter = typeof rawMinStalledHours === "number"
&& Number.isFinite(rawMinStalledHours)
&& rawMinStalledHours > 0;
const scopedResult = signalScope !== null && rawRepoItems !== null
const scopedResult = signalScope !== null && repoItems !== null
? filterScopedRepositoryItems(
rawRepoItems,
repoItems,
prFilter,
params.observed_at ?? repo?.observed_at,
)
Expand All @@ -1301,7 +1375,7 @@ export function observeStewardSignalMonitor(params: JsonObject): JsonObject {
return incompleteObservation;
}
const scopedRepoItems = scopedResult === null ? null : scopedResult.items;
const baseRepoItems = scopedRepoItems ?? rawRepoItems;
const baseRepoItems = scopedRepoItems ?? repoItems;
const hashedRepoItems = baseRepoItems === null
? null
: baseRepoItems.map((item) => projectRepositoryItemForMaterialHash(item, usesStalledAgeFilter));
Expand Down
2 changes: 2 additions & 0 deletions loopx/control_plane/effect_runtime_handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,8 @@ export function createEffectRuntimeHandlers(
["collaboration.steward.report.plan", lazyHandler(() => import("./collaboration/steward_reports.ts"), ({planStewardReport}) => planStewardReport)],
["collaboration.steward.monitor.observation", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({observeStewardPortfolio}) => observeStewardPortfolio)],
["collaboration.steward.monitor.signal_observation", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({observeStewardSignalMonitor}) => observeStewardSignalMonitor)],
["collaboration.steward.monitor.comment_backfill.plan", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({planStewardSignalCommentBackfill}) => planStewardSignalCommentBackfill)],
["collaboration.steward.monitor.review_backfill.plan", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({planStewardSignalReviewBackfill}) => planStewardSignalReviewBackfill)],
["collaboration.steward.monitor.signal_scope.normalize", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({normalizeStewardSignalMonitorScope}) => (params) => ({signal_scope: normalizeStewardSignalMonitorScope(params?.signal_scope)}))],
["collaboration.session.monitor.observation", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({observeManagedWork}) => observeManagedWork)],
["collaboration.conversation.binding", lazyHandler(() => import("./collaboration/conversation_binding.ts"), ({planConversationBinding}) => planConversationBinding)],
Expand Down
Loading
Loading