Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
0496bc7
fix(kanban): auto-derive babysit idempotency key in create_task to st…
exiao Jun 30, 2026
c5935ae
fix(kanban): derive babysit key after board-default workspace resolves
exiao Jun 30, 2026
5925bd7
fix(kanban): pull-URL PR number is authoritative over title #ref
exiao Jun 30, 2026
57b2553
fix(kanban): normalize blank idempotency_key to None before babysit d…
exiao Jun 30, 2026
194f11e
fix(kanban): resolve slug for pending worktree targets in babysit key
exiao Jun 30, 2026
7286eb9
fix(kanban): parse owner/repo#<n> ref as a babysit slug+PR source
exiao Jun 30, 2026
43b4416
fix(kanban): lowercase babysit repo slug for case-insensitive dedup
exiao Jun 30, 2026
9774a21
fix(kanban): canonicalize explicit babysit keys + prefer PR# over issue#
exiao Jun 30, 2026
3d0a7a9
fix(kanban): only derive babysit slug from GitHub remotes
exiao Jun 30, 2026
3a354b6
fix(kanban): migrate legacy mixed-case babysit keys to canonical form
exiao Jun 30, 2026
7ba776d
fix(kanban): derive babysit PR number from body, not just title
exiao Jun 30, 2026
29619a0
fix(kanban): anchor github host and strip .git in babysit pull-URL slug
exiao Jun 30, 2026
c284348
fix(kanban): scope babysit ref precedence so body shorthand can't ove…
exiao Jun 30, 2026
a258610
fix(kanban): title-vs-body scope the babysit URL source too (full pre…
exiao Jun 30, 2026
2045882
fix(kanban): accept authenticated GitHub remotes when deriving babysi…
exiao Jun 30, 2026
b7964df
fix(kanban): rank body pull URL above a bare title #n in babysit deri…
exiao Jun 30, 2026
d822940
fix(kanban): exclude github subdomains from babysit pull-URL host anchor
exiao Jun 30, 2026
4e28ada
fix(kanban): body PR#n over bare title #n + key default-assigned baby…
exiao Jun 30, 2026
8494550
fix(kanban): bare title #n is strictly last in babysit precedence (on…
exiao Jun 30, 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
132 changes: 115 additions & 17 deletions hermes_cli/kanban_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2385,6 +2385,83 @@ def _canonical_assignee(assignee: Optional[str]) -> Optional[str]:
return normalize_profile_name(assignee)


def _slug_from_git_remote(workspace_path: Optional[str]) -> Optional[str]:
"""Resolve a checkout/worktree path to its ``owner/repo`` GitHub slug via the
git ``origin`` remote. Returns ``None`` when the path is empty, not a git
repo, or the remote URL doesn't parse. Mirrors ``_slug_from_worktree`` in
``~/.hermes/scripts/babysit-pr-detector.py``.
"""
if not workspace_path or not os.path.isdir(workspace_path):
return None
Comment thread
exiao marked this conversation as resolved.
Resolved
Comment thread
exiao marked this conversation as resolved.
Resolved
try:
p = subprocess.run(
["git", "-C", workspace_path, "remote", "get-url", "origin"],
capture_output=True,
text=True,
timeout=10,
)
except (subprocess.SubprocessError, OSError):
return None
if p.returncode != 0:
return None
m = re.search(r"[:/]([^/:]+/[^/]+?)(?:\.git)?/?$", p.stdout.strip())
Comment thread
exiao marked this conversation as resolved.
Resolved
return m.group(1) if m else None
Comment on lines +2450 to +2455

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Accept authenticated GitHub remotes when deriving keys

For worktrees whose origin uses an authenticated HTTPS URL such as https://x-access-token:...@github.com/owner/repo.git, this regex does not match because it requires github.com immediately after the scheme. In that private-repo/CI setup _slug_from_git_remote() returns None, so pr-babysitter tasks titled only PR #<n> never get the canonical key and the duplicate-ticket fix is bypassed; allow optional userinfo before github.com.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2045882: _slug_from_git_remote now allows optional userinfo before github.com, so https://x-access-token:TOKEN@github.com/owner/repo.git resolves. Red/green test covers authenticated github remotes and confirms userinfo doesn't loosen the host check (authed gitlab still yields None).



def _derive_babysit_idempotency_key(
title: Optional[str],
body: Optional[str],
workspace_path: Optional[str],
) -> Optional[str]:
"""Derive a canonical ``babysit:<owner>/<repo>#<pr>`` idempotency key for a
pr-babysitter task, so EVERY creation path (the detector cron, the
``kanban_create`` tool, sibling handoffs) dedups against the same PR — not
just the detector that already sets its own key.

Extraction precedence (most reliable first), per the patch note:
* PR number: first ``#(\\d+)`` in ``title``, else a
``github.com/.../pull/(\\d+)`` url in ``title``/``body``.
* Repo slug: a ``github.com/<owner>/<repo>/pull/...`` url in title/body
(most authoritative), else the workspace git remote resolved to
``owner/repo``.

Returns the key only when BOTH a slug and a PR number resolve; otherwise
``None`` — a wrong key is worse than none (PR numbers collide across repos,
so a repo-less key would wrongly cross-dedup #70 in one repo against #70 in
another). When this returns ``None`` the caller leaves the key unset and
behavior is identical to today (no dedup, task still creates).
"""
title = title or ""
body = body or ""

# PR number + repo slug from a github pull-request URL anywhere in the
# title/body (authoritative for both pieces when present).
url_pr: Optional[int] = None
url_slug: Optional[str] = None
um = re.search(
r"github\.com/([^/\s]+/[^/\s]+)/pull/(\d+)",
f"{title}\n{body}",
)
if um:
url_slug = um.group(1)
url_pr = int(um.group(2))

# PR number: prefer the bare ``#<n>`` in the title (the detector's title
# convention), fall back to the pull-URL number.
tm = re.search(r"#(\d+)", title)
pr = int(tm.group(1)) if tm else url_pr
Comment thread
exiao marked this conversation as resolved.
Resolved
if pr is None:
return None

# Repo slug: the pull URL is the most authoritative; otherwise resolve the
# workspace git remote.
slug = url_slug or _slug_from_git_remote(workspace_path)
Comment thread
exiao marked this conversation as resolved.
Resolved
if not slug:
return None

return f"babysit:{slug}#{pr}"
Comment thread
exiao marked this conversation as resolved.
Resolved


# Bare placeholder titles that carry no spec on their own. A task whose title is
# one of these (or the literal "<assignee> task" / the assignee name itself) AND
# whose body is empty has no work in it — it must never reach a worker lane in
Expand Down Expand Up @@ -2621,23 +2698,6 @@ def create_task(
)
skills_list = cleaned

# Idempotency check — return the existing task instead of creating a
# duplicate. Done BEFORE entering write_txn to keep the fast path fast
# and to avoid holding a write lock during the lookup. Race is
# acceptable: two concurrent creators with the same key might both
# insert, at which point both rows exist but the next lookup stabilises.
if idempotency_key:
row = conn.execute(
"SELECT id FROM tasks WHERE idempotency_key = ? "
"AND status != 'archived' "
"ORDER BY created_at DESC LIMIT 1",
(idempotency_key,),
).fetchone()
if row:
return row["id"]

now = int(time.time())

# Resolve workspace_path from board-level default_workdir when the
# caller did not specify one explicitly. Board defaults represent
# persistent project checkouts, so only persistent workspace kinds may
Expand All @@ -2647,6 +2707,14 @@ def create_task(
# task would point cleanup at the user's source tree (#28818). The
# containment guard in ``_cleanup_workspace`` is the safety rail, but
# we also stop the bad state from being created in the first place.
#
# This runs BEFORE the babysit-key derivation below so that a
# pr-babysitter task relying on a board ``default_workdir`` (the common
# ``workspace_kind='worktree'`` + board-default create path) has its
# repo path resolved in time to derive the canonical babysit key from
# the git remote — otherwise ``workspace_path`` is still ``None`` at
# derive time, the key is left unset, and two creates for the same PR
# insert two non-idempotent rows.
if (
workspace_path is None
and project_repo is None
Expand All @@ -2665,6 +2733,36 @@ def create_task(
else:
workspace_path = str(board_default)

# Auto-derive a canonical babysit idempotency key so EVERY pr-babysitter
# creation path dedups against the same PR, not just the detector cron that
# sets its own key. Done AFTER _canonical_assignee (so a pr-babysitter alias
# is still caught) and only when the caller passed no explicit key — when the
# key can't be derived it stays None and behavior is identical to today.
# ``workspace_path or project_repo`` feeds the git-remote slug fallback both
# the board-default-resolved path (above) and a project-linked task's primary
# repo, so the key resolves for every persistent-workspace babysitter create.
if idempotency_key is None and assignee == "pr-babysitter":
Comment thread
exiao marked this conversation as resolved.
Resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle default-assigned babysitter tasks

When operators rely on kanban.default_assignee = pr-babysitter, create_task stores the row with assignee unset and the dispatcher later applies the default assignment, so this condition skips key derivation for those cards. Two unassigned Babysit PR #70 creates will both insert with no idempotency key and then become pr-babysitter tickets, recreating the duplicate-ticket path this change is meant to close; use the effective assignee (explicit or default) for this check.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both fixed in 4e28ada: (1) body PR #n now outranks a bare title #n (moved above title_bare, same as the body-URL rule); (2) the derive guard now uses the effective assignee (explicit or kanban.default_assignee) so default-assigned babysitter cards get keyed at create time. Red/green tests for both.

idempotency_key = _derive_babysit_idempotency_key(
title, body, workspace_path or project_repo
)

# Idempotency check — return the existing task instead of creating a
# duplicate. Done BEFORE entering write_txn to keep the fast path fast
# and to avoid holding a write lock during the lookup. Race is
# acceptable: two concurrent creators with the same key might both
# insert, at which point both rows exist but the next lookup stabilises.
if idempotency_key:
row = conn.execute(
"SELECT id FROM tasks WHERE idempotency_key = ? "
"AND status != 'archived' "
"ORDER BY created_at DESC LIMIT 1",
(idempotency_key,),
Comment thread
exiao marked this conversation as resolved.
Resolved
Comment on lines +2889 to +2892

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Match legacy babysit keys canonically

For boards that already contain pr-babysitter rows created before this canonicalization, the incoming key is now lowercased but the lookup still compares idempotency_key byte-for-byte. A pre-existing row such as babysit:NousResearch/hermes-agent#70 will not be found by a later derived babysit:nousresearch/hermes-agent#70, so create_task inserts another ticket for the same PR instead of deduping until the stored rows are migrated or the babysit lookup normalizes both sides.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3a354b6: added a one-shot canonicalization pass in _migrate_add_optional_columns that normalizes legacy mixed-case babysit: keys in-place, so a pre-existing babysit:NousResearch/hermes-agent#70 row migrates to the canonical lowercased form and the byte-for-byte dedup lookup matches a later derived key. Red/green regression test added (test_legacy_mixed_case_babysit_key_migrated_and_dedups).

).fetchone()
if row:
return row["id"]

now = int(time.time())

# Retry once on the extremely unlikely id collision.
for attempt in range(2):
task_id = _new_task_id()
Expand Down
171 changes: 171 additions & 0 deletions tests/hermes_cli/test_kanban_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2508,6 +2508,177 @@ def test_worktree_explicit_path_succeeds_control(kanban_home, tmp_path):
assert task.workspace_path == str(repo)


# ---------------------------------------------------------------------------
# Auto-derived babysit idempotency key (stop duplicate pr-babysitter tickets)
# ---------------------------------------------------------------------------

def _set_origin_remote(repo: Path, slug: str) -> None:
"""Point ``repo``'s origin remote at a github ``owner/repo`` slug so
``_slug_from_git_remote`` can resolve it."""
subprocess.run(
["git", "-C", str(repo), "remote", "add", "origin",
f"https://github.com/{slug}.git"],
check=True, capture_output=True, text=True,
)


def test_babysit_same_pr_same_repo_dedups(kanban_home, tmp_path):
"""Two pr-babysitter creates for the same PR #70 in the same repo with NO
explicit key dedup to ONE row — the second returns the first task's id.

Fails before the auto-derive change (two distinct rows).
"""
repo = tmp_path / "hermes-agent"
_init_git_repo(repo)
_set_origin_remote(repo, "exiao/hermes-agent")
with kb.connect() as conn:
first = kb.create_task(
conn,
title="Babysit hermes-agent PR #70",
assignee="pr-babysitter",
workspace_kind="worktree",
workspace_path=str(repo),
)
second = kb.create_task(
conn,
title="hermes-agent#70: re-check the flaky CI",
assignee="pr-babysitter",
workspace_kind="worktree",
workspace_path=str(repo),
)
assert second == first
rows = conn.execute(
"SELECT COUNT(*) FROM tasks WHERE assignee = 'pr-babysitter'"
).fetchone()[0]
assert rows == 1
with kb.connect() as conn:
task = kb.get_task(conn, first)
assert task is not None
assert task.idempotency_key == "babysit:exiao/hermes-agent#70"


def test_babysit_dedups_via_board_default_workdir(kanban_home, tmp_path):
"""Two pr-babysitter worktree creates for the same PR that supply NO
explicit ``workspace_path`` and rely on the board ``default_workdir`` to
anchor the repo still dedup to ONE row.

This is the common ``workspace_kind='worktree'`` + board-default create
path. The babysit key must be derived AFTER the board default resolves the
repo path — otherwise ``workspace_path`` is None at derive time, the key is
left unset, and the two creates insert two non-idempotent rows.

Fails before the move (key derived too early → 2 rows).
"""
repo = tmp_path / "hermes-agent"
_init_git_repo(repo)
_set_origin_remote(repo, "exiao/hermes-agent")
kb.create_board("babysit-default-board", default_workdir=str(repo))
with kb.connect(board="babysit-default-board") as conn:
first = kb.create_task(
conn,
title="Babysit hermes-agent PR #70",
assignee="pr-babysitter",
workspace_kind="worktree",
board="babysit-default-board",
)
second = kb.create_task(
conn,
title="hermes-agent#70: re-check the flaky CI",
assignee="pr-babysitter",
workspace_kind="worktree",
board="babysit-default-board",
)
assert second == first
rows = conn.execute(
"SELECT COUNT(*) FROM tasks WHERE assignee = 'pr-babysitter'"
).fetchone()[0]
task = kb.get_task(conn, first)
assert rows == 1
assert task is not None
assert task.idempotency_key == "babysit:exiao/hermes-agent#70"


def test_slug_from_git_remote_skips_missing_path(tmp_path):
"""``_slug_from_git_remote`` returns None without spawning a git subprocess
when the path does not exist or is not a directory (gemini high finding)."""
missing = tmp_path / "does-not-exist"
assert kb._slug_from_git_remote(str(missing)) is None
a_file = tmp_path / "afile"
a_file.write_text("x", encoding="utf-8")
assert kb._slug_from_git_remote(str(a_file)) is None
assert kb._slug_from_git_remote(None) is None
assert kb._slug_from_git_remote("") is None


def test_babysit_same_pr_different_repos_no_cross_dedup(kanban_home, tmp_path):
"""The SAME PR number #70 in two DIFFERENT repos creates two distinct
tasks — PR numbers collide across repos, so a repo-less key must never
cross-dedup."""
repo_a = tmp_path / "hermes-agent"
_init_git_repo(repo_a)
_set_origin_remote(repo_a, "exiao/hermes-agent")
repo_b = tmp_path / "research-agent"
_init_git_repo(repo_b)
_set_origin_remote(repo_b, "cpe-research/research-agent")
with kb.connect() as conn:
a = kb.create_task(
conn,
title="Babysit hermes-agent PR #70",
assignee="pr-babysitter",
workspace_kind="worktree",
workspace_path=str(repo_a),
)
b = kb.create_task(
conn,
title="Babysit research-agent PR #70",
assignee="pr-babysitter",
workspace_kind="worktree",
workspace_path=str(repo_b),
)
assert a != b
ta = kb.get_task(conn, a)
tb = kb.get_task(conn, b)
assert ta is not None and tb is not None
assert ta.idempotency_key == "babysit:exiao/hermes-agent#70"
assert tb.idempotency_key == "babysit:cpe-research/research-agent#70"


def test_babysit_explicit_key_respected_unchanged(kanban_home, tmp_path):
"""An explicit idempotency_key passed by the caller (e.g. the detector
cron) is stored verbatim and the auto-derive does NOT override it."""
repo = tmp_path / "hermes-agent"
_init_git_repo(repo)
_set_origin_remote(repo, "exiao/hermes-agent")
with kb.connect() as conn:
tid = kb.create_task(
conn,
title="Babysit hermes-agent PR #70",
assignee="pr-babysitter",
workspace_kind="worktree",
workspace_path=str(repo),
idempotency_key="babysit:explicit/override#999",
)
task = kb.get_task(conn, tid)
assert task is not None
assert task.idempotency_key == "babysit:explicit/override#999"


def test_babysit_unresolvable_leaves_key_none(kanban_home, tmp_path):
"""A pr-babysitter task whose title/body/workspace yield no (slug, pr)
pair leaves the key None and still creates the task (no regression)."""
# No PR number in the title and no resolvable repo slug (scratch workspace,
# no git remote) → key cannot be derived.
with kb.connect() as conn:
tid = kb.create_task(
conn,
title="Babysit something with no PR reference",
assignee="pr-babysitter",
)
task = kb.get_task(conn, tid)
assert task is not None
assert task.idempotency_key is None


def test_worktree_explicit_non_repo_path_raises_at_create(kanban_home, tmp_path, monkeypatch):
"""Fail-fast (t_f19db0e0): a ``worktree`` task whose explicit path is a real
directory that is NOT a git repo (e.g. an umbrella dir like
Expand Down
Loading