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
14 changes: 14 additions & 0 deletions agents/conductors/community/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,17 @@ reply or state change still needs explicit authorization. The conductor's
bounded direct comment read leaves response state unknown on settled threads
when it cannot establish full post-settlement coverage; the Ears scan provides
the paginated evidence. Fetch full relevant comments before making a judgment.

A stale or cached snapshot turns active or unknown follow-ups into unknown, but
settled threads Ears observed as inactive (including historical follow-ups,
older than 30 days) stay quiet; scan prints the historical ones as a count.
Unknown delivery rows for Announcements and Show and tell are dropped.

## Close due

Scan passes through Ears' optional `close_due` and `awaiting_contributor_since`
and lists due threads under "Close due (21d)" with the standard message from
`PyAutoMind/policy/community_close_due.md` (`close_message` in `--json`).
`close_due` is a candidate, not a verdict: read the thread and keep it open
when our last comment did not ask the contributor for anything. The human
approves the batch once per session before any post or close.
32 changes: 31 additions & 1 deletion agents/conductors/community/_community.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,34 @@ def days_since(iso):
return round((datetime.now(timezone.utc) - then).total_seconds() / 86400, 1)


def close_message(entry):
"""The standard close message (Mind policy/community_close_due.md).

<context> and <what we asked for> are filled in by the session after
reading the thread; the human approves the batch before anything is posted.
"""
opening = (f"Hi @{entry['author']}, we're closing this for now because we haven't "
"heard back in three weeks. Nothing is lost. If you're still <context>, ")
if entry["type"] == "discussion":
return opening + ("reopen this discussion or just reply here <with what we asked for> "
"and we'll pick it up again.")
# Issue authors cannot reopen an issue a maintainer closed.
return opening + "reply here <with what we asked for> and we'll reopen it."


def build_scan(base=None):
"""Compatibility surface over Ears' published evidence; no GitHub scan."""
from _ears_feed import load
base = base or os.environ.get(
"COMMUNITY_EARS_URL", f"https://{PRIMARY_ORG.lower()}.github.io/PyAutoEars")
try:
return load(base, SELF_LOGINS, PRIMARY_ORG, HUB)
surface = load(base, SELF_LOGINS, PRIMARY_ORG, HUB)
except ValueError as exc:
fail(4, str(exc))
for entry in surface["close_due"]:
entry["days_silent"] = days_since(entry["awaiting_contributor_since"])
entry["close_message"] = close_message(entry)
return surface


def print_scan(s):
Expand Down Expand Up @@ -142,9 +161,20 @@ def print_scan(s):
for candidate in s.get('follow_up_review', []):
state = "needs review" if candidate['follow_up']['review_needed'] else "unknown; refresh/check coverage"
print(f"Follow-up: {ref_label(candidate)} — {state} (contributor reopening not required)")
if s.get('historical_follow_up'):
print(f"Historical follow-ups: {s['historical_follow_up']} (settled, >30 days; not listed)")
for delivery in s.get('follow_through', []):
owed = ' — contributor update owed' if delivery['update_owed'] is True else ''
print(f"Delivery: {delivery['discussion']} — {delivery['state']}{owed}")
if s.get('close_due'):
print(f"Close due (21d): {len(s['close_due'])} waiting on the contributor"
" — approve the batch once, then post and close (Mind policy/community_close_due.md)")
if s['stale']:
print(" snapshot is stale: re-read each thread before posting")
for e in s['close_due']:
days = f"{e['days_silent']:.0f}d" if e.get('days_silent') is not None else "?"
print(f" x {ref_label(e)} [{days} silent] @{e['author']}: {e['title'][:70]}")
print(f" {e['close_message']}")
print(f"Next action: {s['next_action']}")


Expand Down
45 changes: 43 additions & 2 deletions agents/conductors/community/_ears_feed.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

MAX_BYTES = 8 * 1024 * 1024
REPO = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\Z")
# Broadcast categories carry no request, so they never owe a delivery update.
BROADCAST = {"Announcements", "Show and tell"}


def timestamp(value):
Expand Down Expand Up @@ -80,6 +82,7 @@ def validate(snapshot, state):
if 'closed' in row and type(row['closed']) is not bool:
raise ValueError('invalid closed state')
validate_follow_up(row)
validate_close_due(row)
validate_delivery(snapshot.get('follow_through', []), snapshot['conversations'])


Expand All @@ -106,6 +109,28 @@ def validate_follow_up(row):
raise ValueError("inconsistent follow-up response")


def validate_close_due(row):
"""Optional Ears close-due observation (Mind policy/community_close_due.md)."""
if "close_due" not in row and "awaiting_contributor_since" not in row:
return
due, since = row.get("close_due"), row.get("awaiting_contributor_since")
if due is not None and type(due) is not bool:
raise ValueError("invalid close-due state")
if since is not None:
timestamp(since)
if due and (since is None or row.get("closed") or row["kind"] not in {"issue", "discussion"}):
raise ValueError("inconsistent close-due evidence")


def settled_quiet(source):
"""A settled thread Ears observed with no pending follow-up (incl. history).

A stale snapshot cannot add activity Ears never saw, so these stay quiet
rather than becoming unknown; only active or unknown candidates degrade.
"""
return source.get("follow_up", {}).get("review_needed") is False


def validate_delivery(rows, conversations):
"""Validate the optional projection without depending on an Ears checkout."""
discussions = {r['url'] for r in conversations if r['kind'] == 'discussion'}
Expand Down Expand Up @@ -162,16 +187,24 @@ def adapt(snapshot, state, self_logins, org, hub, current=None):
# unknown; do not infer a last actor or fetch comments to fill them.
since = source.get("waiting_since")
row = {k: source[k] for k in ("repo", "number", "title", "author", "url", "category", "answered", "coverage", "cached")}
current_claim = not (stale or source["cached"]) or settled_quiet(source)
row.update(type=source["kind"], closed=source.get('closed', False), labels=[], comments=None,
updated_at=None, last_actor=None,
awaiting_response=None if stale or source["cached"] else source["awaiting_response"],
awaiting_response=source["awaiting_response"] if current_claim else None,
waiting_days=round(max(0, (generated - timestamp(since)).total_seconds()) / 86400, 1) if since else None,
review_requested=source["review_requested"],
observed_awaiting_response=source["awaiting_response"])
if "follow_up" in source:
row["follow_up"] = dict(source["follow_up"],
review_needed=None if stale or source["cached"] else source["follow_up"]["review_needed"])
review_needed=source["follow_up"]["review_needed"] if current_claim else None)
row["observed_follow_up"] = source["follow_up"]
if source.get("historical_follow_up_at"):
row["historical_follow_up_at"] = source["historical_follow_up_at"]
if "close_due" in source:
# Passed through as observed; the session re-reads each thread
# before posting, so a stale snapshot only needs a refresh first.
row["close_due"] = source["close_due"]
row["awaiting_contributor_since"] = source["awaiting_contributor_since"]
rows.append(row)
discussions = [r for r in rows if r["type"] == "discussion" and not r['closed']]
issues = [r for r in rows if r["type"] == "issue" and not r["closed"]
Expand All @@ -183,10 +216,15 @@ def adapt(snapshot, state, self_logins, org, hub, current=None):
unknown = sum(r["awaiting_response"] is None or r["coverage"] != "complete" for r in rows)
if unknown:
degraded.append(f"Ears: {unknown} conversation(s) with unknown response state or incomplete coverage")
categories = {r["url"]: r["category"] for r in rows}
delivery = [dict(r, observed_state=r['state'],
state='unknown' if stale else r['state'],
update_owed=None if stale else r['update_owed'])
for r in snapshot.get('follow_through', [])]
# Announcements and Show and tell never carry delivery work; their
# "unknown" rows are noise, not a coverage gap.
delivery = [r for r in delivery
if not (r['state'] == 'unknown' and categories.get(r['discussion']) in BROADCAST)]
if any(r['state'] == 'unknown' for r in delivery):
degraded.append('Delivery evidence is incomplete; unknown is not delivered')
return {
Expand All @@ -201,6 +239,9 @@ def adapt(snapshot, state, self_logins, org, hub, current=None):
"stale": stale, "source": "ears", "coverage": receipts,
"follow_through": delivery,
"follow_up_review": [r for r in rows if "follow_up" in r and r["follow_up"]["review_needed"] is not False],
"historical_follow_up": sum(bool(r.get("historical_follow_up_at")) for r in rows),
"close_due": sorted([r for r in rows if r.get("close_due") is True],
key=lambda r: r["awaiting_contributor_since"]),
"valid_until": state["valid_until"],
"next_action": "Use community triage <ref> to assess context and draft a reply for human approval; this surface posts nothing",
}
Expand Down
29 changes: 29 additions & 0 deletions skills/community/community.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,35 @@ never post or promise a release automatically, and never reopen a settled
Discussion because implementation continued. Follow Ears' REFERENCE.md for
explicit maintainer `Delivery-*` evidence links; these are links, not task state.

## Close due

A thread where we spoke last and the contributor has been silent for 21 days
is closed with a standard message. The rule and the message are in
`PyAutoMind/policy/community_close_due.md`; it never applies to a thread
waiting on us.

1. The scan's **Close due (21d)** section lists Ears' `close_due` candidates,
each with the message prefilled (`close_message` in `--json`). A stale
snapshot needs a refresh, or a re-read of each thread, before posting.
2. Read each thread. Drop any where our last comment did not ask the
contributor for something (an accepted idea, "we'll look at this"). Fill in
`<context>` and `<with what we asked for>`.
3. Present the batch; the human approves it once for the session.
4. Post and close each one from a local CLI:
- Discussion: get the node id, then

```bash
gh api graphql -f query='mutation($d: ID!, $b: String!) {
addDiscussionComment(input:{discussionId:$d, body:$b}) { comment { url } } }' \
-f d=<discussion id> -f b="$(cat message.md)"
gh api graphql -f query='mutation { closeDiscussion(input:{discussionId:"<discussion id>", reason:OUTDATED}) {
discussion { closed stateReason } } }'
```

- Issue: `gh issue close <n> -R <owner/repo> --reason "not planned" --comment "$(cat message.md)"`

No Action or timer closes threads, and nothing is posted without that approval.

## Boundary

- **Hears and drafts; the human speaks.** Every outward message is presented
Expand Down
81 changes: 81 additions & 0 deletions tests/test_ears_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,84 @@ def test_invalid_followup_fails_closed(field, value):
r = followup_row(); r['follow_up'][field] = value
with pytest.raises((ValueError, TypeError, AttributeError)):
adapt(*evidence([r]))


def historical_row(kind='issue', number=5, **extra):
r = row(kind, number, closed=True, awaiting=False, waiting_since=None,
answered=kind == 'discussion', category='Help & Questions' if kind == 'discussion' else '',
**extra)
r['follow_up'] = {'review_needed': False, 'since': None, 'url': None}
r['historical_follow_up_at'] = '2019-06-01T00:00:00Z'
return r


@pytest.mark.parametrize('cached,stale', [(False, False), (True, False), (False, True)])
def test_stale_or_cached_history_stays_quiet(cached, stale):
rows = [historical_row(cached=cached), historical_row('discussion', 6, cached=cached)]
rows[1].pop('historical_follow_up_at') # settled, inactive, not yet historical
snapshot, state = evidence(rows)
if stale: state['status'] = 'stale'
s = adapt(snapshot, state)
assert s['follow_up_review'] == []
assert s['historical_follow_up'] == 1
assert s['counts']['unknown'] == 0


def test_stale_scan_prints_history_as_a_count_only(tmp_path):
feed = tmp_path / 'feed'
base = write_feed(feed, [historical_row(), followup_row('issue', number=9)])
state = json.loads((feed / 'state.json').read_text()); state['status'] = 'stale'
(feed / 'state.json').write_text(json.dumps(state))
result = subprocess.run([str(BRAIN / "bin/pyauto-brain"), "community", "scan"],
env={**os.environ, "COMMUNITY_EARS_URL": base, "COMMUNITY_GH": "/missing/gh"},
capture_output=True, text=True)
assert result.returncode == 0, result.stderr
assert 'Historical follow-ups: 1 (settled, >30 days; not listed)' in result.stdout
assert result.stdout.count('Follow-up:') == 1 # the active candidate, now unknown
assert 'RepoA#5' not in result.stdout


@pytest.mark.parametrize('category,kept', [('Announcements', False), ('Show and tell', False),
('Ideas & Proposals', True)])
def test_broadcast_unknown_delivery_is_filtered(category, kept):
discussion = row('discussion', awaiting=False, category=category)
snapshot, state = evidence([discussion])
snapshot['follow_through'] = [{'discussion': discussion['url'], 'state': 'unknown',
'update_owed': None, 'evidence': [], 'gaps': ['no link']}]
s = adapt(snapshot, state)
assert bool(s['follow_through']) is kept
assert any('Delivery evidence' in d for d in s['degraded']) is kept


def close_due_row(kind='discussion', number=7, due=True, since='2026-01-01T00:00:00Z'):
return row(kind, number, awaiting=False, waiting_since=None, category='Help & Questions',
close_due=due, awaiting_contributor_since=since)


def test_close_due_passes_through_with_the_standard_message(tmp_path):
rows = [close_due_row(), close_due_row('issue', 8), close_due_row('issue', 9, due=False)]
s = adapt(*evidence(rows))
assert [r['number'] for r in s['close_due']] == [7, 8]
base = write_feed(tmp_path / 'feed', rows)
result = subprocess.run([str(BRAIN / "bin/pyauto-brain"), "community", "scan", "--json"],
env={**os.environ, "COMMUNITY_EARS_URL": base, "COMMUNITY_GH": "/missing/gh"},
capture_output=True, text=True)
assert result.returncode == 0, result.stderr
due = json.loads(result.stdout)['close_due']
assert due[0]['close_message'].startswith("Hi @visitor, we're closing this for now")
assert 'reopen this discussion or just reply here' in due[0]['close_message']
assert "reply here <with what we asked for> and we'll reopen it." in due[1]['close_message']
assert due[0]['days_silent'] > 21


def test_snapshots_without_close_due_have_an_empty_section():
s = adapt(*evidence([row()]))
assert s['close_due'] == [] and s['historical_follow_up'] == 0


@pytest.mark.parametrize('change', [{'close_due': 'yes'}, {'awaiting_contributor_since': 'soon'},
{'awaiting_contributor_since': None}])
def test_invalid_close_due_fails_closed(change):
r = close_due_row(); r.update(change)
with pytest.raises(ValueError):
adapt(*evidence([r]))
Loading